Skip to main content

decdn_common/
admin.rs

1//! Wire types for the loopback admin JSON-RPC surface (`appendix-local-admin-http.md`).
2//!
3//! Shared between the daemon (which implements `AdminRpcServer` over a
4//! local cache + peer table) and the user CLI (which speaks
5//! [`AdminRpcClient`] from `decdn node …`). jsonrpsee's `#[rpc]` macro
6//! consumes the source `AdminRpc` trait and emits `AdminRpcClient` in its
7//! place, plus `AdminRpcServer` under the `admin-server` feature, which only
8//! the daemon enables: the client SDK and the CLI link no JSON-RPC server.
9//! The original `AdminRpc` name is not a linkable rustdoc item, hence the
10//! bare backticks.
11//!
12//! DTO fields are deliberately wire-only: no engine handles, no
13//! peer-table types, no daemon runtime types. They use simple owned
14//! values (`String`, `u64`, primitive arrays). Pulling `decdn-common`
15//! into the CLI does not pull the daemon runtime.
16//!
17//! The helper [`parse_hash_arg`] returns [`struct@Hash`] from the
18//! `decdn-config-types` leaf crate (the same leaf the typed config
19//! fields `DecompressMode`, `RetryPolicy`, `OriginUrl`, `PinnedHashes`
20//! come from). That keeps `decdn-cache`/iroh-blobs out of the publisher
21//! CLI's dependency tree (#578); the daemon's `evict` handler converts
22//! the leaf hash to the blob-store hash at its boundary via
23//! `decdn_cache::to_store_hash`. The parser is used only by that
24//! handler today.
25
26use decdn_config_types::Hash;
27// The trait's `RpcResult<T>` returns are read by the macro, and only the
28// server half it emits names the type.
29#[cfg(feature = "admin-server")]
30use jsonrpsee::core::RpcResult;
31use jsonrpsee::proc_macros::rpc;
32use jsonrpsee::types::ErrorObjectOwned;
33use serde::{Deserialize, Serialize};
34
35/// Whether the node's local iroh key is the one bound to its operator address
36/// on-chain (#1034).
37///
38/// This is a correctness signal, not a liveness one. `SlashJudge` resolves an
39/// accused node through `CapacityBond.nodeIdOf`, so a node serving under a key
40/// no binding points at is **unslashable**: it earns normally while its bond is
41/// unreachable, which is a protocol fault rather than an outage — and one with
42/// no symptom the operator would otherwise notice. A key rotation that swapped
43/// `node.secret` without submitting `bindNodeId` lands exactly here, which is
44/// why `decdn node rotate-key` orders its steps to make the state unreachable
45/// and why the daemon reports it when it happens anyway.
46///
47/// Advisory by construction. The check is one RPC at bring-up, and a daemon
48/// that refused to start on it would be brickable by a transient RPC failure
49/// and unable to run the very rotation that repairs it.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "snake_case")]
52pub enum BindingStatus {
53    /// The on-chain binding names this node's key. Nothing to do.
54    Bound,
55    /// The operator is bound to a DIFFERENT node id than the local key —
56    /// the un-slashable state. Either rotate on-chain to match the local key
57    /// (`decdn node rotate-key --key iroh --bind-existing`) or restore the
58    /// key the binding names. Sampled once at bring-up like every other
59    /// variant here, so a live repair does not clear this to `Bound` until
60    /// the daemon restarts — a `mismatch` seen right after running
61    /// `--bind-existing` is not a failed repair, just a stale sample.
62    Mismatch,
63    /// The operator address has no binding at all: never registered, or the
64    /// node id was reclaimed. `decdn node register` makes the initial binding.
65    Unbound,
66    /// Not determined — no `[blockchain]` configuration to check against, or
67    /// the read failed. Explicitly not a synonym for "fine".
68    Unknown,
69}
70
71/// Response body for `admin_v1_health`. Shared between the server
72/// (serializes) and `decdn node health` (deserializes via the generated
73/// client). Intentionally minimal: this method exists so an operator
74/// script can answer "is this admin port the node I think it is, and
75/// has it been up since I started watching?" with one RPC call.
76#[derive(Debug, Clone, Serialize, Deserialize)]
77pub struct HealthResponse {
78    /// Lowercase hex of this node's iroh `PublicKey`.
79    pub node_id: String,
80    /// Whole seconds since the runtime captured the process-start
81    /// `Instant` at the top of `decdn-node run` (before any `await`,
82    /// before the RPC preflight). Computed from a monotonic `Instant`
83    /// so wall-clock skew can't produce a negative or non-monotonic
84    /// value.
85    pub uptime_s: u64,
86    /// Currently in-flight QUIC handler tasks holding a dispatch permit
87    /// (read off the `decdn_dispatch_in_flight` gauge — see
88    /// `ConnectionLimiter` in `decdn-node`). Polled by `decdn node drain
89    /// --wait` (issue #604) to detect when all client streams have
90    /// completed during a graceful drain.
91    pub in_flight_streams: u64,
92    /// Whether `node_id` is the key bound to this operator on-chain (#1034).
93    /// Sampled once at bring-up — the binding only changes by an explicit
94    /// operator transaction, and re-reading it on every health poll would put
95    /// an RPC round trip behind the readiness probe.
96    pub binding: BindingStatus,
97    /// Lowercase hex of the node id the operator IS bound to, when that could
98    /// be read. Present for [`BindingStatus::Bound`] (where it equals
99    /// `node_id`) and, more usefully, for [`BindingStatus::Mismatch`], where it
100    /// names the key to restore. `None` for `Unbound` and `Unknown`.
101    pub bound_node_id: Option<String>,
102    /// Whether this node is in the on-chain active-staker set right now
103    /// (ADR 019 §Phase 4, criterion 1; #1030).
104    ///
105    /// Purely diagnostic. The daemon does **not** gate delivery on it — a node
106    /// policing its own registration constrains only operators who were never
107    /// the threat (see ADR 019 §How criterion 1 is enforced). What `false`
108    /// means is that the two EXTERNAL constraints are in force: the operator
109    /// accrues no governance weight, because its declared capacity caps
110    /// credited bytes at zero, and peers have no reason to route to a node they
111    /// cannot slash.
112    ///
113    /// Unlike [`Self::binding`], this is read LIVE on every poll — it is a
114    /// lookup in the registry projection the daemon already keeps current off
115    /// `CapacityBond` events, not a chain round trip — so an operator who has
116    /// just run `decdn setup` watches it flip to `true` without restarting the
117    /// daemon.
118    ///
119    /// `false` is the answer to "my node is up and healthy, why is it earning
120    /// nothing". Nothing on the wire says so; the traffic simply does not
121    /// arrive. The cause is one of never registered, registered under a key
122    /// this process no longer holds (see [`Self::binding`]), deregistered,
123    /// ejected, bond below `minBond`, or an unbonding request in flight.
124    pub registry_active: bool,
125}
126
127/// Request body for `admin_v1_evict` (issue #279).
128#[derive(Debug, Clone, Serialize, Deserialize)]
129pub struct EvictRequest {
130    /// Hex of the BLAKE3 hash to evict. Must be exactly 64 hex characters
131    /// (mixed case accepted, optional `0x`/`0X` prefix tolerated); rejected
132    /// at the server with `INVALID_PARAMS` otherwise.
133    pub hash: String,
134    /// If `true`, return only the pre-evict snapshot (size, last access,
135    /// pin status, already-evicted flag) without mutating cache state
136    /// (issue #379). Backs `decdn node evict --dry-run`. Required: a caller
137    /// states whether it wants the real evict.
138    pub dry_run: bool,
139}
140
141/// Response body for `admin_v1_evict`.
142///
143/// Carries both the pre-evict snapshot (always populated, so an operator's
144/// audit log captures size and pin status at the moment of evict) and a
145/// `dry_run` flag indicating whether the cache state was actually mutated.
146#[derive(Debug, Clone, Serialize, Deserialize, Default)]
147pub struct EvictResponse {
148    /// Whether the hash would have been served by the cache before this
149    /// call (i.e. `BlobStatus::Complete` *and* not already evicted).
150    /// `false` means the evict was a no-op safety measure (blob never
151    /// cached, or already in `evicted.log`). For a real evict the
152    /// effect is durable; for a dry-run no effect is committed and the
153    /// `was_present` snapshot describes the current state only.
154    pub was_present: bool,
155    /// `true` when this response describes a dry-run preview — the
156    /// cache state was *not* mutated and only [`Self::preview`] is
157    /// meaningful. `false` means the eviction was applied per the
158    /// existing `admin_v1_evict` behaviour.
159    pub dry_run: bool,
160    /// Pre-evict snapshot of the blob's local-cache state (#379).
161    /// Populated for both real and dry-run calls so an operator's
162    /// audit log captures size and pin status at the moment of
163    /// evict. The struct is nested (rather than flattened into
164    /// [`Self`]) so the `--dry-run` view doesn't push the bool count
165    /// past the `clippy::struct_excessive_bools` threshold and so a
166    /// future addition to the snapshot doesn't churn the top-level
167    /// response shape.
168    pub preview: EvictPreview,
169}
170
171/// Pre-evict snapshot returned inside [`EvictResponse::preview`].
172/// Mirrors the cache engine's `EvictionPreview` minus the
173/// engine-internal `served` field (folded into
174/// [`EvictResponse::was_present`]).
175#[derive(Debug, Clone, Serialize, Deserialize, Default)]
176pub struct EvictPreview {
177    /// Bytes the iroh-blobs store reports for this hash, read straight
178    /// from the underlying store regardless of evicted-log state.
179    /// `None` when the blob isn't in the store. A complete blob reports its
180    /// byte length. A partial blob (an interrupted or range pull) reports
181    /// the whole blob's validated size once its last chunk has arrived, and
182    /// `None` before — not the bytes it holds on disk.
183    pub size_bytes: Option<u64>,
184    /// Microseconds elapsed since the last recorded access to this hash: a
185    /// serve, a hit, or a fill. `None` when the hash has had no access since
186    /// the node started — including a blob on disk at start that nothing has
187    /// touched since — or when eviction or quarantine has cleared its entry.
188    pub last_accessed_us_ago: Option<u64>,
189    /// Whether the hash is in the operator-pinned set (#276).
190    /// Pinning protects against LRU eviction but **not** against an
191    /// explicit `admin_v1_evict`; surfaced here so dry-run callers
192    /// can confirm policy state before issuing the real takedown.
193    pub pinned: bool,
194    /// Whether the hash is already in `<cache_dir>/evicted.log`.
195    /// `true` means a real `admin_v1_evict` would short-circuit
196    /// (idempotent re-run, no log line appended).
197    pub already_evicted: bool,
198    /// Ordered list of origin backends the node would consult on a
199    /// post-eviction miss (#439, #284). Empty when the engine has no
200    /// origin configured (cache-only mode); a single-element vec is
201    /// the common single-origin case. Operators running DMCA takedowns or
202    /// LRU sweeps use this to estimate worst-case origin egress cost
203    /// — re-pulling from a `Filesystem` origin is a local read;
204    /// re-pulling through a chain of `Http`/`S3` mirrors multiplies
205    /// the metered-bandwidth bill on a deep fallback.
206    ///
207    /// `skip_serializing_if = "Vec::is_empty"` elides the field
208    /// entirely in cache-only mode, keeping the JSON output minimal;
209    /// `default` reads that elided field back as the empty list.
210    #[serde(default, skip_serializing_if = "Vec::is_empty")]
211    pub origin_kinds: Vec<decdn_config_types::OriginKind>,
212}
213
214/// Response body for `admin_v1_reload` (issue #373). Reports the
215/// post-reload values the SIGHUP arm logs to stdout, so operators using
216/// the RPC path get the same after-state confirmation without scraping
217/// `tracing` output. Only the *reloadable* fields appear here: changes
218/// to non-reloadable sections are logged by the reload path itself
219/// (one `info!` per changed-but-ignored field) and aren't echoed in
220/// the RPC response.
221#[derive(Debug, Clone, Serialize, Deserialize)]
222pub struct ReloadResponse {
223    /// `observability.log_level` after the reload, lowercase
224    /// (`"trace"` / `"debug"` / `"info"` / `"warn"` / `"error"`) — same
225    /// spelling the resolver and config file accept. `"unknown"` only
226    /// appears on the (unreachable post-success) path where the reload
227    /// committed a level but the snapshot mutex was poisoned by a
228    /// concurrent reader; emitted as a string rather than a literal so
229    /// operator scripts can parse one stable shape.
230    pub log_level: String,
231}
232
233/// Request body for `admin_v1_drain` (issue #244). Required, as is its
234/// one field: a caller states which shutdown ordering it wants.
235#[derive(Debug, Clone, Serialize, Deserialize)]
236pub struct DrainRequest {
237    /// When `true`, ask the runtime to keep the admin server alive
238    /// *through* `router.shutdown` instead of closing it early (issue
239    /// #604). This is the opt-in seam for `decdn node drain --wait`: the
240    /// CLI polls `admin_v1_health` for `in_flight_streams == 0` and the
241    /// admin port must stay open long enough for that loop to observe
242    /// completion. `false` keeps the SIGTERM ordering (admin closes
243    /// before `router.shutdown`); `true` only reorders that single drain.
244    pub wait_admin: bool,
245}
246
247/// Response body for `admin_v1_drain` (issue #244). `initiated: true`
248/// reports that the trigger fired; `wait_admin_honored` reports
249/// whether the server actually plans to keep admin alive through
250/// `router.shutdown` (issue #604). The trigger is first-writer-wins, so
251/// a `wait_admin: true` request that loses the race to an earlier drain
252/// without it gets `false` here. The `decdn node drain --wait` client
253/// then refuses to enter the polling loop instead of treating the
254/// imminent ECONNREFUSED as drain completion. A `true` ack covers
255/// admin-RPC races only: a SIGINT/SIGTERM that wins the runtime's
256/// shutdown select still closes admin early.
257#[derive(Debug, Clone, Default, Serialize, Deserialize)]
258pub struct DrainResponse {
259    /// `true` once the trigger has been fired and the runtime's
260    /// shutdown sequence is underway. "Initiated", not "completed":
261    /// when `wait_admin_honored` is `false`, the admin server may
262    /// close before the response itself is delivered (the SIGTERM
263    /// ordering).
264    pub initiated: bool,
265    /// `true` when the server received `wait_admin: true` *and* is
266    /// keeping admin alive through `router.shutdown` on this drain.
267    /// The `--wait` client treats `false` as "server cannot observe
268    /// completion safely" and refuses to poll.
269    pub wait_admin_honored: bool,
270}
271
272/// Per-bucket fill stat for `admin_v1_status` (issue #741). One entry
273/// per *non-empty* Kademlia k-bucket — empty buckets (the vast majority
274/// of the 256-bucket keyspace on a small network) are omitted so the
275/// snapshot stays compact. The bucket capacity is the same Kademlia `K`
276/// for every bucket and so lives once on [`RoutingHealth::bucket_capacity`]
277/// rather than being repeated here.
278#[derive(Debug, Clone, Serialize, Deserialize)]
279pub struct BucketStat {
280    /// Bucket index `0..=255` (XOR-distance shell from this node's id).
281    pub index: u16,
282    /// Live peers currently held in the bucket
283    /// (`1..=`[`RoutingHealth::bucket_capacity`]).
284    pub fill: u16,
285}
286
287/// Routing-table health section of `admin_v1_status` (issue #741).
288#[derive(Debug, Clone, Serialize, Deserialize)]
289pub struct RoutingHealth {
290    /// Total peers across all buckets. Denormalized convenience for
291    /// `--json` consumers and the grep-stable summary line; equals the sum
292    /// of every [`BucketStat::fill`].
293    pub total_peers: u64,
294    /// Number of non-empty buckets. Denormalized convenience equal to
295    /// `buckets.len()`; kept as a stable `key=value` token on the summary
296    /// line so operator scripts need not sum the table.
297    pub non_empty_buckets: u64,
298    /// Per-bucket fill, one entry per non-empty bucket, ascending by index.
299    pub buckets: Vec<BucketStat>,
300    /// Maximum entries any bucket can hold (Kademlia `K`, currently 20).
301    /// One value for the whole table — the renderer pairs it with each
302    /// [`BucketStat::fill`] to show a per-bucket fill ratio.
303    pub bucket_capacity: u16,
304    /// Bucket-refresh interval in whole seconds (ADR 022 §Routing Table,
305    /// default 1 hour). The refresh task refreshes *every* non-empty
306    /// bucket once per interval.
307    pub refresh_interval_s: u64,
308    /// Microseconds-since-epoch the most recent bucket-refresh pass
309    /// completed, or `None` if no pass has run yet (node up less than one
310    /// interval). The refresh pass touches all non-empty buckets at once,
311    /// so this is a single network-wide timestamp rather than a per-bucket
312    /// value.
313    pub last_refresh_us: Option<u64>,
314}
315
316/// DHT provider-record store utilization for `admin_v1_status` (issue #741).
317#[derive(Debug, Clone, Serialize, Deserialize)]
318pub struct RecordStoreHealth {
319    /// Provider records currently held.
320    pub records: u64,
321    /// Global record cap (`RecordStoreConfig::max_records_global`).
322    pub capacity: u64,
323}
324
325/// Republish-scheduler health for `admin_v1_status` (issue #741).
326#[derive(Debug, Clone, Serialize, Deserialize)]
327pub struct RepublishHealth {
328    /// Content hashes currently scheduled for periodic republish.
329    pub scheduled_records: u64,
330}
331
332/// Response body for `admin_v1_status` (issue #741): a single-shot
333/// snapshot of this node's DHT participation health, so an operator can
334/// diagnose cold-start / routing-table degradation without scraping
335/// Prometheus or reading logs.
336#[derive(Debug, Clone, Serialize, Deserialize)]
337pub struct StatusResponse {
338    /// Lowercase hex of this node's iroh `PublicKey` — same encoding as
339    /// [`HealthResponse::node_id`].
340    pub node_id: String,
341    /// Kademlia routing-table health.
342    pub routing: RoutingHealth,
343    /// Active stakers known to this node (the chain-backed `StakerSet`
344    /// cardinality — the set the DHT admits records and routes from).
345    pub known_stakers: u64,
346    /// DHT provider-record store utilization.
347    pub record_store: RecordStoreHealth,
348    /// Republish-scheduler depth.
349    pub republish: RepublishHealth,
350    /// Number of origins currently in the on-chain origin deny-set
351    /// (`ContentBlacklist` origin blacklist, ADR 011). Read from the live
352    /// denylist the client handler and blacklist watcher share; `0` when no
353    /// denylist is wired.
354    pub chain_denied_origins: u64,
355    /// The operator Ethereum address this node runs under — the wallet it is
356    /// funded, bonded, registered, and paid under. Rendered as an EIP-55
357    /// mixed-case checksummed hex string (`0x`-prefixed), the same encoding
358    /// [`LaneSnapshot::counterparty`] uses. Sampled once at bring-up from the
359    /// loaded eth keystore (the same value the node-id binding check derives),
360    /// not re-read per call. `None` when the operator can't be resolved — an
361    /// `AdminState` with no chain wiring (unit tests, cache-only nodes) —
362    /// matching how [`HealthResponse::bound_node_id`] degrades. The address is
363    /// public; no key material is ever exposed here.
364    pub operator_address: Option<String>,
365}
366
367/// JSON view of one lane this node provides against a `PaymentPool`,
368/// emitted by `admin_v1_lanes` (issue #749). A lane is keyed by
369/// `(pool_id, signer, provider)` — `decdn_incentive::LaneKey`. Defined
370/// separately from `decdn-incentive`'s internal `LaneState` so the
371/// replay-critical `last_*` accessors, the `U256` money types, and any
372/// future internal fields can't leak into the wire format: every field
373/// here is a plain owned wire value. Shared between the server
374/// (serializes) and `decdn node lanes` (deserializes via the generated
375/// client).
376///
377/// Money amounts are reported in **micro-USDC** (`u64`) — the same base
378/// unit `blockchain.redeem_threshold_micro_usdc` is configured in. The
379/// underlying `LaneState` carries them as `U256`; the server narrows with
380/// `u64::try_from(...).unwrap_or(u64::MAX)`, so a value that somehow
381/// exceeded `u64::MAX` micro-USDC (~1.8e13 USDC — unreachable for a real
382/// pool) saturates rather than wraps.
383#[derive(Debug, Clone, Serialize, Deserialize)]
384pub struct LaneSnapshot {
385    /// Lowercase hex of the on-chain `PaymentPool` id (`LaneKey::pool_id`),
386    /// `0x`-prefixed — same 32-byte encoding `alloy`'s `B256` `Display`
387    /// produces. Shared by every lane drawing from the same pool.
388    pub pool_id: String,
389    /// The pool owner's Ethereum address — the deposit owner and refund
390    /// destination, and the subject of the ADR-011 blacklist gates.
391    /// Rendered as an EIP-55 mixed-case checksummed hex string
392    /// (`0x`-prefixed) — `alloy`'s `Address` `Display`. Note this differs
393    /// from an iroh node id, which is plain lowercase hex of an Ed25519
394    /// public key (a different identity type, not an EVM address). It is
395    /// *not* necessarily the voucher signer — see [`Self::voucher_signer`].
396    pub counterparty: String,
397    /// The capability signer authorizing vouchers on this lane
398    /// (`LaneKey::signer`): the EIP-712 recovery target for every voucher,
399    /// in the same EIP-55 rendering as [`Self::counterparty`]. Equal to
400    /// `counterparty` for the ordinary self-signing case, and a distinct
401    /// delegate key when the pool owner delegated signing.
402    pub voucher_signer: String,
403    /// Sequence number of the most-recently-accepted voucher. Not tracked
404    /// in the shared-pool model (a pool has no per-lane nonce), so this
405    /// always reports `0`.
406    pub last_nonce: u64,
407    /// Cumulative amount of the most-recently-accepted voucher, in
408    /// micro-USDC (`LaneState::last_amount`). This is the node's total
409    /// accrued claim on this lane — the figure that crosses the
410    /// redemption threshold. `0` before any voucher.
411    pub outstanding_micro_usdc: u64,
412    /// Not tracked in the shared-pool model (the pool's deposit is shared
413    /// across every lane it funds, so no single lane owns a deposit), so
414    /// this always reports `0`.
415    pub deposit_micro_usdc: u64,
416    /// Whole seconds since this process last accepted a voucher on this
417    /// lane, or `None` when no voucher has been observed *since the node
418    /// started*. The activity clock is in-memory: a lane hydrated from
419    /// `lanes.redb` at boot reports `None` until its next voucher, because
420    /// the persisted `LaneState` carries no last-voucher wall-clock.
421    /// Operators use this to spot stale lanes (high `outstanding` but no
422    /// recent vouchers).
423    pub seconds_since_last_voucher: Option<u64>,
424    /// `true` when the accrued claim (`outstanding_micro_usdc`) has
425    /// reached the node's configured redemption threshold
426    /// (`blockchain.redeem_threshold_micro_usdc`), i.e. the redeemer would
427    /// redeem this lane on its next tick. This is an **upper-bound**
428    /// signal: the admin surface does not read the on-chain redeemed
429    /// amount, so it compares the full accrued claim (not the
430    /// un-redeemed delta) against the threshold. A lane that already
431    /// redeemed up to its current claim may still report `true` until the
432    /// next voucher advances it — surfaced so operators can see which
433    /// lanes are *at or above* the redemption bar.
434    pub settlement_eligible: bool,
435}
436
437/// Response body for `admin_v1_lanes` (issue #749). Shared between the
438/// server (serializes), `decdn node lanes` (deserializes via the
439/// generated client), and the integration tests.
440#[derive(Debug, Clone, Serialize, Deserialize)]
441pub struct LanesResponse {
442    /// One entry per lane the node currently tracks. Ordering is most
443    /// recently active first (lanes with a known last-voucher time ahead
444    /// of those without), then by descending outstanding amount — the
445    /// on-call use case is "which lanes are closest to a settlement /
446    /// liquidity event?".
447    pub lanes: Vec<LaneSnapshot>,
448    /// The node's configured redemption threshold in micro-USDC
449    /// (`blockchain.redeem_threshold_micro_usdc`). Echoed once at the top
450    /// level — rather than repeated per lane — so the renderer can show
451    /// the bar each [`LaneSnapshot::settlement_eligible`] is measured
452    /// against without the operator cross-referencing the config.
453    pub redeem_threshold_micro_usdc: u64,
454}
455
456/// One lane the node pays on, as the buyer's own store records it
457/// (`admin_v1_pools`). The buyer-side mirror of [`LaneSnapshot`]: where that
458/// reports what a lane has accrued *against* this node, this reports what this
459/// node has already promised to pay a provider.
460#[derive(Debug, Clone, Serialize, Deserialize)]
461pub struct BuyerLaneSnapshot {
462    /// The capability signer whose key authorized the vouchers on this lane
463    /// (`LaneKey::signer`), EIP-55 checksummed hex. Equal to the pool owner for
464    /// the ordinary self-signing case, and a delegate key otherwise.
465    pub voucher_signer: String,
466    /// The provider being paid on this lane (`LaneKey::provider`), EIP-55
467    /// checksummed hex.
468    pub provider: String,
469    /// Cumulative amount of the last voucher this node signed on the lane, in
470    /// micro-USDC. This is the node's own spend watermark: re-signing a lower
471    /// total is what strands a lane, so it is the figure to compare against
472    /// a provider's complaint.
473    pub last_amount_micro_usdc: u64,
474    /// Bytes delivered as of that same voucher.
475    pub last_bytes_delivered: u64,
476}
477
478/// One `PaymentPool` deposit the node's buyer leg tracks (`admin_v1_pools`).
479///
480/// The amounts are the *stored* ones, not a chain read: this is what the daemon
481/// believes, which is the half an operator cannot otherwise see. A disagreement
482/// with `PaymentPool.getPool` is itself the diagnostic.
483#[derive(Debug, Clone, Serialize, Deserialize)]
484pub struct BuyerPoolSnapshot {
485    /// The on-chain pool id, `0x`-prefixed 32-byte hex.
486    ///
487    /// Unique only within one deployment (`chain_id` and `payment_pool`): the
488    /// contract derives it as `keccak256(owner, ownerPoolNonce)` and a fresh
489    /// deployment restarts that nonce, so two deployments' Nth pools share an
490    /// id. Read it alongside `chain_id` and `payment_pool`, never alone.
491    pub pool_id: String,
492    /// The EIP-712 chain id of the deployment the row was written against.
493    pub chain_id: u64,
494    /// The `PaymentPool` the row was written against, EIP-55 checksummed hex.
495    ///
496    /// With `chain_id`, the only fields that tell a live pool from a same-id
497    /// pool on a deployment the node is not configured against — which is what
498    /// makes them the fields to check when a tracked id and an on-chain
499    /// enumeration appear to agree.
500    pub payment_pool: String,
501    /// The deposit owner — this node's operator address, EIP-55 checksummed hex.
502    pub owner: String,
503    /// The ERC-20 the pool is denominated in (USDC per ADR 003), EIP-55
504    /// checksummed hex.
505    pub token: String,
506    /// The pool's escrowed deposit in micro-USDC, as the store recorded it.
507    ///
508    /// The stored value is a `U256`; the server narrows with
509    /// `u64::try_from(..).unwrap_or(u64::MAX)`, so a deposit that somehow
510    /// exceeded `u64::MAX` micro-USDC (~1.8e13 USDC — unreachable for a real
511    /// pool) saturates rather than wraps. The same holds for every
512    /// `U256`-derived field on [`BuyerLaneSnapshot`], including
513    /// `last_bytes_delivered`.
514    pub deposit_micro_usdc: u64,
515    /// Every lane funded from this pool, ordered by `(signer, provider)`. One
516    /// pool fans out to every provider the owner pays (ADR 003), so this is
517    /// where the pool's spend is actually visible.
518    pub lanes: Vec<BuyerLaneSnapshot>,
519}
520
521/// Snapshot of the node's buyer-side `PaymentPool` state (`admin_v1_pools`).
522///
523/// This is the only way to read `buyer.redb` on a running node: `redb` holds a
524/// process-exclusive lock on that file for the daemon's lifetime, so no CLI can
525/// open it — not even read-only — while the node is up.
526#[derive(Debug, Clone, Serialize, Deserialize)]
527pub struct BuyerPoolsResponse {
528    /// One entry per tracked pool, ordered by `pool_id` so the output is stable
529    /// across calls regardless of the store's internal key order.
530    pub pools: Vec<BuyerPoolSnapshot>,
531    /// `pool_id`s whose stored record would not decode, `0x`-prefixed hex.
532    /// Their deposits stay escrowed but untracked, so an empty [`Self::pools`]
533    /// beside a non-empty `skipped` does not mean "this node owns no pools".
534    pub skipped: Vec<String>,
535}
536
537/// One slash detected against this node's operator (`SlashJudge.Slashed`,
538/// #1032, G-NODE-05). Surfaced so an operator (or a keeper script) can notice a
539/// slash and file `decdn appeal slash` within the 30-day window without watching
540/// the chain directly.
541#[derive(Debug, Clone, Serialize, Deserialize)]
542pub struct SlashRecordDto {
543    /// The globally-monotonic on-chain `slashId` (`CapacityBond.slash`),
544    /// rendered as a decimal string — it is a `uint256` and can exceed `u64`.
545    /// This is the value passed to `decdn appeal slash <SLASH_ID>`.
546    pub slash_id: String,
547    /// Offense taxonomy index (ADR 014): `0` = `RateManipulation`,
548    /// `1` = Blacklist. Kept numeric to avoid drift if the enum grows.
549    pub offense_type: u8,
550    /// Bond amount slashed, in TOKEN base units, as a decimal string (`uint256`).
551    pub amount: String,
552    /// `keccak256` evidence digest from the `Slashed` event (ADR 014),
553    /// `0x`-prefixed 32-byte hex.
554    pub evidence_hash: String,
555    /// Block number the `Slashed` log was mined in, or `None` if the log was
556    /// still pending when observed (rare; live logs carry a block number).
557    pub block_number: Option<u64>,
558    /// **Nominal** appeal-window close (Unix seconds): the `Slashed` block
559    /// timestamp + 30 days, or `None` if the block read failed. This is a cheap
560    /// client-side hint, NOT read from the `CapacityBond` slash record, and it
561    /// ignores protocol-pause extensions — which only ever move the real
562    /// deadline *later* (`markAppealOpen` adds `pausedTotal`). Safe to file
563    /// before this; a keeper must not treat a just-past value as final.
564    pub appeal_window_close: Option<u64>,
565}
566
567/// Snapshot of every slash the watcher has detected against this node's
568/// operator (#1032). Empty list when none — a clean operator.
569#[derive(Debug, Clone, Serialize, Deserialize)]
570pub struct SlashesResponse {
571    /// One entry per distinct detected `slashId`, most-recent first.
572    pub slashes: Vec<SlashRecordDto>,
573}
574
575/// JSON-RPC error code: the request shape was wrong (bad hex, etc.).
576/// Matches the standard JSON-RPC 2.0 `Invalid params` code.
577pub const INVALID_PARAMS_CODE: i32 = -32_602;
578
579/// JSON-RPC error code: the cache layer reported an error during evict
580/// (e.g. the underlying iroh-blobs store I/O failed when persisting the
581/// evicted-hash log).
582pub const CACHE_ERROR_CODE: i32 = -32_002;
583
584/// JSON-RPC error code: the node was started without a config file
585/// path, so `admin_v1_reload` has nothing to re-read. Distinct from
586/// [`RELOAD_ERROR_CODE`] so an operator script can tell "this node
587/// can't reload, ever, until it's restarted with `--config <path>`"
588/// from "this node tried and failed".
589pub const CONFIG_PATH_UNSET_CODE: i32 = -32_003;
590
591/// JSON-RPC error code: `RuntimeReloadState::reload` returned an error
592/// (file unreadable, malformed TOML, rejected resolution, mutex poison,
593/// log-level setter failed). Mirrors the SIGHUP arm's "previous values
594/// retained" guarantee — by the time this surfaces, the running config
595/// is unchanged.
596pub const RELOAD_ERROR_CODE: i32 = -32_004;
597
598/// JSON-RPC error code: `admin_v1_status` was called on a node whose DHT
599/// subsystem is not wired (e.g. a future CLI-only or test invocation that
600/// brings up the admin surface without the DHT handler). A benign,
601/// expected configuration state — distinct from a generic failure so an
602/// operator gets "this node has no DHT to report on" rather than a
603/// confusing transport error, and distinct from [`DHT_POISONED_CODE`] so
604/// it isn't confused with an in-process fault.
605pub const DHT_UNAVAILABLE_CODE: i32 = -32_005;
606
607/// JSON-RPC error code: `admin_v1_status` found a DHT subsystem mutex
608/// (routing table or record store) poisoned — i.e. a thread panicked
609/// while holding it, so the DHT's in-memory state may be inconsistent.
610/// This is a severe in-process fault, kept distinct from the benign
611/// [`DHT_UNAVAILABLE_CODE`] ("no DHT wired") so an operator script can
612/// tell "this node never had a DHT" from "this node's DHT just broke".
613/// The server also logs the poisoning at `error` level.
614pub const DHT_POISONED_CODE: i32 = -32_006;
615
616/// JSON-RPC error code: `admin_v1_lanes` could not read the pool state
617/// store (issue #749) — e.g. the redb load failed or a poisoned
618/// in-memory mutex. A read-side fault distinct from the cache/DHT codes
619/// so an operator script can tell "lane snapshot is unavailable right
620/// now" from a generic transport failure. The server also logs the
621/// underlying store error.
622pub const POOL_STORE_ERROR_CODE: i32 = -32_007;
623
624/// JSON-RPC error code: `admin_v1_slashes` was called on a node whose slash
625/// watcher is not wired (e.g. no `slash_judge_address`, or a test/CLI-only
626/// invocation). Benign config state, distinct from a generic failure so an
627/// operator gets "no slash detection on this node" rather than an opaque error.
628pub const SLASH_DETECTION_UNAVAILABLE_CODE: i32 = -32_009;
629
630/// JSON-RPC error code: `admin_v1_pools` could not read the buyer pool store.
631/// Distinct from [`POOL_STORE_ERROR_CODE`], which covers the seller-side lane
632/// store: the two are different files, and a fault in one says nothing about
633/// the other.
634pub const BUYER_POOL_STORE_ERROR_CODE: i32 = -32_010;
635
636/// JSON-RPC error code: `admin_v1_pools` was called on an admin surface with
637/// no buyer pool store attached, so it can say nothing about what this node
638/// tracks.
639///
640/// Deliberately an error rather than an empty list — unlike `admin_v1_lanes`,
641/// which reports zero lanes as a legitimate state. "This node does not pay for
642/// pulls" and "this node owns no pools" demand opposite responses from an
643/// operator hunting a stranded deposit, and rendering the first as the second
644/// is the ambiguity this method exists to remove.
645///
646/// The production runtime attaches the buyer store unconditionally, so a
647/// running daemon does not answer this: it covers a hand-built `AdminState` —
648/// a test, or a future bring-up with no buy leg — the same posture as
649/// [`DHT_UNAVAILABLE_CODE`]. The alternative for that arm would be an empty
650/// list, which is the answer this code exists to avoid giving.
651pub const BUYER_POOL_UNAVAILABLE_CODE: i32 = -32_011;
652
653/// Admin RPC surface. Versioned via the namespace prefix
654/// (`admin_v1_...`): new methods may be added backwards-compatibly
655/// within `v1`, a breaking change cuts over to `admin_v2_...`.
656#[cfg_attr(feature = "admin-server", rpc(server, client, namespace = "admin_v1"))]
657#[cfg_attr(not(feature = "admin-server"), rpc(client, namespace = "admin_v1"))]
658pub trait AdminRpc {
659    /// Return this node's identity and process uptime.
660    #[method(name = "health")]
661    async fn health(&self) -> RpcResult<HealthResponse>;
662
663    /// Evict a single blob from the local cache (issue #279). The
664    /// eviction is logical: the iroh-blobs store still holds the bytes
665    /// (`Blobs::delete` is `pub(crate)` in iroh-blobs and reserved for
666    /// the GC task) until the next periodic GC sweep reclaims them
667    /// (#518). The takedown itself is persisted to
668    /// `<cache_dir>/evicted.log` so it survives a restart even when
669    /// the next sweep hasn't run yet.
670    ///
671    /// When `req.dry_run` is `true` (issue #379) the cache state is
672    /// *not* mutated: the response carries the pre-evict snapshot
673    /// (size, last-access elapsed time, pin status, already-evicted
674    /// flag) so operators running DMCA takedowns can confirm what the real
675    /// evict will touch
676    /// before committing. The same response shape is used for the
677    /// real-evict path with the snapshot reflecting the
678    /// pre-mutation state.
679    #[method(name = "evict")]
680    async fn evict(&self, req: EvictRequest) -> RpcResult<EvictResponse>;
681
682    /// Re-read the config file the node was started with and apply the
683    /// reloadable subset (issue #373) — the same path SIGHUP triggers,
684    /// exposed over the loopback admin surface for operators who want
685    /// scripted control without `kill -HUP`. Both paths share the same
686    /// `RuntimeReloadState::reload`, whose internal mutexes serialise
687    /// concurrent reloads, so a SIGHUP racing this RPC waits behind it
688    /// rather than corrupting state. Returns:
689    ///
690    /// - [`CONFIG_PATH_UNSET_CODE`] when the node was started without a
691    ///   config path (CLI-only flag invocation has nothing to re-read).
692    /// - [`RELOAD_ERROR_CODE`] when the reload itself fails — previous
693    ///   values are retained, matching the SIGHUP behaviour.
694    /// - On success: [`ReloadResponse`] carrying the post-reload
695    ///   `log_level`.
696    #[method(name = "reload")]
697    async fn reload(&self) -> RpcResult<ReloadResponse>;
698
699    /// Trigger graceful shutdown via the same path SIGTERM exercises (issue
700    /// #244, `appendix-local-admin-http.md`). Stops the iroh router's accept loop and awaits
701    /// in-flight `ProtocolHandler::shutdown` calls; the subsequent task
702    /// drain is bounded by the runtime's 15s `SHUTDOWN_DEADLINE` (the
703    /// router-shutdown step itself is unbounded — a stuck handler hangs
704    /// the runtime, only the post-router task join is timeout-gated).
705    ///
706    /// Fire-and-forget by default: the response returns as soon as the
707    /// trigger lands, not when shutdown completes. Equivalent to `kill
708    /// -TERM <pid>` for operators who'd rather not stat the PID.
709    ///
710    /// The [`DrainRequest`] parameter is required. `wait_admin: false`
711    /// gets the SIGTERM-equivalent shutdown order. `wait_admin: true`
712    /// (issue #604) asks the runtime to keep the admin server alive
713    /// through `router.shutdown` so a polling client can observe
714    /// `admin_v1_health.in_flight_streams` reach 0.
715    #[method(name = "drain")]
716    async fn drain(&self, req: DrainRequest) -> RpcResult<DrainResponse>;
717
718    /// Return a snapshot of this node's DHT participation health (issue
719    /// #741): routing-table bucket fill rates, the network-wide last
720    /// bucket-refresh timestamp, active-staker count, provider-record
721    /// store utilization, and republish-scheduler depth. Intended for
722    /// `decdn node status`, giving operators a single human-readable (or
723    /// `--json`) view to diagnose cold-start or routing-table
724    /// degradation without scraping Prometheus. Returns
725    /// [`DHT_UNAVAILABLE_CODE`] when the DHT subsystem is not wired on
726    /// this node.
727    #[method(name = "status")]
728    async fn status(&self) -> RpcResult<StatusResponse>;
729
730    /// Return a live snapshot of every lane this node provides against a
731    /// `PaymentPool` (issue #749): per lane the outstanding accrued claim,
732    /// time since the last voucher (in-memory, `None` after a restart
733    /// until the next voucher), and whether the accrued claim has reached
734    /// the redemption threshold. Backs `decdn node lanes`, giving
735    /// operators a single view to spot lanes approaching settlement,
736    /// stale lanes, or unusually high outstanding balances before they
737    /// become a liquidity risk — without scraping metrics or logs.
738    /// Returns [`POOL_STORE_ERROR_CODE`] if the pool state store cannot
739    /// be read.
740    #[method(name = "lanes")]
741    async fn lanes(&self) -> RpcResult<LanesResponse>;
742
743    /// Return every slash the node's watcher has detected against its own
744    /// operator (#1032, G-NODE-05): per slash the `slashId`, offense type,
745    /// amount, evidence digest, block, and the 30-day appeal-window close time.
746    /// Consumed directly by operators/keepers (no CLI subcommand wraps it) so
747    /// they notice a slash and file `decdn appeal slash` in time. Returns
748    /// [`SLASH_DETECTION_UNAVAILABLE_CODE`]
749    /// when the slash watcher is not wired on this node.
750    #[method(name = "slashes")]
751    async fn slashes(&self) -> RpcResult<SlashesResponse>;
752
753    /// Return the node's buyer-side `PaymentPool` state: every pool its buyer
754    /// leg tracks, the deposit it believes each holds, and the per-lane spend
755    /// watermark it has signed against each provider.
756    ///
757    /// This is the buyer-side counterpart of [`Self::lanes`], and the only read
758    /// path to `buyer.redb` on a running node — `redb` holds a
759    /// process-exclusive lock on that file for the daemon's lifetime, so a CLI
760    /// pointed at the daemon's data dir cannot open it and would otherwise
761    /// report an unrelated empty store as the node's state.
762    ///
763    /// Returns [`BUYER_POOL_UNAVAILABLE_CODE`] when no buyer leg is wired, and
764    /// [`BUYER_POOL_STORE_ERROR_CODE`] when the store cannot be read.
765    #[method(name = "pools")]
766    async fn pools(&self) -> RpcResult<BuyerPoolsResponse>;
767}
768
769/// Decode a 64-character hex BLAKE3 hash into a [`struct@Hash`].
770///
771/// Goes through `alloy::primitives::hex::decode` (case-insensitive,
772/// `0x`/`0X`-prefix-tolerant) rather than `Hash::from_str` so operators
773/// may paste a `0x`-prefixed hash and get a uniform `INVALID_PARAMS`
774/// error on malformed input. (The leaf [`struct@Hash`]'s own `FromStr`
775/// is panic-free since #578 — unlike the old iroh-blobs `Hash::from_str`
776/// which fell through to a base32 decoder that panicked on a
777/// wrong-size output buffer — but it does not accept a `0x` prefix, so
778/// the alloy path is kept for the operator ergonomics.)
779///
780/// # Errors
781/// Returns an [`ErrorObjectOwned`] with [`INVALID_PARAMS_CODE`] when the
782/// input is not valid hex or doesn't decode to exactly 32 bytes.
783pub fn parse_hash_arg(hex: &str) -> Result<Hash, ErrorObjectOwned> {
784    let trimmed = hex
785        .strip_prefix("0x")
786        .or_else(|| hex.strip_prefix("0X"))
787        .unwrap_or(hex);
788    let bytes = alloy::primitives::hex::decode(trimmed).map_err(|err| {
789        ErrorObjectOwned::owned(
790            INVALID_PARAMS_CODE,
791            format!("invalid hash {hex:?}: {err}"),
792            None::<()>,
793        )
794    })?;
795    let arr: [u8; 32] = bytes.as_slice().try_into().map_err(|_| {
796        ErrorObjectOwned::owned(
797            INVALID_PARAMS_CODE,
798            format!(
799                "invalid hash {hex:?}: expected 32 bytes (64 hex chars), got {}",
800                bytes.len()
801            ),
802            None::<()>,
803        )
804    })?;
805    Ok(Hash::from_bytes(arr))
806}
807
808#[cfg(test)]
809#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
810mod tests;