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, and the node's LOCAL safety
70    /// margin over it. 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.log.setLevel` — live-swap the running node's tracing level filter.
91    LogSetLevel,
92
93    // ---- Cache (shell-owned) ----
94    /// `control.cache.get` — the on-disk cache view (cap/used/dir/shared).
95    CacheGet,
96    /// `control.cache.setCap` — set the cache size cap (floored at 64 MiB).
97    CacheSetCap,
98    /// `control.cache.clear` — delete all locally cached content.
99    CacheClear,
100
101    // ---- Hosted stores (shell-owned) ----
102    /// `control.hostedStores.list` — every held/pinned store with its cached capsules.
103    HostedStoresList,
104    /// `control.hostedStores.pin` — pin a store (and pre-fetch when a root is given).
105    HostedStoresPin,
106    /// `control.hostedStores.unpin` — unpin a store and evict its cached capsules.
107    HostedStoresUnpin,
108    /// `control.hostedStores.status` — per-store pinned flag + cached capsules.
109    HostedStoresStatus,
110    /// `control.capsule.fetch` — start (or report already-cached) a P2P whole-capsule pull for
111    /// one store+root, over the recursive discover-then-dial path rather than the §21 HTTP sync.
112    CapsuleFetch,
113
114    // ---- §21 sync (shell-owned) ----
115    /// `control.sync.status` — whether authenticated whole-store sync is available + pin coverage.
116    SyncStatus,
117    /// `control.sync.trigger` — trigger a §21 sync for one capsule (storeId + root).
118    SyncTrigger,
119
120    // ---- Updater beacon proxy (shell-owned) ----
121    /// `control.updater.status` — the DIG auto-update beacon's current status.
122    UpdaterStatus,
123    /// `control.updater.setChannel` — set the beacon's update channel.
124    UpdaterSetChannel,
125    /// `control.updater.pause` — suspend auto-updates (optionally until a unix time).
126    UpdaterPause,
127    /// `control.updater.resume` — resume auto-updates.
128    UpdaterResume,
129    /// `control.updater.checkNow` — force an immediate update check.
130    UpdaterCheckNow,
131
132    // ---- Pairing administration (shell-owned, MASTER-token only) ----
133    /// `control.pairing.list` — list pending pairing requests + issued paired tokens.
134    PairingList,
135    /// `control.pairing.approve` — approve a pending pairing, minting a scoped token.
136    PairingApprove,
137    /// `control.pairing.revoke` — revoke an issued paired token.
138    PairingRevoke,
139
140    // ---- Peers (delegated to the engine) ----
141    /// `control.peerStatus` — live peer-pool + relay-reservation snapshot.
142    PeerStatus,
143    /// `control.peerCounts` — how many peers this node holds on EACH network (DIG and Chia).
144    PeerCounts,
145    /// `control.peers.connect` — dial a peer by address / resolve a connected peer_id.
146    PeersConnect,
147    /// `control.peers.disconnect` — drop a pooled peer by peer_id.
148    PeersDisconnect,
149
150    // ---- Trusted CHIA full-node peers (shell-owned) ----
151    //
152    // A DIFFERENT network from `control.peers.*` above, which are DIG gossip peers. These name
153    // Chia full nodes the wallet replica will TRUST, and trust here is a real cost: NC-12 makes
154    // dialled peers untrusted precisely so that agreement across several concurrently-queried
155    // peers is what makes a read safe. A trusted peer is exempted from that agreement, so a wrong
156    // or hostile one is believed on its own. Every surface that offers these MUST say so.
157    //
158    // Trust comes from the operator declaring a node THEIR OWN — that is the whole of the
159    // authorisation, and the wording everywhere in this crate says exactly that. It is not
160    // "a node you vouch for": the unbounded authority a trusted peer holds is justified by the
161    // operator controlling both ends, which is false of a stranger's node however well
162    // recommended. A person can be talked into vouching for an address; they cannot be talked
163    // into believing they run it.
164    /// `control.chiaPeers.add` — trust a Chia full node you RUN, bypassing corroboration for it.
165    ChiaPeersAdd,
166    /// `control.chiaPeers.list` — the trusted Chia full-node peers this node tracks.
167    ChiaPeersList,
168    /// `control.chiaPeers.remove` — stop trusting a Chia full node (optionally banning it).
169    ChiaPeersRemove,
170
171    // ---- Subscriptions (delegated to the engine) ----
172    /// `control.subscribe` — subscribe the node to a store (watch + gap-fill).
173    Subscribe,
174    /// `control.unsubscribe` — stop watching a store.
175    Unsubscribe,
176    /// `control.listSubscriptions` — the node's persisted subscription set.
177    ListSubscriptions,
178
179    // ---- Wallet chain transport (delegated to the engine) ----
180    /// `control.wallet.balance` — read an address's confirmed spendable balance for an asset.
181    WalletBalance,
182    /// `control.wallet.coins` — read an address's spendable coin records for an asset.
183    WalletCoins,
184    /// `control.wallet.coinById` — read ONE coin record by coin id, spent or unspent.
185    WalletCoinById,
186    /// `control.wallet.coinSpend` — read the SPEND that spent a coin (puzzle reveal + solution).
187    WalletCoinSpend,
188    /// `control.wallet.coinsByParent` — read the direct children a coin's spend created (one hop).
189    WalletCoinsByParent,
190    /// `control.wallet.arrivals` — read confirmed INCOMING funds since a cursor position.
191    WalletArrivals,
192    /// `control.wallet.peak` — read the node's current chain peak height.
193    WalletPeak,
194    /// `control.wallet.syncStatus` — read whether the wallet's chain replica is being kept current.
195    WalletSyncStatus,
196    /// `control.wallet.broadcast` — push an ALREADY-SIGNED spend bundle to the network.
197    WalletBroadcast,
198    /// `control.wallet.watch` — enrol PUBLIC keys for the node's chain replica to follow.
199    WalletWatch,
200    /// `control.wallet.unwatch` — deregister enrolled public keys, so the following stops.
201    WalletUnwatch,
202    /// `control.wallet.watched` — list the public keys currently enrolled.
203    WalletWatched,
204    /// `control.wallet.reservations.held` — read which coins are committed to in-flight spends.
205    WalletReservationsHeld,
206    /// `control.wallet.reservations.reserve` — atomically hold coins, all of them or none.
207    WalletReservationsReserve,
208    /// `control.wallet.reservations.release` — free a hold now, ahead of its TTL.
209    WalletReservationsRelease,
210
211    // ---- Automated-spend audit record (shell-owned) ----
212    /// `control.spends.list` — read the record of spends this node made WITHOUT asking.
213    SpendsList,
214
215    // ---- Mirror collateral (shell-owned) ----
216    /// `control.collateral.requirement` -- this epoch's per-store collateral requirement.
217    CollateralRequirement,
218    /// `control.collateral.margin.get` -- read the node's local safety margin, in basis points.
219    CollateralMarginGet,
220    /// `control.collateral.margin.set` -- set the node's local safety margin, in basis points.
221    CollateralMarginSet,
222    /// `control.collateral.buffer` -- the $DIG this node recommends holding, and its funding state.
223    CollateralBuffer,
224
225    // ---- dig-profile bodies (delegated to the engine) ----
226    /// `control.profile.putBody` — hand the node the profile body a CONFIRMED chain root commits to.
227    ProfilePutBody,
228    /// `control.profile.getBody` — read back the profile body this node holds at a given root.
229    ProfileGetBody,
230
231    // ---- Pairing bootstrap (OPEN — no token) ----
232    /// `pairing.request` — request a control-token pairing (returns a code to compare).
233    PairingRequest,
234    /// `pairing.poll` — poll a pairing; once the operator approves, returns the scoped token once.
235    PairingPoll,
236}
237
238impl ControlMethod {
239    /// The stable JSON-RPC wire name. Never derived from anything else — the published contract.
240    pub const fn name(self) -> &'static str {
241        match self {
242            ControlMethod::Status => "control.status",
243            ControlMethod::ConfigGet => "control.config.get",
244            ControlMethod::ConfigSetUpstream => "control.config.setUpstream",
245            ControlMethod::LogSetLevel => "control.log.setLevel",
246            ControlMethod::CacheGet => "control.cache.get",
247            ControlMethod::CacheSetCap => "control.cache.setCap",
248            ControlMethod::CacheClear => "control.cache.clear",
249            ControlMethod::HostedStoresList => "control.hostedStores.list",
250            ControlMethod::HostedStoresPin => "control.hostedStores.pin",
251            ControlMethod::HostedStoresUnpin => "control.hostedStores.unpin",
252            ControlMethod::HostedStoresStatus => "control.hostedStores.status",
253            ControlMethod::CapsuleFetch => "control.capsule.fetch",
254            ControlMethod::SyncStatus => "control.sync.status",
255            ControlMethod::SyncTrigger => "control.sync.trigger",
256            ControlMethod::UpdaterStatus => "control.updater.status",
257            ControlMethod::UpdaterSetChannel => "control.updater.setChannel",
258            ControlMethod::UpdaterPause => "control.updater.pause",
259            ControlMethod::UpdaterResume => "control.updater.resume",
260            ControlMethod::UpdaterCheckNow => "control.updater.checkNow",
261            ControlMethod::PairingList => "control.pairing.list",
262            ControlMethod::PairingApprove => "control.pairing.approve",
263            ControlMethod::PairingRevoke => "control.pairing.revoke",
264            ControlMethod::PeerStatus => "control.peerStatus",
265            ControlMethod::PeerCounts => "control.peerCounts",
266            ControlMethod::PeersConnect => "control.peers.connect",
267            ControlMethod::PeersDisconnect => "control.peers.disconnect",
268            ControlMethod::ChiaPeersAdd => "control.chiaPeers.add",
269            ControlMethod::ChiaPeersList => "control.chiaPeers.list",
270            ControlMethod::ChiaPeersRemove => "control.chiaPeers.remove",
271            ControlMethod::Subscribe => "control.subscribe",
272            ControlMethod::Unsubscribe => "control.unsubscribe",
273            ControlMethod::ListSubscriptions => "control.listSubscriptions",
274            ControlMethod::WalletBalance => "control.wallet.balance",
275            ControlMethod::WalletCoins => "control.wallet.coins",
276            ControlMethod::WalletCoinById => "control.wallet.coinById",
277            ControlMethod::WalletCoinSpend => "control.wallet.coinSpend",
278            ControlMethod::WalletCoinsByParent => "control.wallet.coinsByParent",
279            ControlMethod::WalletArrivals => "control.wallet.arrivals",
280            ControlMethod::WalletPeak => "control.wallet.peak",
281            ControlMethod::WalletSyncStatus => "control.wallet.syncStatus",
282            ControlMethod::WalletBroadcast => "control.wallet.broadcast",
283            ControlMethod::WalletWatch => "control.wallet.watch",
284            ControlMethod::WalletUnwatch => "control.wallet.unwatch",
285            ControlMethod::WalletWatched => "control.wallet.watched",
286            ControlMethod::WalletReservationsHeld => "control.wallet.reservations.held",
287            ControlMethod::WalletReservationsReserve => "control.wallet.reservations.reserve",
288            ControlMethod::WalletReservationsRelease => "control.wallet.reservations.release",
289            ControlMethod::SpendsList => "control.spends.list",
290            ControlMethod::CollateralRequirement => "control.collateral.requirement",
291            ControlMethod::CollateralMarginGet => "control.collateral.margin.get",
292            ControlMethod::CollateralMarginSet => "control.collateral.margin.set",
293            ControlMethod::CollateralBuffer => "control.collateral.buffer",
294            ControlMethod::ProfilePutBody => "control.profile.putBody",
295            ControlMethod::ProfileGetBody => "control.profile.getBody",
296            ControlMethod::PairingRequest => "pairing.request",
297            ControlMethod::PairingPoll => "pairing.poll",
298        }
299    }
300
301    /// Resolve a wire name back to its [`ControlMethod`], or `None` for an unknown name.
302    pub fn from_name(name: &str) -> Option<ControlMethod> {
303        ControlMethod::ALL
304            .iter()
305            .copied()
306            .find(|m| m.name() == name)
307    }
308
309    /// Does calling this method require the local control token?
310    ///
311    /// Three groups are reachable WITHOUT one, and they are open for two different reasons:
312    ///
313    /// - the pairing bootstrap (`pairing.request` / `pairing.poll`), so a token-less client can
314    ///   obtain a token at all;
315    /// - the PEER COUNTS (`control.peerCounts`), which disclose three integers about this node's
316    ///   own connectivity and no address, endpoint or secret;
317    /// - the wallet CALLER-ADDRESSED CHAIN READS (`control.wallet.balance` / `.coins` /
318    ///   `.coinById` / `.coinSpend` / `.coinsByParent`) and the node's own chain POSITION
319    ///   (`.peak` / `.syncStatus`), because each needs only PUBLIC chain data the CALLER already
320    ///   named — an address, or a coin id; never a seed, a key, or a signature — and dig-node has
321    ///   served `control.wallet.balance` open since #1851. A person whose node runs as a service
322    ///   with an unreadable token file can still see their own money.
323    ///
324    /// Five wallet methods are deliberately NOT in that second group:
325    ///
326    /// - `control.wallet.broadcast` puts bytes on the network, so the token is what stands between
327    ///   a local process and a broadcast — a mutation on the chain state itself;
328    /// - `control.wallet.watch` and `.unwatch` aim what this node follows, so they are mutations
329    ///   of this node's own watched-key set;
330    /// - `control.wallet.arrivals` and `.watched` take nothing from the caller and answer back
331    ///   with this node's OWN state — watched puzzle hashes and enrolled public keys respectively.
332    ///
333    /// See [`ControlMethod::is_open_read`]. On all five, `UNAUTHORIZED` genuinely means
334    /// *unauthorized*.
335    pub const fn requires_auth(self) -> bool {
336        !self.is_open_read()
337            && !matches!(
338                self,
339                ControlMethod::PairingRequest | ControlMethod::PairingPoll
340            )
341    }
342
343    /// Is this an OPEN READ — served without a control token?
344    ///
345    /// Two kinds of method qualify, and they are open for different reasons:
346    ///
347    /// - the wallet CHAIN READS (`control.wallet.balance` / `.coins` / `.coinById` / `.coinSpend` /
348    ///   `.coinsByParent` / `.peak` / `.syncStatus`), which need only PUBLIC chain data — an
349    ///   address, or a coin id; never a seed, a key, or a signature. On the first five the CALLER
350    ///   supplies the address or coin id, so the node relays a public fact and discloses no
351    ///   association with itself; the last two name the node's own chain position and no address
352    ///   at all;
353    /// - `control.peerCounts`, which is NOT a chain read: it discloses three integers about this
354    ///   node's own connectivity, and no address, endpoint, peer identity or secret. The identity
355    ///   and topology half of the same subject stays gated behind `control.peerStatus`.
356    ///
357    /// Naming both reasons matters more than it looks. The test for membership is *does this
358    /// disclose only data that is already public, or a bare count of this node's own state?* — NOT
359    /// *is it a chain read?* A future method judged against the narrower phrasing, and found to
360    /// contradict a member that was already there, invites widening the predicate by analogy rather
361    /// than against the rule.
362    ///
363    /// `control.wallet.arrivals` is the worked example, and it was briefly a member. It passes the
364    /// narrower phrasing — every field it returns is a public chain fact — and fails the rule: the
365    /// caller supplies NOTHING, so the node volunteers its OWN watched puzzle hashes together with
366    /// the full receive history behind them. The individual facts are public; the ASSOCIATION
367    /// between this node and those addresses is not, and that association is the whole answer. A
368    /// token-less caller could then feed those addresses back into the caller-addressed reads.
369    /// Membership turns on *who names the address*, never on whether the bytes are on chain.
370    ///
371    /// Stated on the contract rather than discovered by calling, because the two refusals a client
372    /// can get here demand OPPOSITE remedies. On an open read, `UNAUTHORIZED` can only come from a
373    /// node build that predates the method and gates it generically, so the remedy is an upgrade.
374    /// On a gated method — the push — `UNAUTHORIZED` means exactly what it says, and the remedy is
375    /// the token. A client that maps the two the same way sends somebody to fix the wrong thing.
376    pub const fn is_open_read(self) -> bool {
377        matches!(
378            self,
379            ControlMethod::WalletBalance
380                | ControlMethod::WalletCoins
381                | ControlMethod::WalletCoinById
382                | ControlMethod::WalletCoinSpend
383                | ControlMethod::WalletCoinsByParent
384                | ControlMethod::WalletPeak
385                | ControlMethod::WalletSyncStatus
386                | ControlMethod::PeerCounts
387        )
388    }
389
390    /// Is this a PAIRING-ADMINISTRATION method that requires the MASTER control token specifically?
391    ///
392    /// A paired (scoped) token can drive ordinary `control.*` mutations but MUST NOT mint more
393    /// tokens or revoke itself — so listing/approving/revoking pairings requires the master token
394    /// (a local file read), never a paired token.
395    ///
396    /// This names the pairing LIFECYCLE only. The predicate an auth gate consults is
397    /// [`ControlMethod::requires_master_token`], of which this is a strict subset.
398    pub const fn is_pairing_admin(self) -> bool {
399        matches!(
400            self,
401            ControlMethod::PairingList
402                | ControlMethod::PairingApprove
403                | ControlMethod::PairingRevoke
404        )
405    }
406
407    /// Does this method require the MASTER control token — the local file read — rather than any
408    /// valid token?
409    ///
410    /// **This, not [`ControlMethod::is_pairing_admin`], is the predicate an auth gate consults.**
411    /// The master tier is not "pairing administration"; it is every method whose effect OUTLIVES
412    /// the token that invoked it, and pairing administration is one instance of that shape.
413    ///
414    /// The rule, stated so a later method can be judged against it rather than by analogy: a
415    /// method belongs here when a caller holding a paired token could use it to acquire authority
416    /// it keeps AFTER that token is revoked. `pairing.revoke` is the designated remedy for a
417    /// compromised paired app, so any method that survives it has escaped the remedy.
418    ///
419    /// The two members outside the pairing lifecycle are `control.chiaPeers.add` and
420    /// `control.chiaPeers.remove`, and they are here for exactly that reason. `add` writes a
421    /// standing entry into the peer store the wallet replica reads, and a peer in that set is
422    /// believed WITHOUT corroboration — it can dictate money-bearing chain facts (peak height, and
423    /// therefore confirmation counts). Once written, the caller no longer needs the token at all,
424    /// and revoking the token does not remove the entry. A paired token must therefore not be able
425    /// to write one. `remove` is the only un-trust remedy and is gated with it, so a paired token
426    /// cannot strip the peers an operator deliberately trusts.
427    ///
428    /// `control.chiaPeers.list` deliberately stays on the ordinary token tier: it is a READ, it
429    /// grants nothing that outlives the token, and gating it would leave a paired client unable to
430    /// show the operator the trust state it is subject to. That matches `control.wallet.arrivals`,
431    /// which is gated at the ordinary tier for disclosing an association without conferring
432    /// authority.
433    pub const fn requires_master_token(self) -> bool {
434        self.is_pairing_admin()
435            || matches!(
436                self,
437                ControlMethod::ChiaPeersAdd | ControlMethod::ChiaPeersRemove
438            )
439    }
440
441    /// How the node routes this method (shell-owned, engine-delegated, or open bootstrap).
442    pub const fn routing(self) -> Routing {
443        match self {
444            ControlMethod::PeerStatus
445            | ControlMethod::PeerCounts
446            | ControlMethod::PeersConnect
447            | ControlMethod::PeersDisconnect
448            | ControlMethod::Subscribe
449            | ControlMethod::Unsubscribe
450            | ControlMethod::ListSubscriptions
451            | ControlMethod::WalletBalance
452            | ControlMethod::WalletCoins
453            | ControlMethod::WalletCoinById
454            | ControlMethod::WalletCoinSpend
455            | ControlMethod::WalletCoinsByParent
456            | ControlMethod::WalletArrivals
457            | ControlMethod::WalletPeak
458            | ControlMethod::WalletSyncStatus
459            | ControlMethod::WalletBroadcast
460            | ControlMethod::WalletWatch
461            | ControlMethod::WalletUnwatch
462            | ControlMethod::WalletWatched
463            | ControlMethod::WalletReservationsHeld
464            | ControlMethod::WalletReservationsReserve
465            | ControlMethod::WalletReservationsRelease
466            | ControlMethod::ProfilePutBody
467            | ControlMethod::ProfileGetBody => Routing::Delegated,
468            ControlMethod::PairingRequest | ControlMethod::PairingPoll => Routing::OpenBootstrap,
469            _ => Routing::Owned,
470        }
471    }
472
473    /// The functional area this method belongs to.
474    pub const fn category(self) -> Category {
475        match self {
476            ControlMethod::Status => Category::Status,
477            ControlMethod::ConfigGet | ControlMethod::ConfigSetUpstream => Category::Config,
478            ControlMethod::LogSetLevel => Category::Log,
479            ControlMethod::CacheGet | ControlMethod::CacheSetCap | ControlMethod::CacheClear => {
480                Category::Cache
481            }
482            ControlMethod::HostedStoresList
483            | ControlMethod::HostedStoresPin
484            | ControlMethod::HostedStoresUnpin
485            | ControlMethod::HostedStoresStatus
486            | ControlMethod::CapsuleFetch => Category::HostedStores,
487            ControlMethod::SyncStatus | ControlMethod::SyncTrigger => Category::Sync,
488            ControlMethod::UpdaterStatus
489            | ControlMethod::UpdaterSetChannel
490            | ControlMethod::UpdaterPause
491            | ControlMethod::UpdaterResume
492            | ControlMethod::UpdaterCheckNow => Category::Updater,
493            ControlMethod::PairingList
494            | ControlMethod::PairingApprove
495            | ControlMethod::PairingRevoke
496            | ControlMethod::PairingRequest
497            | ControlMethod::PairingPoll => Category::Pairing,
498            ControlMethod::PeerStatus
499            | ControlMethod::PeerCounts
500            | ControlMethod::PeersConnect
501            | ControlMethod::PeersDisconnect
502            | ControlMethod::ChiaPeersAdd
503            | ControlMethod::ChiaPeersList
504            | ControlMethod::ChiaPeersRemove => Category::Peers,
505            ControlMethod::Subscribe
506            | ControlMethod::Unsubscribe
507            | ControlMethod::ListSubscriptions => Category::Subscriptions,
508            ControlMethod::WalletBalance
509            | ControlMethod::WalletCoins
510            | ControlMethod::WalletCoinById
511            | ControlMethod::WalletCoinSpend
512            | ControlMethod::WalletCoinsByParent
513            | ControlMethod::WalletArrivals
514            | ControlMethod::WalletPeak
515            | ControlMethod::WalletSyncStatus
516            | ControlMethod::WalletBroadcast
517            | ControlMethod::WalletWatch
518            | ControlMethod::WalletUnwatch
519            | ControlMethod::WalletWatched
520            | ControlMethod::WalletReservationsHeld
521            | ControlMethod::WalletReservationsReserve
522            | ControlMethod::WalletReservationsRelease => Category::Wallet,
523            ControlMethod::SpendsList => Category::Spends,
524            ControlMethod::CollateralRequirement
525            | ControlMethod::CollateralMarginGet
526            | ControlMethod::CollateralMarginSet
527            | ControlMethod::CollateralBuffer => Category::Collateral,
528            ControlMethod::ProfilePutBody | ControlMethod::ProfileGetBody => Category::Profile,
529        }
530    }
531
532    /// A one-line human/agent description for the discovery catalogue.
533    pub const fn summary(self) -> &'static str {
534        match self {
535            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.",
536            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.",
537            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.",
538            ControlMethod::Status => "A rich node status snapshot (version, uptime, addr, cache, hosted/pinned counts, sync availability).",
539            ControlMethod::ConfigGet => "The node's effective configuration (addr/port, upstream + override, cache dir/shared, config path, sync availability).",
540            ControlMethod::ConfigSetUpstream => "Persist an upstream-RPC override; takes effect on next node start (requires_restart).",
541            ControlMethod::LogSetLevel => "Live-swap the running node's tracing EnvFilter directive (not persisted).",
542            ControlMethod::CacheGet => "The on-disk content-cache view: cap_bytes, used_bytes, dir, shared.",
543            ControlMethod::CacheSetCap => "Set the on-disk cache size cap in bytes (floored at 64 MiB).",
544            ControlMethod::CacheClear => "Delete all locally cached DIG content.",
545            ControlMethod::HostedStoresList => "Every held/pinned store, merged, with each store's cached capsules and a pinned flag.",
546            ControlMethod::HostedStoresPin => "Pin a store (storeId[:rootHash]); pre-fetches the capsule when a root is given and §21 sync is available.",
547            ControlMethod::HostedStoresUnpin => "Unpin a store and evict its cached capsules.",
548            ControlMethod::HostedStoresStatus => "Per-store status: pinned flag, cached capsules, total bytes.",
549            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.",
550            ControlMethod::SyncStatus => "Whether authenticated §21 whole-store sync is available, plus pinned-store cache coverage.",
551            ControlMethod::SyncTrigger => "Trigger a §21 sync for one capsule (storeId + root).",
552            ControlMethod::UpdaterStatus => "The DIG auto-update beacon's current status (proxied from dig-updater).",
553            ControlMethod::UpdaterSetChannel => "Set the beacon's update channel (\"nightly\" | \"stable\").",
554            ControlMethod::UpdaterPause => "Suspend the beacon's auto-updates (optionally until a unix time).",
555            ControlMethod::UpdaterResume => "Resume the beacon's auto-updates.",
556            ControlMethod::UpdaterCheckNow => "Force an immediate beacon update check.",
557            ControlMethod::PairingList => "List pending pairing requests and issued paired tokens (MASTER token only).",
558            ControlMethod::PairingApprove => "Approve a pending pairing, minting a scoped token (MASTER token only).",
559            ControlMethod::PairingRevoke => "Revoke an issued paired token by token_id (MASTER token only).",
560            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.",
561            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.",
562            ControlMethod::PeersConnect => "Dial a peer by address, or resolve an already-connected peer_id, via the live gossip pool.",
563            ControlMethod::PeersDisconnect => "Drop a pooled peer by peer_id, closing its mTLS link (idempotent).",
564            ControlMethod::Subscribe => "Subscribe the node to a store it actively watches and gap-fills.",
565            ControlMethod::Unsubscribe => "Stop watching a store.",
566            ControlMethod::ListSubscriptions => "The node's persisted subscription set + count.",
567            ControlMethod::WalletCoins => "READ-only: the spendable coin records for an address + asset, with the tier that answered and the height they reflect.",
568            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.",
569            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.",
570            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.",
571            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`.",
572            ControlMethod::WalletPeak => "READ-only: the node's current chain peak height, independent of any address.",
573            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).",
574            ControlMethod::WalletBroadcast => "Push an ALREADY-SIGNED spend bundle to the network; the node never signs. TOKEN-GATED.",
575            ControlMethod::WalletBalance => "READ-only: the confirmed spendable balance for an address + asset (plus pending, sync freshness, and the peak height it reflects).",
576            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.",
577            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.",
578            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.",
579            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.",
580            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.",
581            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.",
582            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.",
583            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.",
584            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.",
585            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.",
586            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.",
587            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.",
588            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.",
589            ControlMethod::PairingRequest => "OPEN: request a control-token pairing; returns a pairing_id + pairing_code to compare.",
590            ControlMethod::PairingPoll => "OPEN: poll a pairing by id; once the operator approves, returns the scoped token once.",
591        }
592    }
593
594    /// Every catalogued method, in a stable order — the enumeration a machine reads to discover the
595    /// full control surface, and the anchor the conformance KATs pin against.
596    pub const ALL: &'static [ControlMethod] = &[
597        ControlMethod::Status,
598        ControlMethod::ConfigGet,
599        ControlMethod::ConfigSetUpstream,
600        ControlMethod::LogSetLevel,
601        ControlMethod::CacheGet,
602        ControlMethod::CacheSetCap,
603        ControlMethod::CacheClear,
604        ControlMethod::HostedStoresList,
605        ControlMethod::HostedStoresPin,
606        ControlMethod::HostedStoresUnpin,
607        ControlMethod::HostedStoresStatus,
608        ControlMethod::CapsuleFetch,
609        ControlMethod::SyncStatus,
610        ControlMethod::SyncTrigger,
611        ControlMethod::UpdaterStatus,
612        ControlMethod::UpdaterSetChannel,
613        ControlMethod::UpdaterPause,
614        ControlMethod::UpdaterResume,
615        ControlMethod::UpdaterCheckNow,
616        ControlMethod::PairingList,
617        ControlMethod::PairingApprove,
618        ControlMethod::PairingRevoke,
619        ControlMethod::PeerStatus,
620        ControlMethod::PeerCounts,
621        ControlMethod::PeersConnect,
622        ControlMethod::PeersDisconnect,
623        ControlMethod::ChiaPeersAdd,
624        ControlMethod::ChiaPeersList,
625        ControlMethod::ChiaPeersRemove,
626        ControlMethod::Subscribe,
627        ControlMethod::Unsubscribe,
628        ControlMethod::ListSubscriptions,
629        ControlMethod::WalletBalance,
630        ControlMethod::WalletCoins,
631        ControlMethod::WalletCoinById,
632        ControlMethod::WalletCoinSpend,
633        ControlMethod::WalletCoinsByParent,
634        ControlMethod::WalletArrivals,
635        ControlMethod::WalletPeak,
636        ControlMethod::WalletSyncStatus,
637        ControlMethod::WalletBroadcast,
638        ControlMethod::WalletWatch,
639        ControlMethod::WalletUnwatch,
640        ControlMethod::WalletWatched,
641        ControlMethod::WalletReservationsHeld,
642        ControlMethod::WalletReservationsReserve,
643        ControlMethod::WalletReservationsRelease,
644        ControlMethod::SpendsList,
645        ControlMethod::CollateralRequirement,
646        ControlMethod::CollateralMarginGet,
647        ControlMethod::CollateralMarginSet,
648        ControlMethod::CollateralBuffer,
649        ControlMethod::ProfilePutBody,
650        ControlMethod::ProfileGetBody,
651        ControlMethod::PairingRequest,
652        ControlMethod::PairingPoll,
653    ];
654}
655
656#[cfg(test)]
657mod tests {
658    use super::*;
659    use std::collections::BTreeSet;
660
661    #[test]
662    fn every_method_has_a_unique_wire_name() {
663        let names: BTreeSet<&str> = ControlMethod::ALL.iter().map(|m| m.name()).collect();
664        assert_eq!(
665            names.len(),
666            ControlMethod::ALL.len(),
667            "duplicate or missing wire names in the catalog"
668        );
669    }
670
671    #[test]
672    fn from_name_round_trips_every_method() {
673        for &m in ControlMethod::ALL {
674            assert_eq!(ControlMethod::from_name(m.name()), Some(m));
675        }
676        assert_eq!(ControlMethod::from_name("control.nope"), None);
677        assert_eq!(ControlMethod::from_name(""), None);
678    }
679
680    #[test]
681    fn the_token_less_surface_is_exactly_the_bootstrap_plus_the_chain_reads() {
682        // Written out rather than derived from `is_open_read`, so this pins the SET and not the
683        // implementation's opinion of itself. A method added to the open surface must be added
684        // here deliberately -- which is the review step a broadcast must never slip past.
685        let expected_open: BTreeSet<&str> = [
686            "pairing.request",
687            "pairing.poll",
688            "control.wallet.balance",
689            "control.wallet.coins",
690            "control.wallet.coinById",
691            "control.wallet.coinSpend",
692            "control.wallet.coinsByParent",
693            "control.wallet.peak",
694            "control.wallet.syncStatus",
695            "control.peerCounts",
696        ]
697        .into_iter()
698        .collect();
699        assert_eq!(
700            expected_open.len(),
701            10,
702            "the open surface is ten named methods"
703        );
704        let actual_open: BTreeSet<&str> = ControlMethod::ALL
705            .iter()
706            .filter(|m| !m.requires_auth())
707            .map(|m| m.name())
708            .collect();
709        assert_eq!(actual_open, expected_open);
710    }
711
712    /// **The gated wallet methods are the push, the arrival cursor, the three enrolment methods,
713    /// and the three reservation methods.** The fixture varies one thing -- which wallet method is asked -- against a category
714    /// whose other members ARE open, so both nearest wrong implementations fail here: one that opens
715    /// the whole category (the state this crate shipped in at `1190a18`) and one that gates it
716    /// wholesale.
717    ///
718    /// Written out in catalog order rather than derived, so a method joining the gated side is a
719    /// deliberate edit here -- the review step a broadcast, or an enrolment, must never slip past.
720    #[test]
721    fn the_gated_wallet_methods_are_the_push_the_cursor_and_enrolment() {
722        let gated: Vec<&str> = ControlMethod::ALL
723            .iter()
724            .filter(|m| m.category() == Category::Wallet && m.requires_auth())
725            .map(|m| m.name())
726            .collect();
727        assert_eq!(
728            gated,
729            vec![
730                "control.wallet.arrivals",
731                "control.wallet.broadcast",
732                "control.wallet.watch",
733                "control.wallet.unwatch",
734                "control.wallet.watched",
735                "control.wallet.reservations.held",
736                "control.wallet.reservations.reserve",
737                "control.wallet.reservations.release",
738            ]
739        );
740        assert!(!ControlMethod::WalletBroadcast.is_open_read());
741    }
742
743    /// **The arrival cursor is NOT an open read, and the reason is not "is it a chain read?".**
744    ///
745    /// The rule is *who names the address*. `control.wallet.arrivals` takes only a cursor, so the
746    /// node volunteers its OWN watched puzzle hashes and the receive history behind them -- the
747    /// node-to-address association, which is not public, and which a token-less caller could then
748    /// replay into the caller-addressed reads.
749    ///
750    /// The control keeps `control.wallet.coinById` in the same assertion: it is the neighbour the
751    /// analogy was drawn from, it is still open, and it stays open because its CALLER supplies the
752    /// coin id. Without that control this test would also pass on a wholesale gating of the wallet
753    /// category, which is a different (and wrong) implementation.
754    #[test]
755    fn the_arrival_cursor_is_not_an_open_read() {
756        assert!(
757            !ControlMethod::WalletArrivals.is_open_read(),
758            "control.wallet.arrivals discloses this node's OWN watched puzzle hashes to a caller \
759             that supplied nothing, so it MUST NOT be served token-less"
760        );
761        assert!(ControlMethod::WalletArrivals.requires_auth());
762        assert!(
763            ControlMethod::WalletCoinById.is_open_read(),
764            "the caller-addressed reads stay open -- the fix is the membership rule, not gating \
765             the wallet category"
766        );
767    }
768
769    /// **The control plane names every chain primitive `ChainSource` needs.**
770    ///
771    /// The list is written out rather than derived, because the property under test is a claim about
772    /// ANOTHER crate's trait (`dig-chainsource-interface`'s `ChainSource`) that no compiler here can
773    /// check. Five of its seven methods need a control method of their own. The other two need none:
774    /// `parent_spend` is a trait DEFAULT composed from `coin_record` + `coin_spend`, and
775    /// `resolve_singleton_lineage` is composed CLIENT-side from the primitives below rather than
776    /// served as a walk the node performs.
777    ///
778    /// `block_timestamp` is deliberately ABSENT from the control plane. dig-node's light client
779    /// (`chia-peer`'s `ChiaPeerProvider`) does not index block timestamps and answers `Unsupported`,
780    /// so a control method for it could only ever be refused — a surface that looks live and does
781    /// nothing. A consumer mirrors that refusal honestly; if one ever genuinely needs the value, the
782    /// method is an additive minor at that point.
783    ///
784    /// A missing name here is not a cosmetic gap: a client that cannot answer one of these cannot
785    /// implement the trait at all, which is what made a dig-profile mint structurally impossible
786    /// through the node before these two were added (dig_ecosystem#2572).
787    #[test]
788    fn the_catalog_serves_every_chain_source_primitive() {
789        for wire in [
790            "control.wallet.coinById",      // coin_record
791            "control.wallet.coins",         // coin_records_by_puzzle_hash
792            "control.wallet.peak",          // peak_height
793            "control.wallet.coinsByParent", // coin_records_by_parent
794            "control.wallet.coinSpend",     // coin_spend
795        ] {
796            assert!(
797                ControlMethod::from_name(wire).is_some(),
798                "{wire} is required to implement ChainSource over the control plane"
799            );
800        }
801    }
802
803    /// **The two chain primitives are `coinById`'s neighbours, not `arrivals`'.**
804    ///
805    /// Each takes a caller-supplied coin id and returns a deterministic public chain fact,
806    /// so the membership rule — *who names the subject* — puts them on the open side. The gated
807    /// control in the same assertion is what makes the test load-bearing: without it, a wholesale
808    /// opening of the wallet category would pass, and that is a different (and wrong) implementation.
809    #[test]
810    fn the_chain_primitives_are_caller_named_open_reads() {
811        for method in [
812            ControlMethod::WalletCoinSpend,
813            ControlMethod::WalletCoinsByParent,
814        ] {
815            assert!(
816                method.is_open_read(),
817                "{} names its subject in the request and discloses no node-to-address \
818                 association, exactly like control.wallet.coinById",
819                method.name()
820            );
821            assert!(!method.requires_auth());
822        }
823        assert!(
824            ControlMethod::WalletArrivals.requires_auth(),
825            "the caller-supplies-nothing read stays gated -- the rule is who names the subject, \
826             not whether the bytes are on chain"
827        );
828        assert!(ControlMethod::WalletBroadcast.requires_auth());
829    }
830
831    /// **All three enrolment methods are gated — including the one that only reads.**
832    ///
833    /// `control.wallet.watch` and `.unwatch` aim what the node follows, so they are mutations and the
834    /// question barely arises. `control.wallet.watched` is the one a future reader will be tempted to
835    /// open, because it returns nothing but public keys and every other wallet READ in this catalog is
836    /// open. It stays gated under the SAME rule that gates `control.wallet.arrivals`: the caller
837    /// supplies nothing, so the node volunteers its OWN enrolled keys — the node-to-key association,
838    /// which is not public, and which a token-less caller could replay straight into the
839    /// caller-addressed reads.
840    ///
841    /// The control keeps `control.wallet.coinById` open in the same assertion. Without it this test
842    /// would also pass on a wholesale gating of the wallet category, which is a different (and wrong)
843    /// implementation.
844    #[test]
845    fn the_enrolment_methods_are_gated_including_the_read() {
846        for wire in [
847            "control.wallet.watch",
848            "control.wallet.unwatch",
849            "control.wallet.watched",
850        ] {
851            let method = ControlMethod::from_name(wire)
852                .unwrap_or_else(|| panic!("{wire} must be in the catalog"));
853            assert!(
854                !method.is_open_read(),
855                "{wire} either aims this node's subscriptions or names the keys it already \
856                 follows, so it MUST NOT be served token-less"
857            );
858            assert!(method.requires_auth(), "{wire} must require the token");
859            assert_eq!(method.category(), Category::Wallet);
860            assert_eq!(method.routing(), Routing::Delegated);
861        }
862        assert!(
863            ControlMethod::WalletCoinById.is_open_read(),
864            "the caller-addressed reads stay open -- enrolment is gated by the membership rule, \
865             not by gating the wallet category"
866        );
867    }
868
869    #[test]
870    fn only_pairing_bootstrap_is_open_bootstrap_routed() {
871        for &m in ControlMethod::ALL {
872            let open_bootstrap = matches!(
873                m,
874                ControlMethod::PairingRequest | ControlMethod::PairingPoll
875            );
876            assert_eq!(
877                m.routing() == Routing::OpenBootstrap,
878                open_bootstrap,
879                "{} routing mismatch",
880                m.name()
881            );
882        }
883    }
884
885    #[test]
886    fn pairing_admin_methods_are_exactly_three() {
887        let admin: Vec<&str> = ControlMethod::ALL
888            .iter()
889            .filter(|m| m.is_pairing_admin())
890            .map(|m| m.name())
891            .collect();
892        assert_eq!(
893            admin,
894            vec![
895                "control.pairing.list",
896                "control.pairing.approve",
897                "control.pairing.revoke"
898            ]
899        );
900    }
901
902    /// **The master-token tier is the pairing lifecycle PLUS the trusted-peer mutations.**
903    ///
904    /// The set is asserted whole, because the risk is a method quietly joining or leaving it. The
905    /// two non-pairing members are here for a stated reason — `chiaPeers.add` grants authority
906    /// that SURVIVES `pairing.revoke`, so a paired token holding it escapes the very remedy for a
907    /// compromised paired app.
908    #[test]
909    fn the_master_token_tier_is_pairing_admin_plus_the_trusted_peer_mutations() {
910        let master: BTreeSet<&str> = ControlMethod::ALL
911            .iter()
912            .filter(|m| m.requires_master_token())
913            .map(|m| m.name())
914            .collect();
915        let expected: BTreeSet<&str> = [
916            "control.pairing.list",
917            "control.pairing.approve",
918            "control.pairing.revoke",
919            "control.chiaPeers.add",
920            "control.chiaPeers.remove",
921        ]
922        .into_iter()
923        .collect();
924        assert_eq!(master, expected);
925
926        // Pairing administration is a STRICT subset, not a synonym: a gate that consults
927        // `is_pairing_admin` instead of `requires_master_token` lets a paired token add a peer.
928        for &m in ControlMethod::ALL {
929            assert!(
930                !m.is_pairing_admin() || m.requires_master_token(),
931                "{} is pairing-admin but not master-tier",
932                m.name()
933            );
934        }
935        assert!(
936            master.len()
937                > ControlMethod::ALL
938                    .iter()
939                    .filter(|m| m.is_pairing_admin())
940                    .count(),
941            "the two predicates must not be interchangeable"
942        );
943
944        // Master implies the token is required at all.
945        for &m in ControlMethod::ALL {
946            assert!(
947                !m.requires_master_token() || m.requires_auth(),
948                "{}",
949                m.name()
950            );
951        }
952    }
953
954    /// **The trust wording stays inside NC-12's authorisation: a node the operator RUNS.**
955    ///
956    /// NC-12 permits trust only from "the operator declaring it their own node". Widening that to
957    /// vouching moves the case outside the justification for the unbounded authority the entry
958    /// carries, and "a node you vouch for" is a phrase somebody can be talked into applying to a
959    /// stranger's address.
960    #[test]
961    fn the_add_summary_authorises_only_a_node_the_operator_runs() {
962        let summary = ControlMethod::ChiaPeersAdd.summary().to_lowercase();
963        assert!(
964            summary.contains("a node you run"),
965            "add must name the operator-run scope, got: {summary}"
966        );
967        for widened in ["vouch", "otherwise trust", "trust yourself", "recommend"] {
968            assert!(
969                !summary.contains(widened),
970                "add summary widens operator trust past NC-12 with {widened:?}: {summary}"
971            );
972        }
973    }
974
975    #[test]
976    fn delegated_set_matches_the_engine_surface() {
977        let delegated: BTreeSet<&str> = ControlMethod::ALL
978            .iter()
979            .filter(|m| m.routing() == Routing::Delegated)
980            .map(|m| m.name())
981            .collect();
982        let expected: BTreeSet<&str> = [
983            "control.wallet.coins",
984            "control.wallet.coinById",
985            "control.wallet.coinSpend",
986            "control.wallet.coinsByParent",
987            "control.wallet.arrivals",
988            "control.wallet.peak",
989            "control.wallet.syncStatus",
990            "control.wallet.broadcast",
991            "control.wallet.watch",
992            "control.wallet.unwatch",
993            "control.wallet.watched",
994            "control.wallet.reservations.held",
995            "control.wallet.reservations.reserve",
996            "control.wallet.reservations.release",
997            "control.profile.putBody",
998            "control.profile.getBody",
999            "control.peerStatus",
1000            "control.peerCounts",
1001            "control.peers.connect",
1002            "control.peers.disconnect",
1003            "control.subscribe",
1004            "control.unsubscribe",
1005            "control.listSubscriptions",
1006            "control.wallet.balance",
1007        ]
1008        .into_iter()
1009        .collect();
1010        assert_eq!(delegated, expected);
1011    }
1012
1013    /// **The trusted-Chia-peer methods are declared, gated, and say what they cost.**
1014    ///
1015    /// A trusted peer BYPASSES corroboration (NC-12: dialled peers are untrusted and agreement
1016    /// across ~5 concurrently-queried peers is what makes a read safe). The catalog is what a
1017    /// machine reads before offering the control, so the cost is stated HERE and not only in a
1018    /// doc page — a client that surfaces `summary()` surfaces the warning with it.
1019    #[test]
1020    fn the_trusted_chia_peer_methods_are_gated_and_disclose_the_corroboration_bypass() {
1021        let declared: BTreeSet<&str> = ControlMethod::ALL.iter().map(|m| m.name()).collect();
1022        for name in [
1023            "control.chiaPeers.add",
1024            "control.chiaPeers.list",
1025            "control.chiaPeers.remove",
1026        ] {
1027            assert!(declared.contains(name), "{name} is not in the catalog");
1028            let m = ControlMethod::from_name(name).expect("from_name round-trips");
1029            assert_eq!(m.category(), Category::Peers, "{name} is a peers method");
1030            assert_eq!(m.routing(), Routing::Owned, "{name} is served by the shell");
1031            assert!(m.requires_auth(), "{name} must require the control token");
1032            assert!(!m.is_open_read(), "{name} is not an open read");
1033        }
1034        // The MUTATIONS need the MASTER token; the READ deliberately does not. `add` writes
1035        // standing, corroboration-free authority that outlives the token that wrote it — a paired
1036        // token must not be able to install it, and `remove` is the only way back out.
1037        assert!(ControlMethod::ChiaPeersAdd.requires_master_token());
1038        assert!(ControlMethod::ChiaPeersRemove.requires_master_token());
1039        assert!(
1040            !ControlMethod::ChiaPeersList.requires_master_token(),
1041            "list grants nothing that outlives the token; gating it would blind a paired client \
1042             to the trust state it is subject to"
1043        );
1044        // The COST, not merely the capability: the two methods that change the trusted set must
1045        // name the bypass. A summary that only described the action would let a client offer the
1046        // control while silently withholding what it gives up.
1047        for name in ["control.chiaPeers.add", "control.chiaPeers.remove"] {
1048            let summary = ControlMethod::from_name(name).unwrap().summary();
1049            assert!(
1050                summary.to_lowercase().contains("corroboration"),
1051                "{name} summary must name the corroboration bypass, got: {summary}"
1052            );
1053        }
1054    }
1055
1056    #[test]
1057    fn every_method_has_a_nonempty_summary() {
1058        for &m in ControlMethod::ALL {
1059            assert!(!m.summary().is_empty(), "{} has no summary", m.name());
1060        }
1061    }
1062}