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