Skip to main content

dig_node_control_interface/
method.rs

1//! The canonical control-method catalog.
2//!
3//! [`ControlMethod`] enumerates every method a client can send to a running dig-node's CONTROL
4//! plane, its stable wire name, whether it requires the local control token, whether it is a
5//! pairing-administration method (which requires the MASTER token specifically), and how the node
6//! routes it (owned by the service shell, delegated to the embedded node engine, or an open
7//! pairing-bootstrap method reachable without a token).
8//!
9//! This is the SINGLE source of truth for "what can be controlled". The node dispatchers, the
10//! client SDKs (CLI `dign`, the extension, dig-app, hub), the OpenRPC/discovery surface, and the
11//! conformance KATs all read this one table, so the method set can never drift between them.
12//!
13//! Mirrors the live dig-node surface: the shell-owned methods in
14//! `dig-node-service/src/control.rs` (`CONTROL_METHODS`) plus the peer/subscription methods
15//! delegated to `dig-node-core` (`control.peerStatus` / `control.peers.*` / `control.subscribe`
16//! / `control.unsubscribe` / `control.listSubscriptions`), and the two OPEN pairing-bootstrap
17//! methods (`pairing.request` / `pairing.poll`) a token-less MV3 extension uses to obtain a
18//! scoped token after local operator approval.
19
20/// How the node resolves a control method — the routing source of truth.
21#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub enum Routing {
23    /// Answered by the dig-node service shell itself (config/status/cache/pins/sync/updater/pairing-admin).
24    Owned,
25    /// Delegated to the embedded dig-node engine's own control surface (peers + subscriptions).
26    Delegated,
27    /// An OPEN bootstrap method reachable WITHOUT the control token (pairing handshake).
28    OpenBootstrap,
29}
30
31/// The functional area a control method belongs to — for grouping in UIs and docs.
32///
33/// `#[non_exhaustive]` so adding a category in a minor release is additive; downstream matches must
34/// carry a `_ => …` arm. A new method often arrives with a new area, so this enum grows on the same
35/// cadence as [`ControlMethod`] and needs the same guarantee.
36#[non_exhaustive]
37#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
38pub enum Category {
39    /// Node status snapshot.
40    Status,
41    /// Node configuration (upstream override).
42    Config,
43    /// Live log-level control.
44    Log,
45    /// On-disk content cache.
46    Cache,
47    /// Hosted/pinned stores.
48    HostedStores,
49    /// §21 authenticated whole-store sync.
50    Sync,
51    /// The DIG auto-update beacon proxy.
52    Updater,
53    /// Control-token pairing lifecycle.
54    Pairing,
55    /// The L7 peer network: the live pool snapshot, the per-network peer counts, and dial/drop.
56    Peers,
57    /// The node's subscribed-store set.
58    Subscriptions,
59    /// Wallet chain transport: the read-only chain views (balance, coins, one coin by id, peak,
60    /// sync status) plus the push of an already-signed spend bundle.
61    Wallet,
62    /// The automated-spend AUDIT record: what this node signed WITHOUT per-transaction approval.
63    /// Read-only; nothing in this category initiates, signs or alters a spend.
64    Spends,
65    /// dig-profile BODIES: handing the node the bytes a confirmed on-chain root commits to, and
66    /// reading one back. The chain root itself is never written here -- dig-app signs and pushes
67    /// that (§908); this category moves only the bytes an already-confirmed root commits to.
68    Profile,
69    /// Mirror-collateral: this epoch's derived per-store requirement, the node's LOCAL safety
70    /// margin over it, and the per-`(store, root)` state of the bonds this node actually holds. The requirement is consensus-derived and read-only here; the margin is an
71    /// operator preference this node owns and MUST NOT let into any census or signal.
72    Collateral,
73}
74
75/// A dig-node CONTROL method.
76///
77/// `#[non_exhaustive]` so adding a method in a minor release is additive; downstream matches must
78/// carry a `_ => …` arm. Convert to/from the wire name with [`ControlMethod::name`] /
79/// [`ControlMethod::from_name`].
80#[non_exhaustive]
81#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
82pub enum ControlMethod {
83    // ---- Status / config / log (shell-owned) ----
84    /// `control.status` — a rich node status snapshot.
85    Status,
86    /// `control.config.get` — the node's effective configuration.
87    ConfigGet,
88    /// `control.config.setUpstream` — persist an upstream-RPC override (effective on restart).
89    ConfigSetUpstream,
90    /// `control.config.setMirrorAdvertiseUrls` — override (or clear) the URLs this node
91    /// advertises in its mirror-coin memos (dig-node#562). The result states whether that took
92    /// effect immediately or needs a restart — see [`crate::results::SetMirrorAdvertiseUrlsResult`].
93    ConfigSetMirrorAdvertiseUrls,
94    /// `control.log.setLevel` — live-swap the running node's tracing level filter.
95    LogSetLevel,
96
97    // ---- Cache (shell-owned) ----
98    /// `control.cache.get` — the on-disk cache view (cap/used/dir/shared).
99    CacheGet,
100    /// `control.cache.setCap` — set the cache size cap (floored at 64 MiB).
101    CacheSetCap,
102    /// `control.cache.clear` — delete all locally cached content.
103    CacheClear,
104
105    // ---- Hosted stores (shell-owned) ----
106    /// `control.hostedStores.list` — every held/pinned store with its cached capsules.
107    HostedStoresList,
108    /// `control.hostedStores.pin` — pin a store (and pre-fetch when a root is given).
109    HostedStoresPin,
110    /// `control.hostedStores.unpin` — unpin a store and evict its cached capsules.
111    HostedStoresUnpin,
112    /// `control.hostedStores.status` — per-store pinned flag + cached capsules.
113    HostedStoresStatus,
114    /// `control.capsule.fetch` — start (or report already-cached) a P2P whole-capsule pull for
115    /// one store+root, over the recursive discover-then-dial path rather than the §21 HTTP sync.
116    CapsuleFetch,
117
118    // ---- §21 sync (shell-owned) ----
119    /// `control.sync.status` — whether authenticated whole-store sync is available + pin coverage.
120    SyncStatus,
121    /// `control.sync.trigger` — trigger a §21 sync for one capsule (storeId + root).
122    SyncTrigger,
123
124    // ---- Updater beacon proxy (shell-owned) ----
125    /// `control.updater.status` — the DIG auto-update beacon's current status.
126    UpdaterStatus,
127    /// `control.updater.setChannel` — set the beacon's update channel.
128    UpdaterSetChannel,
129    /// `control.updater.pause` — suspend auto-updates (optionally until a unix time).
130    UpdaterPause,
131    /// `control.updater.resume` — resume auto-updates.
132    UpdaterResume,
133    /// `control.updater.checkNow` — force an immediate update check.
134    UpdaterCheckNow,
135
136    // ---- Pairing administration (shell-owned, MASTER-token only) ----
137    /// `control.pairing.list` — list pending pairing requests + issued paired tokens.
138    PairingList,
139    /// `control.pairing.approve` — approve a pending pairing, minting a scoped token.
140    PairingApprove,
141    /// `control.pairing.revoke` — revoke an issued paired token.
142    PairingRevoke,
143
144    // ---- Peers (delegated to the engine) ----
145    /// `control.peerStatus` — live peer-pool + relay-reservation snapshot.
146    PeerStatus,
147    /// `control.peerCounts` — how many peers this node holds on EACH network (DIG and Chia).
148    PeerCounts,
149    /// `control.peers.connect` — dial a peer by address / resolve a connected peer_id.
150    PeersConnect,
151    /// `control.peers.disconnect` — drop a pooled peer by peer_id.
152    PeersDisconnect,
153
154    // ---- Trusted CHIA full-node peers (shell-owned) ----
155    //
156    // A DIFFERENT network from `control.peers.*` above, which are DIG gossip peers. These name
157    // Chia full nodes the wallet replica will TRUST, and trust here is a real cost: NC-12 makes
158    // dialled peers untrusted precisely so that agreement across several concurrently-queried
159    // peers is what makes a read safe. A trusted peer is exempted from that agreement, so a wrong
160    // or hostile one is believed on its own. Every surface that offers these MUST say so.
161    //
162    // Trust comes from the operator declaring a node THEIR OWN — that is the whole of the
163    // authorisation, and the wording everywhere in this crate says exactly that. It is not
164    // "a node you vouch for": the unbounded authority a trusted peer holds is justified by the
165    // operator controlling both ends, which is false of a stranger's node however well
166    // recommended. A person can be talked into vouching for an address; they cannot be talked
167    // into believing they run it.
168    /// `control.chiaPeers.add` — trust a Chia full node you RUN, bypassing corroboration for it.
169    ChiaPeersAdd,
170    /// `control.chiaPeers.list` — the trusted Chia full-node peers this node tracks.
171    ChiaPeersList,
172    /// `control.chiaPeers.remove` — stop trusting a Chia full node (optionally banning it).
173    ChiaPeersRemove,
174
175    // ---- Subscriptions (delegated to the engine) ----
176    /// `control.subscribe` — subscribe the node to a store (watch + gap-fill).
177    Subscribe,
178    /// `control.unsubscribe` — stop watching a store.
179    Unsubscribe,
180    /// `control.listSubscriptions` — the node's persisted subscription set.
181    ListSubscriptions,
182
183    // ---- Wallet chain transport (delegated to the engine) ----
184    /// `control.wallet.balance` — read an address's confirmed spendable balance for an asset.
185    WalletBalance,
186    /// `control.wallet.coins` — read an address's spendable coin records for an asset.
187    WalletCoins,
188    /// `control.wallet.coinById` — read ONE coin record by coin id, spent or unspent.
189    WalletCoinById,
190    /// `control.wallet.coinSpend` — read the SPEND that spent a coin (puzzle reveal + solution).
191    WalletCoinSpend,
192    /// `control.wallet.coinsByParent` — read the direct children a coin's spend created (one hop).
193    WalletCoinsByParent,
194    /// `control.wallet.arrivals` — read confirmed INCOMING funds since a cursor position.
195    WalletArrivals,
196    /// `control.wallet.operatorAddress` — read the address of the node's OWN machine wallet.
197    WalletOperatorAddress,
198    /// `control.wallet.peak` — read the node's current chain peak height.
199    WalletPeak,
200    /// `control.wallet.syncStatus` — read whether the wallet's chain replica is being kept current.
201    WalletSyncStatus,
202    /// `control.wallet.broadcast` — push an ALREADY-SIGNED spend bundle to the network.
203    WalletBroadcast,
204    /// `control.wallet.watch` — enrol PUBLIC keys for the node's chain replica to follow.
205    WalletWatch,
206    /// `control.wallet.unwatch` — deregister enrolled public keys, so the following stops.
207    WalletUnwatch,
208    /// `control.wallet.watched` — list the public keys currently enrolled.
209    WalletWatched,
210    /// `control.wallet.reservations.held` — read which coins are committed to in-flight spends.
211    WalletReservationsHeld,
212    /// `control.wallet.reservations.reserve` — atomically hold coins, all of them or none.
213    WalletReservationsReserve,
214    /// `control.wallet.reservations.release` — free a hold now, ahead of its TTL.
215    WalletReservationsRelease,
216    /// `control.wallet.resetCoinDb` — discard the cached coin database and re-sync from chain.
217    WalletResetCoinDb,
218
219    // ---- Automated-spend audit record (shell-owned) ----
220    /// `control.spends.list` — read the record of spends this node made WITHOUT asking.
221    SpendsList,
222
223    // ---- Mirror collateral (shell-owned) ----
224    /// `control.collateral.requirement` -- this epoch's per-store collateral requirement.
225    CollateralRequirement,
226    /// `control.collateral.margin.get` -- read the node's local safety margin, in basis points.
227    CollateralMarginGet,
228    /// `control.collateral.margin.set` -- set the node's local safety margin, in basis points.
229    CollateralMarginSet,
230    /// `control.collateral.buffer` -- the $DIG this node recommends holding, and its funding state.
231    CollateralBuffer,
232    /// `control.mirror.bondStates` -- the per-`(store, root)` mirror bond state, and the $DIG
233    /// those bonds have locked.
234    MirrorBondStates,
235
236    // ---- dig-profile bodies (delegated to the engine) ----
237    /// `control.profile.putBody` — hand the node the profile body a CONFIRMED chain root commits to.
238    ProfilePutBody,
239    /// `control.profile.getBody` — read back the profile body this node holds at a given root.
240    ProfileGetBody,
241
242    // ---- Pairing bootstrap (OPEN — no token) ----
243    /// `pairing.request` — request a control-token pairing (returns a code to compare).
244    PairingRequest,
245    /// `pairing.poll` — poll a pairing; once the operator approves, returns the scoped token once.
246    PairingPoll,
247}
248
249impl ControlMethod {
250    /// The stable JSON-RPC wire name. Never derived from anything else — the published contract.
251    pub const fn name(self) -> &'static str {
252        match self {
253            ControlMethod::Status => "control.status",
254            ControlMethod::ConfigGet => "control.config.get",
255            ControlMethod::ConfigSetUpstream => "control.config.setUpstream",
256            ControlMethod::ConfigSetMirrorAdvertiseUrls => "control.config.setMirrorAdvertiseUrls",
257            ControlMethod::LogSetLevel => "control.log.setLevel",
258            ControlMethod::CacheGet => "control.cache.get",
259            ControlMethod::CacheSetCap => "control.cache.setCap",
260            ControlMethod::CacheClear => "control.cache.clear",
261            ControlMethod::HostedStoresList => "control.hostedStores.list",
262            ControlMethod::HostedStoresPin => "control.hostedStores.pin",
263            ControlMethod::HostedStoresUnpin => "control.hostedStores.unpin",
264            ControlMethod::HostedStoresStatus => "control.hostedStores.status",
265            ControlMethod::CapsuleFetch => "control.capsule.fetch",
266            ControlMethod::SyncStatus => "control.sync.status",
267            ControlMethod::SyncTrigger => "control.sync.trigger",
268            ControlMethod::UpdaterStatus => "control.updater.status",
269            ControlMethod::UpdaterSetChannel => "control.updater.setChannel",
270            ControlMethod::UpdaterPause => "control.updater.pause",
271            ControlMethod::UpdaterResume => "control.updater.resume",
272            ControlMethod::UpdaterCheckNow => "control.updater.checkNow",
273            ControlMethod::PairingList => "control.pairing.list",
274            ControlMethod::PairingApprove => "control.pairing.approve",
275            ControlMethod::PairingRevoke => "control.pairing.revoke",
276            ControlMethod::PeerStatus => "control.peerStatus",
277            ControlMethod::PeerCounts => "control.peerCounts",
278            ControlMethod::PeersConnect => "control.peers.connect",
279            ControlMethod::PeersDisconnect => "control.peers.disconnect",
280            ControlMethod::ChiaPeersAdd => "control.chiaPeers.add",
281            ControlMethod::ChiaPeersList => "control.chiaPeers.list",
282            ControlMethod::ChiaPeersRemove => "control.chiaPeers.remove",
283            ControlMethod::Subscribe => "control.subscribe",
284            ControlMethod::Unsubscribe => "control.unsubscribe",
285            ControlMethod::ListSubscriptions => "control.listSubscriptions",
286            ControlMethod::WalletBalance => "control.wallet.balance",
287            ControlMethod::WalletCoins => "control.wallet.coins",
288            ControlMethod::WalletCoinById => "control.wallet.coinById",
289            ControlMethod::WalletCoinSpend => "control.wallet.coinSpend",
290            ControlMethod::WalletCoinsByParent => "control.wallet.coinsByParent",
291            ControlMethod::WalletArrivals => "control.wallet.arrivals",
292            ControlMethod::WalletOperatorAddress => "control.wallet.operatorAddress",
293            ControlMethod::WalletPeak => "control.wallet.peak",
294            ControlMethod::WalletSyncStatus => "control.wallet.syncStatus",
295            ControlMethod::WalletBroadcast => "control.wallet.broadcast",
296            ControlMethod::WalletWatch => "control.wallet.watch",
297            ControlMethod::WalletUnwatch => "control.wallet.unwatch",
298            ControlMethod::WalletWatched => "control.wallet.watched",
299            ControlMethod::WalletReservationsHeld => "control.wallet.reservations.held",
300            ControlMethod::WalletReservationsReserve => "control.wallet.reservations.reserve",
301            ControlMethod::WalletReservationsRelease => "control.wallet.reservations.release",
302            ControlMethod::WalletResetCoinDb => "control.wallet.resetCoinDb",
303            ControlMethod::SpendsList => "control.spends.list",
304            ControlMethod::CollateralRequirement => "control.collateral.requirement",
305            ControlMethod::CollateralMarginGet => "control.collateral.margin.get",
306            ControlMethod::CollateralMarginSet => "control.collateral.margin.set",
307            ControlMethod::CollateralBuffer => "control.collateral.buffer",
308            ControlMethod::MirrorBondStates => "control.mirror.bondStates",
309            ControlMethod::ProfilePutBody => "control.profile.putBody",
310            ControlMethod::ProfileGetBody => "control.profile.getBody",
311            ControlMethod::PairingRequest => "pairing.request",
312            ControlMethod::PairingPoll => "pairing.poll",
313        }
314    }
315
316    /// Resolve a wire name back to its [`ControlMethod`], or `None` for an unknown name.
317    pub fn from_name(name: &str) -> Option<ControlMethod> {
318        ControlMethod::ALL
319            .iter()
320            .copied()
321            .find(|m| m.name() == name)
322    }
323
324    /// Does calling this method require the local control token?
325    ///
326    /// Three groups are reachable WITHOUT one, and they are open for two different reasons:
327    ///
328    /// - the pairing bootstrap (`pairing.request` / `pairing.poll`), so a token-less client can
329    ///   obtain a token at all;
330    /// - the PEER COUNTS (`control.peerCounts`), which disclose three integers about this node's
331    ///   own connectivity and no address, endpoint or secret;
332    /// - the wallet CALLER-ADDRESSED CHAIN READS (`control.wallet.balance` / `.coins` /
333    ///   `.coinById` / `.coinSpend` / `.coinsByParent`) and the node's own chain POSITION
334    ///   (`.peak` / `.syncStatus`), because each needs only PUBLIC chain data the CALLER already
335    ///   named — an address, or a coin id; never a seed, a key, or a signature — and dig-node has
336    ///   served `control.wallet.balance` open since #1851. A person whose node runs as a service
337    ///   with an unreadable token file can still see their own money.
338    ///
339    /// Five wallet methods are deliberately NOT in that second group:
340    ///
341    /// - `control.wallet.broadcast` puts bytes on the network, so the token is what stands between
342    ///   a local process and a broadcast — a mutation on the chain state itself;
343    /// - `control.wallet.watch` and `.unwatch` aim what this node follows, so they are mutations
344    ///   of this node's own watched-key set;
345    /// - `control.wallet.arrivals` and `.watched` take nothing from the caller and answer back
346    ///   with this node's OWN state — watched puzzle hashes and enrolled public keys respectively.
347    ///
348    /// See [`ControlMethod::is_open_read`]. On all five, `UNAUTHORIZED` genuinely means
349    /// *unauthorized*.
350    pub const fn requires_auth(self) -> bool {
351        !self.is_open_read()
352            && !matches!(
353                self,
354                ControlMethod::PairingRequest | ControlMethod::PairingPoll
355            )
356    }
357
358    /// Is this an OPEN READ — served without a control token?
359    ///
360    /// Two kinds of method qualify, and they are open for different reasons:
361    ///
362    /// - the wallet CHAIN READS (`control.wallet.balance` / `.coins` / `.coinById` / `.coinSpend` /
363    ///   `.coinsByParent` / `.peak` / `.syncStatus`), which need only PUBLIC chain data — an
364    ///   address, or a coin id; never a seed, a key, or a signature. On the first five the CALLER
365    ///   supplies the address or coin id, so the node relays a public fact and discloses no
366    ///   association with itself; the last two name the node's own chain position and no address
367    ///   at all;
368    /// - `control.peerCounts`, which is NOT a chain read: it discloses three integers about this
369    ///   node's own connectivity, and no address, endpoint, peer identity or secret. The identity
370    ///   and topology half of the same subject stays gated behind `control.peerStatus`.
371    ///
372    /// Naming both reasons matters more than it looks. The test for membership is *does this
373    /// disclose only data that is already public, or a bare count of this node's own state?* — NOT
374    /// *is it a chain read?* A future method judged against the narrower phrasing, and found to
375    /// contradict a member that was already there, invites widening the predicate by analogy rather
376    /// than against the rule.
377    ///
378    /// `control.wallet.arrivals` is the worked example, and it was briefly a member. It passes the
379    /// narrower phrasing — every field it returns is a public chain fact — and fails the rule: the
380    /// caller supplies NOTHING, so the node volunteers its OWN watched puzzle hashes together with
381    /// the full receive history behind them. The individual facts are public; the ASSOCIATION
382    /// between this node and those addresses is not, and that association is the whole answer. A
383    /// token-less caller could then feed those addresses back into the caller-addressed reads.
384    /// Membership turns on *who names the address*, never on whether the bytes are on chain.
385    ///
386    /// Stated on the contract rather than discovered by calling, because the two refusals a client
387    /// can get here demand OPPOSITE remedies. On an open read, `UNAUTHORIZED` can only come from a
388    /// node build that predates the method and gates it generically, so the remedy is an upgrade.
389    /// On a gated method — the push — `UNAUTHORIZED` means exactly what it says, and the remedy is
390    /// the token. A client that maps the two the same way sends somebody to fix the wrong thing.
391    pub const fn is_open_read(self) -> bool {
392        matches!(
393            self,
394            ControlMethod::WalletBalance
395                | ControlMethod::WalletCoins
396                | ControlMethod::WalletCoinById
397                | ControlMethod::WalletCoinSpend
398                | ControlMethod::WalletCoinsByParent
399                | ControlMethod::WalletPeak
400                | ControlMethod::WalletSyncStatus
401                | ControlMethod::PeerCounts
402        )
403    }
404
405    /// Is this a PAIRING-ADMINISTRATION method that requires the MASTER control token specifically?
406    ///
407    /// A paired (scoped) token can drive ordinary `control.*` mutations but MUST NOT mint more
408    /// tokens or revoke itself — so listing/approving/revoking pairings requires the master token
409    /// (a local file read), never a paired token.
410    ///
411    /// This names the pairing LIFECYCLE only. The predicate an auth gate consults is
412    /// [`ControlMethod::requires_master_token`], of which this is a strict subset.
413    pub const fn is_pairing_admin(self) -> bool {
414        matches!(
415            self,
416            ControlMethod::PairingList
417                | ControlMethod::PairingApprove
418                | ControlMethod::PairingRevoke
419        )
420    }
421
422    /// Does this method require the MASTER control token — the local file read — rather than any
423    /// valid token?
424    ///
425    /// **This, not [`ControlMethod::is_pairing_admin`], is the predicate an auth gate consults.**
426    /// The master tier is not "pairing administration"; it is every method whose effect OUTLIVES
427    /// the token that invoked it, and pairing administration is one instance of that shape.
428    ///
429    /// The rule, stated so a later method can be judged against it rather than by analogy: a
430    /// method belongs here when a caller holding a paired token could use it to acquire authority
431    /// it keeps AFTER that token is revoked. `pairing.revoke` is the designated remedy for a
432    /// compromised paired app, so any method that survives it has escaped the remedy.
433    ///
434    /// The two members outside the pairing lifecycle are `control.chiaPeers.add` and
435    /// `control.chiaPeers.remove`, and they are here for exactly that reason. `add` writes a
436    /// standing entry into the peer store the wallet replica reads, and a peer in that set is
437    /// believed WITHOUT corroboration — it can dictate money-bearing chain facts (peak height, and
438    /// therefore confirmation counts). Once written, the caller no longer needs the token at all,
439    /// and revoking the token does not remove the entry. A paired token must therefore not be able
440    /// to write one. `remove` is the only un-trust remedy and is gated with it, so a paired token
441    /// cannot strip the peers an operator deliberately trusts.
442    ///
443    /// `control.chiaPeers.list` deliberately stays on the ordinary token tier: it is a READ, it
444    /// grants nothing that outlives the token, and gating it would leave a paired client unable to
445    /// show the operator the trust state it is subject to. That matches `control.wallet.arrivals`,
446    /// which is gated at the ordinary tier for disclosing an association without conferring
447    /// authority.
448    ///
449    /// `control.config.setMirrorAdvertiseUrls` ALSO stays ordinary, and for the same reason as
450    /// `control.chiaPeers.list` rather than by analogy to its own persistence: "outlives the
451    /// token" is necessary but not sufficient (see this repo's #40, which argues
452    /// `control.config.setUpstream` should be promoted for exactly this gap). The persisted
453    /// override survives `pairing.revoke` just as `setUpstream`'s does, but it installs no
454    /// principal this node will thereafter believe, obey, or forward requests to — it changes only
455    /// what THIS node broadcasts about itself in its own mirror-coin memo. The node never dials the
456    /// value, never trusts bytes read FROM it, and never routes a call TO it. A caller cannot use
457    /// it to make the node trust or obey anyone new, which is the same reason `cache.setCap` and
458    /// `log.setLevel` stay ordinary despite also persisting past the call that set them.
459    pub const fn requires_master_token(self) -> bool {
460        self.is_pairing_admin()
461            || matches!(
462                self,
463                ControlMethod::ChiaPeersAdd | ControlMethod::ChiaPeersRemove
464            )
465    }
466
467    /// How the node routes this method (shell-owned, engine-delegated, or open bootstrap).
468    pub const fn routing(self) -> Routing {
469        match self {
470            ControlMethod::PeerStatus
471            | ControlMethod::PeerCounts
472            | ControlMethod::PeersConnect
473            | ControlMethod::PeersDisconnect
474            | ControlMethod::Subscribe
475            | ControlMethod::Unsubscribe
476            | ControlMethod::ListSubscriptions
477            | ControlMethod::WalletBalance
478            | ControlMethod::WalletCoins
479            | ControlMethod::WalletCoinById
480            | ControlMethod::WalletCoinSpend
481            | ControlMethod::WalletCoinsByParent
482            | ControlMethod::WalletArrivals
483            | ControlMethod::WalletPeak
484            | ControlMethod::WalletSyncStatus
485            | ControlMethod::WalletBroadcast
486            | ControlMethod::WalletWatch
487            | ControlMethod::WalletUnwatch
488            | ControlMethod::WalletWatched
489            | ControlMethod::WalletReservationsHeld
490            | ControlMethod::WalletReservationsReserve
491            | ControlMethod::WalletReservationsRelease
492            | ControlMethod::WalletResetCoinDb
493            | ControlMethod::ProfilePutBody
494            | ControlMethod::ProfileGetBody => Routing::Delegated,
495            ControlMethod::PairingRequest | ControlMethod::PairingPoll => Routing::OpenBootstrap,
496            _ => Routing::Owned,
497        }
498    }
499
500    /// The functional area this method belongs to.
501    pub const fn category(self) -> Category {
502        match self {
503            ControlMethod::Status => Category::Status,
504            ControlMethod::ConfigGet
505            | ControlMethod::ConfigSetUpstream
506            | ControlMethod::ConfigSetMirrorAdvertiseUrls => Category::Config,
507            ControlMethod::LogSetLevel => Category::Log,
508            ControlMethod::CacheGet | ControlMethod::CacheSetCap | ControlMethod::CacheClear => {
509                Category::Cache
510            }
511            ControlMethod::HostedStoresList
512            | ControlMethod::HostedStoresPin
513            | ControlMethod::HostedStoresUnpin
514            | ControlMethod::HostedStoresStatus
515            | ControlMethod::CapsuleFetch => Category::HostedStores,
516            ControlMethod::SyncStatus | ControlMethod::SyncTrigger => Category::Sync,
517            ControlMethod::UpdaterStatus
518            | ControlMethod::UpdaterSetChannel
519            | ControlMethod::UpdaterPause
520            | ControlMethod::UpdaterResume
521            | ControlMethod::UpdaterCheckNow => Category::Updater,
522            ControlMethod::PairingList
523            | ControlMethod::PairingApprove
524            | ControlMethod::PairingRevoke
525            | ControlMethod::PairingRequest
526            | ControlMethod::PairingPoll => Category::Pairing,
527            ControlMethod::PeerStatus
528            | ControlMethod::PeerCounts
529            | ControlMethod::PeersConnect
530            | ControlMethod::PeersDisconnect
531            | ControlMethod::ChiaPeersAdd
532            | ControlMethod::ChiaPeersList
533            | ControlMethod::ChiaPeersRemove => Category::Peers,
534            ControlMethod::Subscribe
535            | ControlMethod::Unsubscribe
536            | ControlMethod::ListSubscriptions => Category::Subscriptions,
537            ControlMethod::WalletBalance
538            | ControlMethod::WalletCoins
539            | ControlMethod::WalletCoinById
540            | ControlMethod::WalletCoinSpend
541            | ControlMethod::WalletCoinsByParent
542            | ControlMethod::WalletArrivals
543            | ControlMethod::WalletPeak
544            | ControlMethod::WalletSyncStatus
545            | ControlMethod::WalletOperatorAddress
546            | ControlMethod::WalletBroadcast
547            | ControlMethod::WalletWatch
548            | ControlMethod::WalletUnwatch
549            | ControlMethod::WalletWatched
550            | ControlMethod::WalletReservationsHeld
551            | ControlMethod::WalletReservationsReserve
552            | ControlMethod::WalletReservationsRelease
553            | ControlMethod::WalletResetCoinDb => Category::Wallet,
554            ControlMethod::SpendsList => Category::Spends,
555            ControlMethod::CollateralRequirement
556            | ControlMethod::CollateralMarginGet
557            | ControlMethod::CollateralMarginSet
558            | ControlMethod::CollateralBuffer
559            | ControlMethod::MirrorBondStates => Category::Collateral,
560            ControlMethod::ProfilePutBody | ControlMethod::ProfileGetBody => Category::Profile,
561        }
562    }
563
564    /// A one-line human/agent description for the discovery catalogue.
565    pub const fn summary(self) -> &'static str {
566        match self {
567            ControlMethod::ChiaPeersAdd => "Trust a Chia full node by IP. A trusted peer BYPASSES CORROBORATION: this node normally believes a chain answer only when several independently-dialled peers agree, and a trusted peer is believed on its own -- so a wrong or hostile one can feed this node a false view of the chain. Add only a node you run yourself.",
568            ControlMethod::ChiaPeersList => "The Chia full-node peers this node tracks, each flagged user_managed: true where a person added it by hand and it is therefore trusted without corroboration.",
569            ControlMethod::ChiaPeersRemove => "Stop trusting a Chia full node, optionally banning it. Removing restores corroboration for that peer: chain answers must once again be agreed by independently-dialled peers.",
570            ControlMethod::Status => "A rich node status snapshot (version, uptime, addr, cache, hosted/pinned counts, sync availability).",
571            ControlMethod::ConfigGet => "The node's effective configuration (addr/port, upstream + override, cache dir/shared, config path, sync availability, mirror advertise-URL view).",
572            ControlMethod::ConfigSetUpstream => "Persist an upstream-RPC override; takes effect on next node start (requires_restart).",
573            ControlMethod::ConfigSetMirrorAdvertiseUrls => "Override (urls: a non-empty list) or clear (urls: null/absent) the URLs this node advertises in its own mirror-coin memos. The result's requires_restart says whether that took effect now or needs a node restart -- check it before telling anyone the change is live. An explicit EMPTY list is refused rather than guessed at -- it is ambiguous between advertising nothing and reverting to the derived default. Checked only for a well-formed absolute URL (scheme + host): an operator's LAN or private address is accepted on purpose, the same derived-vs-operator asymmetry dig-node#562 established.",
574            ControlMethod::LogSetLevel => "Live-swap the running node's tracing EnvFilter directive (not persisted).",
575            ControlMethod::CacheGet => "The on-disk content-cache view: cap_bytes, used_bytes, dir, shared.",
576            ControlMethod::CacheSetCap => "Set the on-disk cache size cap in bytes (floored at 64 MiB).",
577            ControlMethod::CacheClear => "Delete all locally cached DIG content.",
578            ControlMethod::HostedStoresList => "Every held/pinned store, merged, with each store's cached capsules and a pinned flag.",
579            ControlMethod::HostedStoresPin => "Pin a store (storeId[:rootHash]); pre-fetches the capsule when a root is given and §21 sync is available.",
580            ControlMethod::HostedStoresUnpin => "Unpin a store and evict its cached capsules.",
581            ControlMethod::HostedStoresStatus => "Per-store status: pinned flag, cached capsules, total bytes.",
582            ControlMethod::CapsuleFetch => "Start a P2P whole-capsule pull for one store+root over the recursive discover-then-dial path (distinct from the §21 HTTP sync `control.sync.trigger` uses). Answers `already_cached` without dialling out when the capsule is already on disk.",
583            ControlMethod::SyncStatus => "Whether authenticated §21 whole-store sync is available, plus pinned-store cache coverage.",
584            ControlMethod::SyncTrigger => "Trigger a §21 sync for one capsule (storeId + root).",
585            ControlMethod::UpdaterStatus => "The DIG auto-update beacon's current status (proxied from dig-updater).",
586            ControlMethod::UpdaterSetChannel => "Set the beacon's update channel (\"nightly\" | \"stable\").",
587            ControlMethod::UpdaterPause => "Suspend the beacon's auto-updates (optionally until a unix time).",
588            ControlMethod::UpdaterResume => "Resume the beacon's auto-updates.",
589            ControlMethod::UpdaterCheckNow => "Force an immediate beacon update check.",
590            ControlMethod::PairingList => "List pending pairing requests and issued paired tokens (MASTER token only).",
591            ControlMethod::PairingApprove => "Approve a pending pairing, minting a scoped token (MASTER token only).",
592            ControlMethod::PairingRevoke => "Revoke an issued paired token by token_id (MASTER token only).",
593            ControlMethod::PeerStatus => "Live peer-pool + relay-reservation snapshot, including the per-peer connected array; each entry carries an always-present `software` field (the peer's advertised build). Its `relay.peer_count` counts peers connected to THE RELAY, not to this node, and is never the answer to \"how many peers does this node have\" -- that is control.peerCounts.",
594            ControlMethod::PeerCounts => "READ-only: how many peers this node holds on EACH network -- dig_peer_count (DIG content/gossip, port 9445) and chia_peer_count (Chia full nodes serving the wallet chain sync). Two unrelated numbers, each named for its network.",
595            ControlMethod::PeersConnect => "Dial a peer by address, or resolve an already-connected peer_id, via the live gossip pool.",
596            ControlMethod::PeersDisconnect => "Drop a pooled peer by peer_id, closing its mTLS link (idempotent).",
597            ControlMethod::Subscribe => "Subscribe the node to a store it actively watches and gap-fills.",
598            ControlMethod::Unsubscribe => "Stop watching a store.",
599            ControlMethod::ListSubscriptions => "The node's persisted subscription set + count.",
600            ControlMethod::WalletCoins => "READ-only: the spendable coin records for an address + asset, with the tier that answered and the height they reflect.",
601            ControlMethod::WalletCoinById => "READ-only: ONE coin record by coin id, spent or unspent, with no address and no asset scope; `coin: null` means the chain holds no such coin.",
602            ControlMethod::WalletCoinSpend => "READ-only: the SPEND that spent a coin -- its puzzle reveal, its solution and the coin itself -- named by the coin's own id. `spend: null` means the consulted chain shows that coin as unspent or unknown; it NEVER means the chain could not be reached, which is an error.",
603            ControlMethod::WalletCoinsByParent => "READ-only: the DIRECT children created by spending one coin, named by that parent's coin id. ONE hop, never a recursive walk: an empty list means the parent created no known children, and a caller wanting a lineage composes hops itself.",
604            ControlMethod::WalletArrivals => "READ-only: confirmed INCOMING funds recorded since a cursor position, oldest first -- the answer to `was I just paid?`, which no balance or coin list can give. Each row is a coin the node determined ARRIVED: confirmed on chain, above the wallet's arrival baseline, not previously reported, and not the wallet's own change. Resume from `cursor` (the last row you were handed), never from `latest`.",
605            ControlMethod::WalletOperatorAddress => "READ-only: the address of the node's OWN operator wallet -- the MACHINE-custody wallet that pays mirror-coin collateral, never the user's. Returns a public address and puzzle hash and NEVER any key, seed or derivation material. TOKEN-GATED, and answered by THIS node rather than forwarded upstream.",
606            ControlMethod::WalletPeak => "READ-only: the node's current chain peak height, independent of any address.",
607            ControlMethod::WalletSyncStatus => "READ-only: whether the wallet's CHAIN replica is being kept current (not_started/syncing/synced/no_wallet_enrolled/wallet_not_unlocked), the replica's own height, and its CHIA full-node peer count -- unrelated to control.sync.status (DIG stores) and to control.peerStatus (DIG peers).",
608            ControlMethod::WalletBroadcast => "Push an ALREADY-SIGNED spend bundle to the network; the node never signs. TOKEN-GATED.",
609            ControlMethod::WalletBalance => "READ-only: the confirmed spendable balance for an address + asset (plus pending, sync freshness, and the peak height it reflects).",
610            ControlMethod::WalletWatch => "Enrol PUBLIC keys (48-byte G1, lowercase 96-hex) for the node's chain replica to follow, so their addresses are synced and readable. IDEMPOTENT: re-enrolling a key already enrolled succeeds and changes nothing. Keys, never puzzle hashes -- the node derives the addresses itself, so one derivation serves every client. TOKEN-GATED.",
611            ControlMethod::WalletUnwatch => "Deregister enrolled public keys, so the node stops following their addresses. IDEMPOTENT: a key that was never enrolled is not an error. TOKEN-GATED.",
612            ControlMethod::SpendsList => "READ-only: the record of spends this node made WITHOUT per-transaction approval -- what moved, when, on whose standing authority, and whether the chain confirmed it. It NEVER initiates, signs, cancels or alters a spend, and there is no verb here that edits an entry. A failed spend is reported WITH the stage it died at, because only a signing failure means the money definitely did not move; a broadcast or confirmation failure is an UNKNOWN outcome, as is `unresolved`. A page is bounded and says so via `complete`; `unreadable_lines` reports entries the node could not parse, so an audit trail that lost rows can never read as a tidy shorter one. TOKEN-GATED although it is a read: the caller supplies no identifier, so the answer is this node's OWN state.",
613            ControlMethod::CollateralRequirement => "READ-only: this epoch's per-store mirror-collateral requirement in DIG base units, the collateral protocol version that computed it, and the census inputs behind it (advertised stores, collateralised owners, controller multiplier, small-network handicap) so a client can show WHY the figure moved rather than only that it did. A node that has not censused the epoch, or that is inside the census finality depth, answers `unknown` WITH the reason -- never a zero, which would read as a free requirement. `stores` counts qualifying (owner, store, root) advertisements and `owners` counts distinct owner puzzle hashes: neither is a node count. It NEVER returns the local safety margin, which is not a consensus value.",
614            ControlMethod::CollateralMarginGet => "Read the node's LOCAL safety margin in BASIS POINTS over the epoch requirement (`100` is +1%). The margin is an operator preference that changes only how much THIS node chooses to lock; it is never a census input and no value derived from it reaches another node. Basis points are the unit the collateral crate's own presets and rounding use, and are never converted.",
615            ControlMethod::CollateralMarginSet => "Set the node's LOCAL safety margin in BASIS POINTS (`100` is +1%), returning the margin now in force. Bounded at 10000 bp (+100%): the margin multiplies what the node locks on every store, so an unbounded value would commit the operator to an arbitrary posting. A margin above the bound is REFUSED as -32602 INVALID_PARAMS rather than clamped, so the applied value can never differ silently from the requested one. A margin gives room if the requirement rises; it does NOT guarantee a store is counted, because the requirement is re-derived every epoch and can rise by more than any margin.",
616            ControlMethod::ProfilePutBody => "Hand the node the dig-profile BODY that a chain root commits to. The node INDEPENDENTLY resolves that root on chain and REFUSES any body whose recomputed root is not the confirmed one -- the caller's `root` is a claim to be checked, never a fact to be trusted, and dig-app is a caller like any other. Bodies are capped at MAX_BODY_BYTES (4 MiB). TOKEN-GATED.",
617            ControlMethod::ProfileGetBody => "READ-only: the dig-profile body this node holds at a given store id + root, or `body: null` when it holds none. `null` NEVER means the body could not be read, which is an error. TOKEN-GATED.",
618            ControlMethod::WalletWatched => "READ-only: the public keys currently enrolled, so a client can reconcile what it asked for against what the node holds. TOKEN-GATED although it is a read -- the caller supplies nothing, so the answer is this node's OWN key set.",
619            ControlMethod::WalletReservationsHeld => "READ-only: every coin currently committed to an in-flight spend, each with the reservation holding it and the unix second that hold lapses, plus the node's own clock. `reserved: []` means NOTHING is held; a set that cannot be read is an error, never an empty list. Narrows what a caller may SELECT; never subtract these from a balance -- the coins are still the user's money. TOKEN-GATED although it is a read: the caller supplies nothing, so the answer is this node's OWN state.",
620            ControlMethod::WalletReservationsReserve => "Atomically hold coins against further selection: EVERY named coin or none. A coin already held refuses the whole call and reserves nothing, as WALLET_COINS_RESERVED -- a WAIT, never a shortfall. Reserving an empty list succeeds with a handle that releases nothing. The requested ttl_secs is clamped by the node, which returns the lifetime it actually applied. Bookkeeping only: it holds no key and authorizes nothing (§908). TOKEN-GATED.",
621            ControlMethod::WalletReservationsRelease => "Free a hold now rather than waiting out its TTL -- call it the moment a spend is known settled or known dead. A handle that names no live reservation is a SUCCESS with released: false, because a caller releasing on confirmation cannot know whether the TTL got there first. Every hold also lapses on its own, so an abandoned reservation is recoverable and never a permanent funds lockout. TOKEN-GATED.",
622            ControlMethod::WalletResetCoinDb => "DESTRUCTIVE: discard this node's cached coin database and re-sync it from chain. No key material is affected -- coins live on chain and are re-derived by the resync. Refuses with SpendInFlight while a spend is outstanding, so a reset can never race a hold. Requires params.confirm = true or refuses as INVALID_PARAMS; the on-wire acknowledgement is the confirmation, not a default. TOKEN-GATED.",
623            ControlMethod::CollateralBuffer => "READ-only: the $DIG this node recommends HOLDING, in DIG base units, and the funding state it is in -- plus the working behind the figure: the (owner, store, root) pairs THIS NODE serves, the epoch's pre-margin per-store requirement, the local margin in force (BASIS POINTS, `100` is +1%, never converted), the unreclaimed transition overlap, and the escalation headroom. Amounts are DIG base units (3 decimals, one base unit is 0.001 DIG) and never mojos, which are XCH's 1e-12 unit. The HORIZON the headroom assumed travels in the payload and is never implied: escalation is bounded at +12.5% per epoch and COMPOUNDS (x1.12 at one epoch, x1.60 at four, x4.62 at thirteen), so the same buffer over a different horizon is a different claim; `escalation_ceiling_micros` is a WORST CASE, not a forecast -- in the dead band the multiplier does not move. The FUNDING STATE is carried rather than left to each client to re-derive from thresholds, because two clients deriving it will disagree and the one that disagrees about a funding warning is the one an operator acts on; `short_now` and `dangerously_low` leave an epoch uncovered, `below_recommended_buffer` covers every epoch with no cushion and is a READOUT, never a notification. A node that cannot enumerate its served set, cannot read its reclaim state, cannot see its balance, or has no requirement to scale answers `unknown` WITH the reason -- never a zero, which here reads as NO BUFFER NEEDED and would have an operator post nothing. It is a SEPARATE method from `control.collateral.requirement` because that figure is consensus-derived while this one is local: it depends on this node's own served set, an operator preference, and a horizon this node chose. TOKEN-GATED although it is a read: the caller supplies nothing, so the answer is this node's OWN served set, preference and balance.",
624            ControlMethod::MirrorBondStates => "READ-only: the state of every mirror bond this node holds, keyed per (store, root), plus the $DIG those bonds have LOCKED. Seven states, and six of them mean `no coin yet` for entirely different reasons: `bonded` (a coin id, epoch and the amount THAT COIN locks, read from the coin and not from today's requirement), `pending` (submitted, unconfirmed -- never a shortfall), `unfunded` (the ONLY genuine out-of-funds state, carrying how many DIG BASE UNITS this bond alone is short), `deferred` (the epoch requirement is unknown so no create can be priced -- the wallet may be full), `withheld` (Relayed provenance: held and deliberately never advertised), `disabled` (collateralisation is switched off node-wide) and `reclaiming` (a live coin whose money is STILL LOCKED until the reclaim confirms). Conflating `unfunded` with `withheld` or `disabled` produces hourly out-of-funds alarms about a healthy node, which is the defect this method removes. Amounts are DIG base units (3 decimals, one base unit is 0.001 DIG) and NEVER mojos, which are XCH's 1e-12 unit. `locked_dig_base_units` is the WHOLE-SET total including reclaiming coins, computed by the node: a client MUST NOT sum the page, which would under-report locked money by a page boundary and show unspendable funds as available. A node that cannot enumerate its bonds, cannot read chain, cannot see its own in-flight creates, or cannot determine the provenance of what it holds answers `unknown` for the WHOLE call WITH the reason -- there is no per-row unknown and no empty-list fallback, because a truncated list and a complete one read the same. A page is bounded, ordered by ascending (store_id, root), and says via `complete` whether it is the whole set; resume from the `cursor` key you were HANDED. TOKEN-GATED although it is a read: the caller supplies nothing, so the answer is this node's OWN bond set and funding position.",
625            ControlMethod::PairingRequest => "OPEN: request a control-token pairing; returns a pairing_id + pairing_code to compare.",
626            ControlMethod::PairingPoll => "OPEN: poll a pairing by id; once the operator approves, returns the scoped token once.",
627        }
628    }
629
630    /// Every catalogued method, in a stable order — the enumeration a machine reads to discover the
631    /// full control surface, and the anchor the conformance KATs pin against.
632    pub const ALL: &'static [ControlMethod] = &[
633        ControlMethod::Status,
634        ControlMethod::ConfigGet,
635        ControlMethod::ConfigSetUpstream,
636        ControlMethod::ConfigSetMirrorAdvertiseUrls,
637        ControlMethod::LogSetLevel,
638        ControlMethod::CacheGet,
639        ControlMethod::CacheSetCap,
640        ControlMethod::CacheClear,
641        ControlMethod::HostedStoresList,
642        ControlMethod::HostedStoresPin,
643        ControlMethod::HostedStoresUnpin,
644        ControlMethod::HostedStoresStatus,
645        ControlMethod::CapsuleFetch,
646        ControlMethod::SyncStatus,
647        ControlMethod::SyncTrigger,
648        ControlMethod::UpdaterStatus,
649        ControlMethod::UpdaterSetChannel,
650        ControlMethod::UpdaterPause,
651        ControlMethod::UpdaterResume,
652        ControlMethod::UpdaterCheckNow,
653        ControlMethod::PairingList,
654        ControlMethod::PairingApprove,
655        ControlMethod::PairingRevoke,
656        ControlMethod::PeerStatus,
657        ControlMethod::PeerCounts,
658        ControlMethod::PeersConnect,
659        ControlMethod::PeersDisconnect,
660        ControlMethod::ChiaPeersAdd,
661        ControlMethod::ChiaPeersList,
662        ControlMethod::ChiaPeersRemove,
663        ControlMethod::Subscribe,
664        ControlMethod::Unsubscribe,
665        ControlMethod::ListSubscriptions,
666        ControlMethod::WalletBalance,
667        ControlMethod::WalletCoins,
668        ControlMethod::WalletCoinById,
669        ControlMethod::WalletCoinSpend,
670        ControlMethod::WalletCoinsByParent,
671        ControlMethod::WalletArrivals,
672        ControlMethod::WalletPeak,
673        ControlMethod::WalletSyncStatus,
674        ControlMethod::WalletOperatorAddress,
675        ControlMethod::WalletBroadcast,
676        ControlMethod::WalletWatch,
677        ControlMethod::WalletUnwatch,
678        ControlMethod::WalletWatched,
679        ControlMethod::WalletReservationsHeld,
680        ControlMethod::WalletReservationsReserve,
681        ControlMethod::WalletReservationsRelease,
682        ControlMethod::WalletResetCoinDb,
683        ControlMethod::SpendsList,
684        ControlMethod::CollateralRequirement,
685        ControlMethod::CollateralMarginGet,
686        ControlMethod::CollateralMarginSet,
687        ControlMethod::CollateralBuffer,
688        ControlMethod::MirrorBondStates,
689        ControlMethod::ProfilePutBody,
690        ControlMethod::ProfileGetBody,
691        ControlMethod::PairingRequest,
692        ControlMethod::PairingPoll,
693    ];
694}
695
696#[cfg(test)]
697mod tests {
698    use super::*;
699    use std::collections::BTreeSet;
700
701    #[test]
702    fn every_method_has_a_unique_wire_name() {
703        let names: BTreeSet<&str> = ControlMethod::ALL.iter().map(|m| m.name()).collect();
704        assert_eq!(
705            names.len(),
706            ControlMethod::ALL.len(),
707            "duplicate or missing wire names in the catalog"
708        );
709    }
710
711    #[test]
712    fn from_name_round_trips_every_method() {
713        for &m in ControlMethod::ALL {
714            assert_eq!(ControlMethod::from_name(m.name()), Some(m));
715        }
716        assert_eq!(ControlMethod::from_name("control.nope"), None);
717        assert_eq!(ControlMethod::from_name(""), None);
718    }
719
720    #[test]
721    fn the_token_less_surface_is_exactly_the_bootstrap_plus_the_chain_reads() {
722        // Written out rather than derived from `is_open_read`, so this pins the SET and not the
723        // implementation's opinion of itself. A method added to the open surface must be added
724        // here deliberately -- which is the review step a broadcast must never slip past.
725        let expected_open: BTreeSet<&str> = [
726            "pairing.request",
727            "pairing.poll",
728            "control.wallet.balance",
729            "control.wallet.coins",
730            "control.wallet.coinById",
731            "control.wallet.coinSpend",
732            "control.wallet.coinsByParent",
733            "control.wallet.peak",
734            "control.wallet.syncStatus",
735            "control.peerCounts",
736        ]
737        .into_iter()
738        .collect();
739        assert_eq!(
740            expected_open.len(),
741            10,
742            "the open surface is ten named methods"
743        );
744        let actual_open: BTreeSet<&str> = ControlMethod::ALL
745            .iter()
746            .filter(|m| !m.requires_auth())
747            .map(|m| m.name())
748            .collect();
749        assert_eq!(actual_open, expected_open);
750    }
751
752    /// **The gated wallet methods are the push, the arrival cursor, the operator address, the three
753    /// enrolment methods, the three reservation methods, and the coin-db reset.** The fixture varies one thing -- which wallet method is asked -- against a category
754    /// whose other members ARE open, so both nearest wrong implementations fail here: one that opens
755    /// the whole category (the state this crate shipped in at `1190a18`) and one that gates it
756    /// wholesale.
757    ///
758    /// Written out in catalog order rather than derived, so a method joining the gated side is a
759    /// deliberate edit here -- the review step a broadcast, or an enrolment, must never slip past.
760    #[test]
761    fn the_gated_wallet_methods_are_the_push_the_cursor_and_enrolment() {
762        let gated: Vec<&str> = ControlMethod::ALL
763            .iter()
764            .filter(|m| m.category() == Category::Wallet && m.requires_auth())
765            .map(|m| m.name())
766            .collect();
767        assert_eq!(
768            gated,
769            vec![
770                "control.wallet.arrivals",
771                // Gated for the SAME reason as `arrivals` above: the caller does not name the
772                // address, so the node volunteers its own node-to-address association. Here it is
773                // the machine wallet's, which no open read discloses.
774                "control.wallet.operatorAddress",
775                "control.wallet.broadcast",
776                "control.wallet.watch",
777                "control.wallet.unwatch",
778                "control.wallet.watched",
779                "control.wallet.reservations.held",
780                "control.wallet.reservations.reserve",
781                "control.wallet.reservations.release",
782                "control.wallet.resetCoinDb",
783            ]
784        );
785        assert!(!ControlMethod::WalletBroadcast.is_open_read());
786    }
787
788    /// **The arrival cursor is NOT an open read, and the reason is not "is it a chain read?".**
789    ///
790    /// The rule is *who names the address*. `control.wallet.arrivals` takes only a cursor, so the
791    /// node volunteers its OWN watched puzzle hashes and the receive history behind them -- the
792    /// node-to-address association, which is not public, and which a token-less caller could then
793    /// replay into the caller-addressed reads.
794    ///
795    /// The control keeps `control.wallet.coinById` in the same assertion: it is the neighbour the
796    /// analogy was drawn from, it is still open, and it stays open because its CALLER supplies the
797    /// coin id. Without that control this test would also pass on a wholesale gating of the wallet
798    /// category, which is a different (and wrong) implementation.
799    #[test]
800    fn the_arrival_cursor_is_not_an_open_read() {
801        assert!(
802            !ControlMethod::WalletArrivals.is_open_read(),
803            "control.wallet.arrivals discloses this node's OWN watched puzzle hashes to a caller \
804             that supplied nothing, so it MUST NOT be served token-less"
805        );
806        assert!(ControlMethod::WalletArrivals.requires_auth());
807        assert!(
808            ControlMethod::WalletCoinById.is_open_read(),
809            "the caller-addressed reads stay open -- the fix is the membership rule, not gating \
810             the wallet category"
811        );
812    }
813
814    /// **The control plane names every chain primitive `ChainSource` needs.**
815    ///
816    /// The list is written out rather than derived, because the property under test is a claim about
817    /// ANOTHER crate's trait (`dig-chainsource-interface`'s `ChainSource`) that no compiler here can
818    /// check. Five of its seven methods need a control method of their own. The other two need none:
819    /// `parent_spend` is a trait DEFAULT composed from `coin_record` + `coin_spend`, and
820    /// `resolve_singleton_lineage` is composed CLIENT-side from the primitives below rather than
821    /// served as a walk the node performs.
822    ///
823    /// `block_timestamp` is deliberately ABSENT from the control plane. dig-node's light client
824    /// (`chia-peer`'s `ChiaPeerProvider`) does not index block timestamps and answers `Unsupported`,
825    /// so a control method for it could only ever be refused — a surface that looks live and does
826    /// nothing. A consumer mirrors that refusal honestly; if one ever genuinely needs the value, the
827    /// method is an additive minor at that point.
828    ///
829    /// A missing name here is not a cosmetic gap: a client that cannot answer one of these cannot
830    /// implement the trait at all, which is what made a dig-profile mint structurally impossible
831    /// through the node before these two were added (dig_ecosystem#2572).
832    #[test]
833    fn the_catalog_serves_every_chain_source_primitive() {
834        for wire in [
835            "control.wallet.coinById",      // coin_record
836            "control.wallet.coins",         // coin_records_by_puzzle_hash
837            "control.wallet.peak",          // peak_height
838            "control.wallet.coinsByParent", // coin_records_by_parent
839            "control.wallet.coinSpend",     // coin_spend
840        ] {
841            assert!(
842                ControlMethod::from_name(wire).is_some(),
843                "{wire} is required to implement ChainSource over the control plane"
844            );
845        }
846    }
847
848    /// **The two chain primitives are `coinById`'s neighbours, not `arrivals`'.**
849    ///
850    /// Each takes a caller-supplied coin id and returns a deterministic public chain fact,
851    /// so the membership rule — *who names the subject* — puts them on the open side. The gated
852    /// control in the same assertion is what makes the test load-bearing: without it, a wholesale
853    /// opening of the wallet category would pass, and that is a different (and wrong) implementation.
854    #[test]
855    fn the_chain_primitives_are_caller_named_open_reads() {
856        for method in [
857            ControlMethod::WalletCoinSpend,
858            ControlMethod::WalletCoinsByParent,
859        ] {
860            assert!(
861                method.is_open_read(),
862                "{} names its subject in the request and discloses no node-to-address \
863                 association, exactly like control.wallet.coinById",
864                method.name()
865            );
866            assert!(!method.requires_auth());
867        }
868        assert!(
869            ControlMethod::WalletArrivals.requires_auth(),
870            "the caller-supplies-nothing read stays gated -- the rule is who names the subject, \
871             not whether the bytes are on chain"
872        );
873        assert!(ControlMethod::WalletBroadcast.requires_auth());
874    }
875
876    /// **All three enrolment methods are gated — including the one that only reads.**
877    ///
878    /// `control.wallet.watch` and `.unwatch` aim what the node follows, so they are mutations and the
879    /// question barely arises. `control.wallet.watched` is the one a future reader will be tempted to
880    /// open, because it returns nothing but public keys and every other wallet READ in this catalog is
881    /// open. It stays gated under the SAME rule that gates `control.wallet.arrivals`: the caller
882    /// supplies nothing, so the node volunteers its OWN enrolled keys — the node-to-key association,
883    /// which is not public, and which a token-less caller could replay straight into the
884    /// caller-addressed reads.
885    ///
886    /// The control keeps `control.wallet.coinById` open in the same assertion. Without it this test
887    /// would also pass on a wholesale gating of the wallet category, which is a different (and wrong)
888    /// implementation.
889    #[test]
890    fn the_enrolment_methods_are_gated_including_the_read() {
891        for wire in [
892            "control.wallet.watch",
893            "control.wallet.unwatch",
894            "control.wallet.watched",
895        ] {
896            let method = ControlMethod::from_name(wire)
897                .unwrap_or_else(|| panic!("{wire} must be in the catalog"));
898            assert!(
899                !method.is_open_read(),
900                "{wire} either aims this node's subscriptions or names the keys it already \
901                 follows, so it MUST NOT be served token-less"
902            );
903            assert!(method.requires_auth(), "{wire} must require the token");
904            assert_eq!(method.category(), Category::Wallet);
905            assert_eq!(method.routing(), Routing::Delegated);
906        }
907        assert!(
908            ControlMethod::WalletCoinById.is_open_read(),
909            "the caller-addressed reads stay open -- enrolment is gated by the membership rule, \
910             not by gating the wallet category"
911        );
912    }
913
914    #[test]
915    fn only_pairing_bootstrap_is_open_bootstrap_routed() {
916        for &m in ControlMethod::ALL {
917            let open_bootstrap = matches!(
918                m,
919                ControlMethod::PairingRequest | ControlMethod::PairingPoll
920            );
921            assert_eq!(
922                m.routing() == Routing::OpenBootstrap,
923                open_bootstrap,
924                "{} routing mismatch",
925                m.name()
926            );
927        }
928    }
929
930    #[test]
931    fn pairing_admin_methods_are_exactly_three() {
932        let admin: Vec<&str> = ControlMethod::ALL
933            .iter()
934            .filter(|m| m.is_pairing_admin())
935            .map(|m| m.name())
936            .collect();
937        assert_eq!(
938            admin,
939            vec![
940                "control.pairing.list",
941                "control.pairing.approve",
942                "control.pairing.revoke"
943            ]
944        );
945    }
946
947    /// **The master-token tier is the pairing lifecycle PLUS the trusted-peer mutations.**
948    ///
949    /// The set is asserted whole, because the risk is a method quietly joining or leaving it. The
950    /// two non-pairing members are here for a stated reason — `chiaPeers.add` grants authority
951    /// that SURVIVES `pairing.revoke`, so a paired token holding it escapes the very remedy for a
952    /// compromised paired app.
953    #[test]
954    fn the_master_token_tier_is_pairing_admin_plus_the_trusted_peer_mutations() {
955        let master: BTreeSet<&str> = ControlMethod::ALL
956            .iter()
957            .filter(|m| m.requires_master_token())
958            .map(|m| m.name())
959            .collect();
960        let expected: BTreeSet<&str> = [
961            "control.pairing.list",
962            "control.pairing.approve",
963            "control.pairing.revoke",
964            "control.chiaPeers.add",
965            "control.chiaPeers.remove",
966        ]
967        .into_iter()
968        .collect();
969        assert_eq!(master, expected);
970
971        // Pairing administration is a STRICT subset, not a synonym: a gate that consults
972        // `is_pairing_admin` instead of `requires_master_token` lets a paired token add a peer.
973        for &m in ControlMethod::ALL {
974            assert!(
975                !m.is_pairing_admin() || m.requires_master_token(),
976                "{} is pairing-admin but not master-tier",
977                m.name()
978            );
979        }
980        assert!(
981            master.len()
982                > ControlMethod::ALL
983                    .iter()
984                    .filter(|m| m.is_pairing_admin())
985                    .count(),
986            "the two predicates must not be interchangeable"
987        );
988
989        // Master implies the token is required at all.
990        for &m in ControlMethod::ALL {
991            assert!(
992                !m.requires_master_token() || m.requires_auth(),
993                "{}",
994                m.name()
995            );
996        }
997    }
998
999    /// **The trust wording stays inside NC-12's authorisation: a node the operator RUNS.**
1000    ///
1001    /// NC-12 permits trust only from "the operator declaring it their own node". Widening that to
1002    /// vouching moves the case outside the justification for the unbounded authority the entry
1003    /// carries, and "a node you vouch for" is a phrase somebody can be talked into applying to a
1004    /// stranger's address.
1005    #[test]
1006    fn the_add_summary_authorises_only_a_node_the_operator_runs() {
1007        let summary = ControlMethod::ChiaPeersAdd.summary().to_lowercase();
1008        assert!(
1009            summary.contains("a node you run"),
1010            "add must name the operator-run scope, got: {summary}"
1011        );
1012        for widened in ["vouch", "otherwise trust", "trust yourself", "recommend"] {
1013            assert!(
1014                !summary.contains(widened),
1015                "add summary widens operator trust past NC-12 with {widened:?}: {summary}"
1016            );
1017        }
1018    }
1019
1020    #[test]
1021    fn delegated_set_matches_the_engine_surface() {
1022        let delegated: BTreeSet<&str> = ControlMethod::ALL
1023            .iter()
1024            .filter(|m| m.routing() == Routing::Delegated)
1025            .map(|m| m.name())
1026            .collect();
1027        let expected: BTreeSet<&str> = [
1028            "control.wallet.coins",
1029            "control.wallet.coinById",
1030            "control.wallet.coinSpend",
1031            "control.wallet.coinsByParent",
1032            "control.wallet.arrivals",
1033            "control.wallet.peak",
1034            "control.wallet.syncStatus",
1035            "control.wallet.broadcast",
1036            "control.wallet.watch",
1037            "control.wallet.unwatch",
1038            "control.wallet.watched",
1039            "control.wallet.reservations.held",
1040            "control.wallet.reservations.reserve",
1041            "control.wallet.reservations.release",
1042            "control.wallet.resetCoinDb",
1043            "control.profile.putBody",
1044            "control.profile.getBody",
1045            "control.peerStatus",
1046            "control.peerCounts",
1047            "control.peers.connect",
1048            "control.peers.disconnect",
1049            "control.subscribe",
1050            "control.unsubscribe",
1051            "control.listSubscriptions",
1052            "control.wallet.balance",
1053        ]
1054        .into_iter()
1055        .collect();
1056        assert_eq!(delegated, expected);
1057    }
1058
1059    /// **The trusted-Chia-peer methods are declared, gated, and say what they cost.**
1060    ///
1061    /// A trusted peer BYPASSES corroboration (NC-12: dialled peers are untrusted and agreement
1062    /// across ~5 concurrently-queried peers is what makes a read safe). The catalog is what a
1063    /// machine reads before offering the control, so the cost is stated HERE and not only in a
1064    /// doc page — a client that surfaces `summary()` surfaces the warning with it.
1065    #[test]
1066    fn the_trusted_chia_peer_methods_are_gated_and_disclose_the_corroboration_bypass() {
1067        let declared: BTreeSet<&str> = ControlMethod::ALL.iter().map(|m| m.name()).collect();
1068        for name in [
1069            "control.chiaPeers.add",
1070            "control.chiaPeers.list",
1071            "control.chiaPeers.remove",
1072        ] {
1073            assert!(declared.contains(name), "{name} is not in the catalog");
1074            let m = ControlMethod::from_name(name).expect("from_name round-trips");
1075            assert_eq!(m.category(), Category::Peers, "{name} is a peers method");
1076            assert_eq!(m.routing(), Routing::Owned, "{name} is served by the shell");
1077            assert!(m.requires_auth(), "{name} must require the control token");
1078            assert!(!m.is_open_read(), "{name} is not an open read");
1079        }
1080        // The MUTATIONS need the MASTER token; the READ deliberately does not. `add` writes
1081        // standing, corroboration-free authority that outlives the token that wrote it — a paired
1082        // token must not be able to install it, and `remove` is the only way back out.
1083        assert!(ControlMethod::ChiaPeersAdd.requires_master_token());
1084        assert!(ControlMethod::ChiaPeersRemove.requires_master_token());
1085        assert!(
1086            !ControlMethod::ChiaPeersList.requires_master_token(),
1087            "list grants nothing that outlives the token; gating it would blind a paired client \
1088             to the trust state it is subject to"
1089        );
1090        // The COST, not merely the capability: the two methods that change the trusted set must
1091        // name the bypass. A summary that only described the action would let a client offer the
1092        // control while silently withholding what it gives up.
1093        for name in ["control.chiaPeers.add", "control.chiaPeers.remove"] {
1094            let summary = ControlMethod::from_name(name).unwrap().summary();
1095            assert!(
1096                summary.to_lowercase().contains("corroboration"),
1097                "{name} summary must name the corroboration bypass, got: {summary}"
1098            );
1099        }
1100    }
1101
1102    /// **`control.config.setMirrorAdvertiseUrls` stays ORDINARY tier — it installs no principal.**
1103    ///
1104    /// It outlives the token exactly like `chiaPeers.add` and the proposed `config.setUpstream`
1105    /// promotion (this repo's #40) — the persisted override survives `pairing.revoke` just as
1106    /// theirs do. The discriminator this contract's own doc states is narrower than "outlives the
1107    /// token": whether the node will thereafter BELIEVE, OBEY, or SPEAK TO whatever was installed.
1108    /// `chiaPeers.add` makes the node trust a peer's chain answers without corroboration;
1109    /// `config.setUpstream` makes the node FORWARD calls to a third party. This method changes
1110    /// only what this node broadcasts ABOUT ITSELF in its own mirror-coin memo — the node never
1111    /// dials the value, never trusts bytes FROM it, and never forwards anything TO it. A caller
1112    /// cannot use it to make the node trust or obey anyone new, the same reason `cache.setCap` and
1113    /// `log.setLevel` stay ordinary despite also persisting.
1114    #[test]
1115    fn set_mirror_advertise_urls_is_ordinary_tier_and_config_category() {
1116        let m = ControlMethod::ConfigSetMirrorAdvertiseUrls;
1117        assert_eq!(m.name(), "control.config.setMirrorAdvertiseUrls");
1118        assert_eq!(m.category(), Category::Config);
1119        assert_eq!(m.routing(), Routing::Owned);
1120        assert!(m.requires_auth(), "a mutation on this plane is never open");
1121        assert!(!m.requires_master_token());
1122        assert!(!m.is_open_read());
1123        assert!(!m.is_pairing_admin());
1124    }
1125
1126    #[test]
1127    fn every_method_has_a_nonempty_summary() {
1128        for &m in ControlMethod::ALL {
1129            assert!(!m.summary().is_empty(), "{} has no summary", m.name());
1130        }
1131    }
1132}