Skip to content

feat(rewards): durable funder-ownership registry (identity only) - #606

Merged
MichaelTaylor3d merged 2 commits into
developfrom
feat/3285-funded-distributor-registry
Sep 10, 2026
Merged

feat(rewards): durable funder-ownership registry (identity only)#606
MichaelTaylor3d merged 2 commits into
developfrom
feat/3285-funded-distributor-registry

Conversation

@MichaelTaylor3d

Copy link
Copy Markdown
Contributor

Refs #3285 — DO NOT MERGE, gate round in progress.

What this adds

crates/dig-node-core/src/rewards/funded.rs: the durable record of which reward distributors this node funds. rewards::port's module doc names this as blocker 2 of two — RewardsChainPort::funded_distributors has no identity set to start from, because there is no chain-wide "list every distributor and filter to mine" call.

Identity only, and there is nowhere to put an amount. A record is a launcher id plus the store id when the funding act knew it. No reserve, accrued, or paid-out figure, for two independent reasons: every money figure here is chain-derived (port::DistributorChainState is read, never stored) and goes stale the moment the chain moves; and dig_ecosystem#3286's rewards * withdrawal_share_bps wrapping u64 multiply upstream means a figure crossing this boundary can already be wrong, so durable storage would make a wrong number about someone's money permanent. The merkle root that DistributorRef also carries is deliberately not persisted either — it names one generation and is superseded on every update.

Persistence mirrors rewards_claim::engine::ClaimEngine: an optional state directory (None = inert, so tests and every default build need no disk), atomic temp-file-then-rename write, and a corrupt record is never overwritten — the same refusal persist_fee_window makes. The funded set is never cached on the registry: every read re-reads the file and every write is a read-modify-write, so the struct holds a path and nothing else. That is the engine's F16/F18 discipline, and it means an operator who repairs the file underneath a running node is observed on the very next read.

A failed read never renders as "funds nothing". FundedDistributorsRead is closed and names the legitimate empty case separately from every unknown:

outcome meaning
Funded(set) a record exists and names these (never empty)
FundsNothing a record exists, intact, naming nobody — the ONE renderable empty answer
NotConfigured(NoStateDirectory / StateDirectoryMissing / NoRecordWritten) UNKNOWN
PersistedStateCorrupt { path, quarantined_to } exists, not trustworthy
IoFailed { path, error } could not be read

determined() returns Some(&[]) only for FundsNothing and None for every non-answer, so a caller that renders dig.listRewardDistributors cannot collapse "unknown" into [] by accident. This is dig-rewards-coin SPEC §2.4 clause 1 ("absence is not silence") in the place it costs most: an empty list tells an operator it funds no distributors.

Quarantine is a COPY, and the corrupt record stays put. Moving it aside would leave the next read finding no file — i.e. NoRecordWritten and, one honest-looking render later, an empty list. So the bytes are copied to funded-distributors.json.corrupt for the operator and the original is left exactly as found, which keeps every subsequent read reporting corrupt until a human resolves it. A test asserts that second read.

Node carries it in a OnceLock slot (funded_distributors) with pub(crate) install_funded_distributor_registry / funded_distributor_registry / funded_distributors_read, mirroring mirror_pointers and reward_prover_statuses. A slot rather than a constructor argument for the same reason as those: the FFI/browser path has no state directory. A second install returns false and changes nothing.

On-disk format

<state_dir>/funded-distributors.json, hex ids so an operator can read and repair it by hand ([u8; 32] would serialize as 32 JSON numbers nobody can check by eye). An unknown version is corrupt, not empty.

{
  "version": 1,
  "distributors": [
    { "launcher_id": "abab…", "store_id": "cdcd…" },
    { "launcher_id": "0505…" }
  ]
}

Nothing constructs it in production yet

Nothing in dig-node funds a distributor today, and the startup loader belongs to #3268's files, which are read-only to this lane. The slot and its methods carry #[cfg_attr(not(test), allow(dead_code))] with docs naming the ticket that will supply the caller — the same marking register_reward_prover_status uses — rather than a clippy failure or an implication that it is live. Until #3268 wires it, funded_distributors_read() answers NotConfigured(NoStateDirectory): unknown, deliberately never empty.

None of dig.listRewardDistributors / dig.getRewardDistributor / dig.listRewardDistributorCommitments is touched — they stay -32601 with no stub.

Tests

Executed, against real tempfile::TempDir directories, no filesystem mock. Round-trip; simulated restart (the writing registry is dropped in a scope, then a fresh registry is constructed over the same directory — exactly what a new process starts from, since nothing is cached); corrupt-quarantine including the follow-up read and the byte-for-byte preservation of both files; malformed id and unknown version as corrupt rather than skipped/empty; refusal to overwrite a corrupt record; missing state directory; existing directory with no record; genuinely-empty record; idempotent re-record and store-id refinement; a contradicting store id as a conflict that overwrites nothing; and the two Node-level reads.

🤖 Generated with Claude Code

MichaelTaylor3d and others added 2 commits September 10, 2026 05:00
Records WHICH reward distributors this node funds -- launcher id plus the
store id when the funding act knew it -- and nothing else. No amount can
be recorded: every money figure here is chain-derived and goes stale, and
dig_ecosystem#3286's wrapping u64 share multiply means a figure crossing
this boundary can already be wrong. Durable storage would make it
permanent.

Persistence mirrors rewards_claim::engine::ClaimEngine: an optional state
directory (absent = inert, so tests and default builds need no disk),
atomic write, and a corrupt record is never overwritten. The set is never
cached on the registry -- every read re-reads the file -- so no transient
state lives on the struct across calls (the engine's F16/F18 discipline).

The read outcome is closed and distinguishes funds-nothing from every
unknown: NotConfigured (no state dir / dir missing / nothing written yet),
PersistedStateCorrupt and IoFailed. A corrupt record is quarantined by
COPY and left in place, so the next read is corrupt too rather than
decaying into an empty list -- SPEC 2.4 clause 1 in the place it costs
most, since an empty dig.listRewardDistributors tells an operator it funds
no distributors.

Node carries it in a OnceLock slot with pub(crate) accessors, mirroring
mirror_pointers and reward_prover_statuses. Nothing installs it in
production yet: no dig-node code funds a distributor, and the startup
wiring belongs to dig_ecosystem#3268, so the slot is marked the same way
register_reward_prover_status is.

Refs #3285

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Two test-only `Node` literals got the slot twice (E0062), because the
inserted line's own indentation made the wider-indented site match twice.

Refs #3285

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@MichaelTaylor3d

Copy link
Copy Markdown
Contributor Author

Adversarial leg (loop-decider) — dig_ecosystem#3285 — head ee01f44a

Verdict: MERGE-WITH-CONDITIONS. Two conditions, both ticket-side, both checkable before the squash; no code change required at this SHA.

1. Does the prover-status precedent (#595) transfer?

Only half of it. The half that transfers: this registry is writer-agnostic. record() takes {launcher_id, Option<store_id>} and nothing in the on-disk shape assumes the writer is a fund transaction; an operator declaration, a startup config sync, or a future fund path can all feed it, and the IdentityConflict / IdentityRefined arms are exactly what a declaration writer needs. So merging does not lock a shape the undecided writer could contradict — that was my main attack and it did not land.

The half that does NOT transfer: #595's "honest-empty now, honest-populated later" argument was warranted because the writer had a named ticket (#3265). Here the writer has none, and the PR's own docs paper over that by saying "#3268 wires the install" — but #3268's PR#605 is already green and contains no call to install_funded_distributor_registry, and #3268's scope is the claim loop, not this registry. As written, after #3267, #3268 and this PR all merge, the slot is still OnceLock::new() forever and funded_distributors_read() answers NotConfigured(NoStateDirectory) on every production node. That is honest, but it is honest about a hole nobody owns. Precedent reused past its warrant unless the conditions below restore it.

2. Does it deliver anything with no caller?

No observable behaviour changes. That is acceptable groundwork here for a specific reason: the decision this PR embeds (durable local record; UNKNOWN is never []; corrupt record stays put and is copied, not moved; identity only) is the part that would be re-litigated if the file were written later by whichever lane ships the writer. Landing it now with 16 real-disk tests fixes the failure table before the writer exists. If it waited, it should wait for exactly one thing: a named writer ticket — and that is a ticket, not code, so the wait costs nothing. Hence a condition, not DO-NOT-MERGE.

3. The un-ticketed hole — what should the writer be?

Yes, this is a third prerequisite and it must be filed. Shape: an operator-facing declaration, not a fund path in dig-node. Launching and funding a distributor spends a reserve CAT from a user wallet (dig-rewards-coin launch/fund, driven from dig-app/Sage); the node never holds those keys and cannot observe that act. A "fund path in dig-node" would either require user custody in the node (the identity boundary this ecosystem refuses) or never happen. A declaration (dig.registerFundedDistributor on the local RPC and/or a config list) is the only writer that can exist, and this PR's hand-editable hex JSON is already the right store for it.

One consequence the writer ticket must carry so it does not become a fourth prerequisite: a declared launcher id is a claim, not a fact. The consumer (RewardsChainPort::funded_distributors) must read each declared id through the #3267 reader — it needs the root for DistributorRef anyway — and a declared id the reader reports Malformed/unavailable for must render as an error entry, never be dropped from the list (dropping it recreates the "funded distributor became invisible" failure this module exists to prevent).

4. Identity-only — safe side or prescribed defect?

Safe side, and the distinction from the deleted money type is exact: that type carried a partial money figure a consumer would render as whole. This record carries none, and the only place a consumer can derive an amount is the chain via dig-rewards-coin — which is also where #3286's authoritative restatement is going. There is no "somewhere worse" to push a consumer toward; the worse place would have been this file. The unpersisted root is the same reasoning applied correctly. Also checked: store_id: Option here vs the required store_id: Bytes32 on DistributorRef means a None record cannot become a DistributorRef without a chain read — correct, since the root requires one regardless.

5. Precedent — two registries with no writer

Two is a pattern and the pattern has a cost: this PR's doc already contains a born-false ownership claim ("belongs to #3268") because the author had to name some future caller. Rule for the third: a new rewards/ module gated entirely behind cfg_attr(not(test), allow(dead_code)) does not merge unless the PR body links an OPEN ticket that names the exact function it will call — no "the startup path will wire it". The writer/installer being un-ticketed is the tell that a lane is designing ahead of the family plan; the fix is to file the ticket in the same unit, not to hold the code.

Conditions (both pre-squash, both checkable by URL)

  • C1 — writer ticket filed and linked. An open dig_ecosystem issue for the operator declaration writer (dig.registerFundedDistributor and/or config), scoped to call FundedDistributorRegistry::record, carrying the §3 verification consequence above, cross-linked from #3285 and this PR body.
  • C2 — installer owned. Either #3268 is amended (comment on the issue, and PR#605 must not close it) to include calling Node::install_funded_distributor_registry with the node's state dir at startup, or a child ticket is filed for it. Whichever ticket owns the install also owns correcting the "belongs to #3268" sentences in lib.rs field/method docs and funded.rs if they turn out false.

Code-level notes for the other two legs, none blocking: read() on a corrupt file has a side effect (quarantine copy, overwritten on every read — benign since the original is preserved); std::fs::rename over an existing target replaces on Windows, so the atomic write is sound cross-platform; record() refines store_id None -> Some from any writer without verification, which is correct for a declaration store and must stay a consumer-side check.

@MichaelTaylor3d

Copy link
Copy Markdown
Contributor Author

Security audit — PASS

Head SHA audited: ee01f44a784d308b60585adf2775eb9006119e59 (confirmed via gh pr view --json headRefOid and git log -1 in a fresh worktree — matches).

Scope: crates/dig-node-core/src/rewards/funded.rs (new, 848 lines), rewards/mod.rs (+1), src/lib.rs (+126, Node slot + accessors + tests). Diffed against origin/develop merge-base 56f398d1+975/-0 across exactly those 3 files, matching the brief.

Severity context, stated up front: nothing constructs this registry in production. install_funded_distributor_registry / funded_distributors_read are #[cfg_attr(not(test), allow(dead_code))], called only from tests; dig.listRewardDistributors still returns -32601 (out of scope, confirmed by crates/dig-node-core/tests/reward_methods_tier_guard.rs, which also proves every *Reward* method is Tier::Control and NOT peer-reachable — so even once wired, the errors this registry can produce reach only the loopback/admin caller, i.e. the operator's own view of their own machine, never a remote peer). This is real severity-limiting context, not an excuse to skip the audit.

1. Path handling — clear

record_path() always joins the operator-supplied state_dir with the compile-time constant FUNDED_DISTRIBUTORS_FILE; the quarantine target is likewise the compile-time constant FUNDED_DISTRIBUTORS_QUARANTINE_FILE (funded.rs:53-59,188-192,335). No parsed record content, launcher id, or store id ever contributes to a path — there is no traversal surface, hostile or otherwise, because the file name is never derived from data. Symlink-following on read (std::fs::read_to_string, funded.rs:265) and on the quarantine copy (std::fs::copy, funded.rs:336) is real but requires the operator's own state directory to already contain a hostile symlink — same trust boundary as the operator who configured state_dir in the first place; not attacker-reachable. TOCTOU between corrupt-detection and quarantine-copy (funded.rs:210-220 to funded.rs:334-348) requires the caller to already have write access to the state directory, at which point they do not need a race. PathBuf/error: String in PersistedStateCorrupt/IoFailed surface only through Tier::Control, loopback-only, per above — no leak to a stranger.

2. Quarantine as a write primitive — clear, and better than the brief worried

quarantine() copies to the fixed filename FUNDED_DISTRIBUTORS_QUARANTINE_FILE every time (funded.rs:334-348); fs::copy overwrites its destination. Repeated reads of the same corrupt record overwrite the same quarantine file — one file, not one-per-read. No unbounded growth, no ENOSPC amplification. Confirmed by a_corrupt_record_reports_corrupt_and_quarantines_and_is_never_empty (funded.rs:620-671), which reads twice and asserts the second read is still PersistedStateCorrupt.

3. Deserialization — clear

serde_json::from_str over a string loaded whole via read_to_string (funded.rs:264-271): a huge or deeply-nested hostile file could cost memory/stack, but only if the attacker already has write access to the operator's state directory — same trust boundary as above, not a new hole this PR opens. Unknown format version is refused, not best-effort: funded.rs:272-277 rejects any record.version != RECORD_FORMAT_VERSION as LoadFailure::Corrupt before any distributor is parsed. an_unknown_format_version_is_corrupt_not_empty (funded.rs:695-708) verified passing in CI (see test count below) and by inspection actually asserts PersistedStateCorrupt and determined() == None — it does refuse, not best-effort.

4. Honesty property — clear, verified both structurally and by test

funded_distributors_read() with no installed registry returns NotConfigured(NoStateDirectory), never FundsNothing (lib.rs new code, Node::funded_distributors_read). Every fault path in funded.rs::read() (NotConfigured x3 reasons, PersistedStateCorrupt, IoFailed) is disjoint from FundsNothing, which requires an intact record that parses to an empty vec (funded.rs:210-219). determined() returns None for every not-an-answer variant, Some(&[]) only for the one legitimate case (funded.rs:114-131), and every_not_an_answer_outcome_is_undetermined (funded.rs:824-847) enumerates all five undetermined variants and checks each.

One structural gap, not exploitable today, worth a ticket: FundedDistributorsRead::Funded(Vec<FundedDistributor>) is a plain public variant over a plain Vec — the type system does not forbid constructing Funded(vec![]) from outside this module the way the doc comment claims ("Never empty"). Every current construction site (funded.rs:213) guards it correctly with if set.is_empty() first, and no other code in this diff constructs the variant. This is defense-in-depth, not a live vulnerability — recommend a ticket to make the empty case unconstructible at the type level (e.g. a private field or a smart constructor) before more callers than this module ever build the variant directly.

5. Write integrity — clear; write IS atomic

save() writes to path.with_extension("json.tmp") then std::fs::renames over the real path (funded.rs:285-298) — temp-file-plus-rename, and std::fs::rename replaces the destination atomically on both POSIX and Windows. A corrupt record is never overwritten: record() returns refuse_corrupt(...) before ever calling save() when the existing file fails to load (funded.rs:229-236), verified by a_corrupt_record_is_never_overwritten_by_a_new_funding_record (funded.rs:713-734, asserts the on-disk bytes are byte-identical to what was seeded). merge() never removes an entry — a conflicting offer returns Err(IdentityConflict) before mutating set, so record() returns before save() and the prior file is untouched, verified by a_contradicting_store_id_is_a_conflict_and_overwrites_nothing (funded.rs:588-614, asserts the read-back set still holds only the originally recorded identity). A partial/interrupted write cannot produce a smaller valid set: the write path is one serde_json::to_string_pretty of the entire in-memory set to a temp file, then one atomic rename — there is no path that renames a partially-written temp file into place, and no in-place truncate-and-rewrite of the real file at any point.

Genuine but out-of-reach-today concern: record() does load-merge-save with no locking (funded.rs:225-250). Two concurrent record() calls against the same registry could both load the same base state and the second save() would silently clobber the first's addition — a real non-clobber gap for concurrent writers. Not exploitable now because no production caller exists yet (the sole caller today is tests, one at a time); flag for #3268, which will decide whether funding acts can occur concurrently. Defense-in-depth, not a gate blocker for this PR.

6. No amounts — clear, verified structurally (stronger than the test)

FundedDistributor has exactly two fields, launcher_id: Bytes32 and store_id: Option<Bytes32> (funded.rs:69-75) — there is no numeric field anywhere in the type for a money figure (wrapped or otherwise) to occupy; PersistedDistributor mirrors this with two string fields (funded.rs:393-398). This is a compile-time guarantee, not merely a runtime test — #3286's u64-wrap concern in withdraw_incentives.rs cannot reach this boundary because there is no slot to receive it. the_persisted_record_is_hex_and_carries_no_amount (funded.rs:520-548) additionally greps the serialized text for amount/mojos/base_units/reserve/accrued/paid_out/balance and passed in CI.

CI evidence (executed count, not the checkmark)

Test + coverage job (run 34476390827, job 102868075855): nextest summary line —
Summary [ 949.120s] 3375 tests run: 3375 passed (17 slow), 4 skipped — 0 failed, all 3375 executed, including every rewards::funded::tests::* test named in the brief (a_corrupt_record_is_never_overwritten_by_a_new_funding_record, a_contradicting_store_id_is_a_conflict_and_overwrites_nothing, an_unknown_format_version_is_corrupt_not_empty, the_persisted_record_is_hex_and_carries_no_amount, all confirmed PASS by grepping the raw job log). Fail-fast/retries (#3287) did not mask anything here since the run completed with 0 failures.

Findings summary

No LIVE vulnerability. Two defense-in-depth notes (not gating): (a) FundedDistributorsRead::Funded(vec![]) is type-constructible though never constructed today — recommend a ticket to close it structurally before more call sites exist; (b) record() has no lock across concurrent callers — recommend #3268 decide whether concurrent funding acts are possible before wiring a caller.

Out of scope, not audited

crates/dig-node-service/** and the startup path (#3268/PR#605), the three unserved reward RPC methods (-32601), dig-rewards-coin.

Worktree note

Created D:\worktrees\dig-node-606-audit (fetched pull/606/head) for read-only diffing against origin/develop; no files modified, nothing pushed.

@MichaelTaylor3d MichaelTaylor3d left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: PASS

Head SHA reviewed: ee01f44a784d308b60585adf2775eb9006119e59 (matches the SHA I was asked to gate; PR is currently draft).

Properties 1-5

  1. Corrupt/unconfigured/failed never renders as "funds nothing" — verified. FundedDistributorsRead::Funded is only constructed from a non-empty parsed set (funded.rs read(): Ok(set) if set.is_empty() => FundsNothing, Ok(set) => Funded(set)), so Funded(vec![]) is unreachable by construction — nothing in the module builds it, and into_distributors() only returns Ok with the full parsed set or Err (corrupt). Every fault path (NotConfigured, PersistedStateCorrupt, IoFailed) is a distinct variant; determined() maps only Funded/FundsNothing to Some. Confirmed by 6 tests (no_state_directory_reports_not_configured_never_empty, a_missing_state_directory_..., an_existing_directory_with_no_record_is_not_configured_not_empty, a_corrupt_record_reports_corrupt_and_quarantines_and_is_never_empty, a_malformed_id_inside_a_parseable_record_is_corrupt_not_a_skipped_entry, an_unknown_format_version_is_corrupt_not_empty) all asserting read.determined() == None and read != FundsNothing.

  2. determined() is the only accessor and is exhaustive — partially verified, one finding. determined()'s match has no wildcard arm — it names all 5 variants explicitly, so the compiler forces a decision when a 6th variant is added. That is a real completeness mechanism, but it lives in production code, not the test. every_not_an_answer_outcome_is_undetermined (funded.rs:825) is a hand-built array of the 5 current variants, not derived from the enum. See inline finding — its own doc claims it "catches ... a future variant" determined mis-reports, which is false: a 6th variant added with a wrong (Some) arm in determined() would compile and this test would still pass unchanged, because nothing forces the new variant into the array.

  3. No money persisted — verified against bytes, not a struct. the_persisted_record_is_hex_and_carries_no_amount reads the file with std::fs::read_to_string and asserts on the JSON text: hex ids present, and none of amount|mojos|base_units|reserve|accrued|paid_out|balance appear anywhere in the file. That is a real bytes-level pin — a field added later to PersistedDistributor would have to dodge every one of those substrings to pass, which a real amount field practically can't.

  4. Corrupt records never destroyed — verified. record() checks load() first; on LoadFailure::Corrupt it returns refuse_corrupt (a PersistedStateCorrupt outcome) before ever calling save() — no code path reaches save() after a corrupt load. a_corrupt_record_is_never_overwritten_by_a_new_funding_record proves the original bytes are untouched after a record() call. quarantine() copies (not moves) so the original stays in place and the next read is still PersistedStateCorrupt, not NoRecordWritten -> eventually-empty; quarantined_to: None on a failed copy still returns the PersistedStateCorrupt verdict (verdict does not depend on the copy succeeding).

  5. No transient state on the struct — verified. FundedDistributorRegistry holds only state_dir: Option<PathBuf>. Every read()/record() call does its own load()/save() from disk; nothing is cached across calls, matching the claim-engine F16/F18 discipline the module doc cites.

Non-vacuity spot checks

  • a_malformed_id_inside_a_parseable_record_is_corrupt_not_a_skipped_entry: into_distributors() uses .map(...).collect::<Result<_,_>>(), i.e. short-circuits to Err on the first bad id rather than .filter_map — reverting to filter_map (silently skipping) would make this test go RED (it currently expects PersistedStateCorrupt). Real.
  • an_unknown_format_version_is_corrupt_not_empty: load() explicitly checks record.version != RECORD_FORMAT_VERSION before returning Ok(Some(record)); deleting that check would parse {"version":2,"distributors":[]} successfully to an empty vec -> FundsNothing, and the test's assert!(matches!(read, PersistedStateCorrupt{..})) would fail. Real.
  • a_fresh_registry_over_the_same_directory_still_sees_the_set: writer registry is dropped (explicit scope) before a second with_state_dir reads — genuinely exercises "no cached state," would fail if a future change added an in-memory cache field. Real.
  • a_contradicting_store_id_is_a_conflict_and_overwrites_nothing: merge()'s (Some(recorded), Some(offered)) if recorded != offered => Err(IdentityConflict) arm is the only thing stopping a silent overwrite; removing that guard (falling to the _ => Ok(AlreadyRecorded) catch-all) would silently keep the OLD value instead of reporting conflict, which the test's explicit IdentityConflict{recorded,offered} assertion would catch. Real.
  • every_not_an_answer_outcome_is_undetermined: see finding below — real for the 5 named variants (would fail if e.g. IoFailed regressed to Some), but does not, and cannot as written, catch a mis-handled new variant. Its own docstring overclaims this.

Test + coverage job (run 34476390827, job 102868075855)

Summary [949.120s] 3375 tests run: 3375 passed (17 slow), 4 skipped — no failures, ran to completion (not truncated by fail-fast). All 16 of this PR's tests present and PASS: 14 in rewards::funded::tests, plus lib.rs's a_node_with_no_installed_funder_registry_reads_not_configured and a_node_reads_through_the_installed_funder_registry.

Blast radius / scope

Diff touches exactly crates/dig-node-core/src/lib.rs, .../rewards/funded.rs (new), .../rewards/mod.rs (one pub mod funded; line) — matches the brief. No touch to dig-node-service/**, rewards_claim/**, service.rs, entrypoint.rs, main.rs, service_control.rs, tests/dependency_tree.rs, or any RPC dispatch file — the three reward RPC methods are untouched, still falling through to -32601, no stub added. lib.rs gains only the funded_distributors: OnceLock<...> slot plus install_funded_distributor_registry/funded_distributor_registry/funded_distributors_read, mirroring reward_prover_statuses's existing accessor shape — no second convention invented.

allow(dead_code) markers

install_funded_distributor_registry's doc names #3268 as the future caller. The field doc on funded_distributors also names #3268/#3285. The remaining allow(dead_code) sites (funded_distributor_registry, funded_distributors_read, FundedDistributorRegistry::with_state_dir, read, record, determined) do not each individually cite a ticket number in their own doc comment — non-blocking, noted below, since the module doc they sit under already carries the full context and a rustdoc reader lands there first.

What I did not run

Did not build/test locally (relied on the CI job log, read line-by-line); did not execute the RPC surface end-to-end (out of scope, confirmed by diff scope alone).

For your report

  • What's persisted: identity only — a launcher id and an optional store id, both as lowercase hex strings, in PersistedRecord { version: u32, distributors: Vec<{ launcher_id: String, store_id: Option<String> }> }.
  • Format: JSON (serde_json::to_string_pretty), atomic write (.json.tmp + rename), file funded-distributors.json inside the registry's state dir.
  • Restart-survival proof: a_fresh_registry_over_the_same_directory_still_sees_the_set — writes via one registry, drops it, constructs a new FundedDistributorRegistry::with_state_dir over the same directory, and asserts the read matches.

Inline findings below; only one is non-trivial (the completeness-test overclaim) and it is non-blocking for this PASS given the underlying compiler-enforced exhaustiveness in determined() — but the docstring should be corrected so it does not misrepresent what the test proves.

Comment thread crates/dig-node-core/src/rewards/funded.rs
@MichaelTaylor3d

Copy link
Copy Markdown
Contributor Author

Adversarial gate conditions satisfied — both ticket-only, no code change at ee01f44a

The adversarial leg returned MERGE-WITH-CONDITIONS with two conditions, both checkable by URL:

  • C1 — the writer. Filed as #3291. The writer must be an operator declaration (dig.registerFundedDistributor or config), not a fund path, because funding spends a reserve CAT from a user wallet the node never holds — so dig-node can never observe the funding act directly. That ticket carries the consequence the gate required: a declared id is a claim, so an id that reads Malformed or whose chain read is unavailable must render as an error entry, never be silently dropped. Dropping it would defeat this PR's own guard from the other side.
  • C2 — the installer, and a doc claim that is false as merged. Filed as #3292. The doc sentences in crates/dig-node-core/src/lib.rs and crates/dig-node-core/src/rewards/funded.rs attribute the startup call to #3268, but PR#605 contains no such call and #3268's scope is the claim loop. Without an installer the slot stays empty on every production node even after #3267, #3268 and #3285 all merge, while the code reads as finished. #3292 owns both the installer and correcting those sentences.

Standing rule adopted from this gate

This is the second allow(dead_code)-gated module landed in rewards/ (after the prover-status registry in #595). Two is a pattern, so the rule going forward: no fully allow(dead_code)-gated rewards/ module merges without an OPEN ticket naming the exact function it will call. #3291 and #3292 are what satisfy that here.

On the precedent I reused, and where it did not reach

I justified this the way I justified the prover-status registry in #595: reading a real registry is honest-empty now and honest-populated when a writer appears, whereas a hardcoded empty would be honest today and a SPEC §2.4 clause 1 lie later. The gate's correction is that the precedent transfers only half — #595's warrant was a named writer ticket, and this had none until now. The registry itself is writer-agnostic (record() takes { launcher_id, Option<store_id> }, and the identity-conflict / identity-refinement arms suit a declaration writer as readily as a fund path), so merging locks no shape the undecided writer could contradict.

Non-blocking notes recorded rather than actioned, since fixing them would move a thrice-gated SHA: Funded(vec![]) is type-constructible though never constructed; record() takes no lock across concurrent callers (unreachable today, no production caller); read() on a corrupt file has a benign side effect in the quarantine copy.

@MichaelTaylor3d
MichaelTaylor3d marked this pull request as ready for review September 10, 2026 16:13
@MichaelTaylor3d
MichaelTaylor3d merged commit 90fff0c into develop Sep 10, 2026
14 checks passed
@MichaelTaylor3d
MichaelTaylor3d deleted the feat/3285-funded-distributor-registry branch September 10, 2026 16:13
MichaelTaylor3d added a commit that referenced this pull request Sep 10, 2026
…unning (#607)

* feat(mirror): persist mirror-bond coin ids (#575)

* chore: open lane for #574

* feat(mirror): persist mirror-bond coin ids so a restart cannot double-create

Bond identity was reconstructed from a live chain scan on every read
(`mirror/observe.rs`), with no persistence of its own. A restart, a cold
replica, or a lagging/flaky chain source all rendered a real, unspent,
confirmed bond as "no bonds" -- and because the in-flight suppression is
keyed on pending/submitted audit entries, a bond whose create had already
CONFIRMED was not suppressed either, so the same short scan that emptied
the read surface also cleared the one thing that would have stopped a
second coin being paid for collateral that already exists (dig-node#574).

Persist the (store, root, epoch) -> coin_id mapping in the EXISTING spend
audit record (spend-audit.jsonl) rather than a new store: a mirror-coin
create already writes store_id + AuditedBond{root, epoch} + amount there,
and the coin id itself becomes durable the moment resolve_landed_spends
confirms it. This adds the one missing piece -- the advertised URL a
create carries -- and a read-side query, confirmed_mirror_bond, that
returns the newest CONFIRMED record naming a triple.

Chain stays authoritative. mirror::local_bond::recheck_missing_bonds
never trusts the record: for a held bond the live scan did not cover, it
asks the record for a candidate coin id, then re-verifies that SPECIFIC
coin against chain via the same independent check (chain_bond_verdict)
that verifies an untrusted peer's claimed bond. Only a fresh `Bonded`
verdict is folded back in, as covered; `Unbonded`/`Unverified` fall
through to an ordinary create, exactly as if no record existed.

Version: 0.254.86 (patch -- per #522 the MSI ProductVersion minor field
is exhausted and the counter lives in patch).

Co-Authored-By: Claude <noreply@anthropic.com>

* test(mirror): prove the recovery wiring end to end through PassRunner::run

Adds two integration-level tests over the REAL pass pipeline, not just the
isolated recheck_missing_bonds unit tests: a bond missing from the live
scan with a chain-reverified durable record is recovered (no double
create, correct Bonded state reported), and the control -- the same
record but chain disproves it -- correctly falls through to an ordinary
create. Together these are the concrete regression test for the
cold-start/lagging-chain-source double-create scenario the ticket asked
to have measured.

Also refactors in_flight_creates to take the already-folded SpendLedger
instead of re-reading the log itself, so PassRunner::run reads the audit
file once per pass and shares it with the new recovery step, and fixes a
doc comment on in_flight_creates that the recovery step would otherwise
have made stale on landing ("a Confirmed create has a coin the chain
observation already sees" is no longer unconditionally true).

Co-Authored-By: Claude <noreply@anthropic.com>

* chore(fmt): wrap long test signatures to satisfy rustfmt

Co-Authored-By: Claude <noreply@anthropic.com>

* chore(clippy): use slice::from_ref instead of cloning for a single-element slice

Co-Authored-By: Claude <noreply@anthropic.com>

* chore(release): bump to v0.254.89

Base branch moved to develop after PR #576 merged there at v0.254.88
(main and develop are currently identical), leaving this branch's
carried-forward .88 as a zero-increment against the new base. Bumped
to the next free integer after fetching and verifying both origin/main
and origin/develop tip at .88.

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>

* fix(peer): count accepted relayed circuits in the connected pool (#579)

serve_accepted_relay_conn served every accepted relayed circuit (full mTLS
auth, full L7 peer RPC) while registering it nowhere, so connected_peers
under-reported every relayed inbound peer -- the relay-leg twin of the
direct-inbound defect #402/#523 already fixed.

adopt_inbound_peer_in_pool now dispatches by TraversalKind: Relayed routes to
dig-gossip's already-published adopt_relayed_inbound_handle (v0.32.0, the rev
this repo already pins), every other tier keeps the unchanged
adopt_direct_inbound_handle path. serve_accepted_relay_conn adopts before
serving and releases after, mirroring the direct listener exactly.

Refs: https://github.com/DIG-Network/dig_ecosystem/issues/3124

* fix(cli): guard the exit-code namespace shared with diga against collisions (#582)

* chore: open lane for #3189

* fix(cli): guard the exit-code namespace shared with diga against collisions

dign and diga deliberately share one process exit-code numbering (dig-app's
outcome.rs says so in its own doc comment), so a number is free only if it
is unoccupied ecosystem-wide. dig-node#407 assigned exit 7 to
NODE_UNREACHABLE by checking only this repo's own table, where 7 genuinely
was free -- and collided with diga's NOT_CONNECTED. A reviewer caught it by
hand; nothing failed automatically.

Adds scripts/check-exit-code-collisions.sh: parses both enums' code()/name()
match arms straight from their own source -- this repo's ExitCode, and a
live fetch of dig-app's outcome.rs at its default branch -- and fails if a
number carries two different names, or if either side draws a number from
the reserved shell signal range (126, 127, 128+N). Ships with an 18-case
hermetic test harness (scripts/tests/check-exit-code-collisions.test.sh)
covering the actual #407 collision shape, arm-order independence, arm-count
mismatch, the reserved-range boundary from both sides, the live-fetch path
itself, and fail-closed behaviour on an empty/missing/unreachable table.

Wires a real (unstubbed) invocation into ci.yml's existing "Release-script
tests" job so a collision introduced by a future PR, on either side, is a
red required check on that PR -- not a note a reviewer has to catch. The
fetch retries twice (2s backoff) since this becomes a required, network-
dependent check; a fetch failure still fails closed after retrying, never
silently passing as "diga has no codes".

Updates SPEC.md 8.4 to point at the mechanical guard instead of leaving
"re-check both tables" as unenforced prose, and records that the
extension's WALLET_WS_ERR.NOT_CONNECTED = -33001 is a separate JSON-RPC
error-code space, not a rival of this one. Adds a doc-comment to the
existing transcribed collision test pointing future readers at the live
script as the authoritative check; the transcription remains as a narrower,
hermetic regression pin for the #407 shape specifically.

No renumbering: every currently-assigned code is unchanged.

Refs #3189

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>

* fix(hygiene): port the lost-continuation guard to 4 crates, fix 48 corrupted strings (#3190) (#583)

* chore: open lane for #3190

* fix(hygiene): port the lost-continuation guard to 4 crates, fix 48 corrupted strings

Replicates dig-node-service::continuation_guard (dig-node#526/#501) into dig-node-core,
dig-wallet, dig-runtime and dig-chat-protocol, line-for-line apart from crate-specific
constants -- ported rather than reinvented, per dig_ecosystem#3190.

Wiring the guard in surfaced 48 pre-existing lost-continuation defects the ticket's own
"no measured corruption in these four crates" note did not anticipate: 36 in dig-node-core,
12 in dig-wallet, mostly test-assertion prose where a multi-line message lost its `\`
continuation and shipped the source's own indentation as a mid-sentence space run (one
as the worse `\n`-plus-indentation variant). All 48 are collapsed to the single space the
sentence always meant, with surrounding indentation and wording otherwise untouched.

Two lines are real column-alignment, not defects, and get a targeted EXCLUDED_LINE_RANGES
entry on dig-node-core instead of a rewrite: download.rs's `claimed(...)` fixture-table
trailing comments, and net.rs's `label : value` debug-print alignment.

Refs https://github.com/DIG-Network/dig_ecosystem/issues/3190
Refs https://github.com/DIG-Network/dig_ecosystem/issues/3130

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>

* feat(mirror): detect an IP change daily and reconcile mirror coins to the current advertise URL

Automatic half (D1-D4) of the daily mirror-URL reconcile: derived personal-day offset, two-observation hysteresis, nine ordered gates with K sized as a self-funding prefix before any reclaim, `submitted` never `completed`, audit lines gain `reclaim_reason` + `trigger`.

Gates at b4c09866: loop-reviewer PASS (review 5129272285), loop-security PASS @ 175304e1 (tree byte-identical, `git diff 175304e1 b4c09866` empty), adversarial loop-decider PASS (comment 5567083644; SHOULD-FIX findings ticketed separately).

Refs DIG-Network/dig-node#570
Refs DIG-Network/dig_ecosystem#3203

* feat(serve): content hosting + serve path batch, v0.255.0 (dig_ecosystem#3212)

Nine commits from the #3212 serve-path lane, gated at 899cc68f (reviewer review 5130425808,
security comment 5568662836), plus the single semver bump to 0.255.0 for the develop -> main batch.

- store_id/root case normalised at the CapsuleKey boundary; cache delete targets the matched entry
- tier-0 occupancy reads the eviction-aware ledger
- profile-sync outbound budget in bytes; announcer asked first
- melt confirmation depth on the terminal spend, fail-closed
- EngineWarming (-32002) while the peer tier attaches, never -32004
- window completeness derived from the bytes read
- deps: dig-stun 0.2, chia-query 0.24.3, dig-nat 0.21.2, dig-logging 0.2.2

Refs DIG-Network/dig_ecosystem#3212

* chore: untrack gitnexus-generated agent files (#590)

* chore: untrack gitnexus-generated agent files

These files were generated by `gitnexus analyze` as a side effect of
indexing this repository. They are development-loop private tooling
output, not product code, and carry no secrets. They are removed from
tracking going forward via .gitignore; history is deliberately NOT
rewritten.

Refs #3177

* chore: drop private-repo reference from gitignore comment

The ignore comment named a private repository and an internal issue
number in a public file, which is the same disclosure class this
change set exists to remove; the reference is dropped and the
guidance kept.

* feat(rewards): always-on prover loop engine -- honest liveness, type-enforced self-exclusion, bounded spend (#593)

The always-on reward-prover engine: ~2,000 lines under
`crates/dig-node-core/src/rewards/`, built against the merged `dig-rewards-coin`
SPEC. Library only -- nothing spawns it, and the sole production
`RewardsChainPort` refuses every call, so it cannot spend. Wiring the composed
system is #3265, which carries its own gate.

The epic's premise -- "anytime the process isn't running, rewards are not being
distributed" -- is half wrong, and the false half is the dangerous one. `Sync`,
`NewEpoch` and `InitiatePayout` need no manager authority, so funder downtime does
not stop rewards: it FREEZES THE ENTRY SET while accrual and payouts continue.
Peers that stopped mirroring keep earning; peers that started cannot begin. That
shaped the whole design.

Liveness honesty (SPEC 2.4). The status record carries no `healthy`/`ok`/`up`
boolean and no precomputed staleness, because a wedged loop cannot report its own
wedging -- whatever it last wrote stays there, so a writer-set flag reads true
forever after the failure it exists to reveal. The reader derives staleness from
`last_cycle_completed_at` against `observed_at` and its own clock. A recursive
JSON-key test enforces the absence at every nesting depth; asserting on keys and
never substrings, since `ProverState::Running` legitimately serializes the VALUE
"running". The one legal staleness signal is chain-derived (SPEC 12.4: 48 hours
AND a non-zero reserve, from the singleton's own spend history) and lives on the
distributor read, where a wedged prover cannot fake it.

Self-exclusion is a compile error, not a habit. dig-node#261's lesson is that an
invariant enforced on some paths is not an invariant. `admit` is the single
admission point, checks both SPEC 5.2 coordinates (own peer_id OR a payout puzzle
hash this wallet controls), and mints an `AdmittedPeer` with private fields and no
public constructor -- so `EntryAction::Add` cannot be built by a path that skipped
admission.

A prover's own fault can never strike a peer. `GateError` is a distinct type from
`GateIneligibleReason` and `record_prover_fault` takes `&self`, so SPEC 3.6 clause
4 is enforced by the borrow checker rather than by comment. Without that, a
misconfigured operator -- one missing mirror-collateral epoch ordinal -- would
strike every peer at once and evict its entire 250-entry set in three hours, each
eviction a fee it pays plus a settlement out of its own reserve.

The money bounds are stated where a human reads them (`rewards/mod.rs`): 24
bundles/day, 192 entry actions/day, a fee ceiling of 24x the configured standard
fee, 192 removals/day worst case with 96/day sustained churn. Recorded honestly:
SPEC 6.3's rate bound and fee ceiling are ONE control, not two.

Three gate rounds, every leg fresh-context. Round 3 at this head: reviewer PASS,
adversarial decider RATIFY (leg closed), security CHANGES-REQUIRED on a finding
the decider ratified deliberately -- adjudicated in
https://github.com/DIG-Network/dig-node/pull/593#issuecomment-5601784815 and
carried to #3265 with the remedy corrected, because the proposed fix would have
persisted a poison flag to the very store whose writes were failing.

Found and fixed under gate: a census ordinal off by one in both directions (SPEC
4.6 requires n-1 exactly); an unreachable grace window leaving a named constant
with no reader; a missing `NewEpoch` spend; an absent-ordinal path attributing a
prover fault to peers; and a daily fee ceiling 24x too high because a per-bundle
fee was consumed as a daily ceiling.

Refs DIG-Network/dig_ecosystem#3250

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat: serve dig.getRewardProverStatus at Tier::Control (#595)

* chore: open lane for #3269

Bump dig-rpc-protocol to 0.11.0 (adds dig.getRewardProverStatus and
the other reward RPC methods to the wire).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(rewards): fail-closed Reward-tier guard + dig-rpc-protocol 0.11 line assertion

- dependency_tree.rs: assert the resolved dig-rpc-protocol line is 0.11 (was 0.10);
  documents the known-red two-version state pending the dig-peer 0.14.0 /
  dig-download 0.23.0 cascade (#3269).
- reward_methods_tier_guard.rs: fail-closed guard over the live Method::ALL
  catalogue -- every Reward-named method must be Tier::Control and not
  peer-reachable, so a fifth reward method added later is caught at the wrong
  tier automatically rather than inheriting a wrong default (binds #3261's rule
  node-side).
- peer.rs: sibling unit test exercising the real (pub(crate)) is_peer_reachable_method,
  since an external integration test cannot see it -- same guard, executed against
  this node's own allowlist rather than only the shared crate's.

Refs #3269

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* style: remove trailing blank line in reward_methods_tier_guard.rs

* feat(rpc): serve dig.getRewardProverStatus at Tier::Control

Adds the missing handler for PR#595: a new reward_prover_statuses
registry + accessors on Node (empty until #3265 spawns a prover loop,
so the registry read is real, not a stub), a dispatch.rs arm inside
the Method enum match (never the string pre-match), and a
field-for-field mapping from dig-node-core's internal
rewards::state::RewardProverStatus (camelCase-tagged) onto
dig-rpc-protocol 0.11's wire RewardProverStatus (snake_case-tagged
struct, camelCase-tagged ProverState value), widening entry_count
u32 -> u64 explicitly and hex-encoding the three [u8; 32] identity
fields.

An all-zero launcher_id (what an uninitialised registry slot
hex-encodes to) is omitted at this boundary rather than rendered as
a real distributor with a plausible-looking id -- the money-hole
class the dig-rewards-coin driver's adversarial gates found three
times.

Tests (in dig-node-core::lib.rs's existing test module, where the
pub(crate) registry accessors are visible) drive the real dispatch
entry point (handle_rpc -> RpcDispatch::dispatch -> the Method arm)
and assert field-for-field on the serialized JSON body: populated
registry, empty registry (-> {"statuses": []}), zero-id omission,
tier/peer-reachability, enum-match-not-string-prematch, and
launcher_id filtering. The no-health-boolean / no-staleness
assertion is by key set, not substring.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* style: rustfmt the reward-prover-status registry + tests

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* chore(deps): bump dig-download 0.23, dig-peer 0.14, dig-rpc-protocol 0.11

Closes the two-versions-of-dig-rpc-protocol split (#3269): dig-download 0.23.0
and dig-peer 0.14.0 both now resolve dig-rpc-protocol ^0.11, matching
dig-node-core's own dig-rpc-protocol = "0.11.0" line, and dig-node-service's
two 0.10 lines (main dep + dev-dependency restatement for
openrpc_drift_guard.rs) move to 0.11 to match.

Manifests only. cargo update / Cargo.lock intentionally NOT run yet: a fourth
capper, dig-peer-selector ("0.11" in dig-node-core/Cargo.toml), still requires
dig-peer = "^0.13" in every published version through 0.11.1, so the tree
cannot fully resolve until a dig-peer-selector release picks up dig-peer 0.14.
CI will stay red on this commit for that reason, which is expected.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(rpc): close dig-rpc-protocol 0.11 cascade + attribute payout figures

Bump dig-peer-selector 0.11 -> 0.12 (the release that moves onto dig-peer
^0.14) and run cargo update, closing the two-versions-of-dig-rpc-protocol
split: Cargo.lock now resolves exactly one dig-rpc-protocol, at 0.11.0,
alongside dig-peer 0.14.0, dig-download 0.23.0, dig-peer-selector 0.12.0.

Add a subject-attribution test and doc comments to
reward_prover_status_to_wire: total_paid_out_base_units and
reserve_base_units are per-distributor totals (this distributor's payout to
ALL its mirrors, and this distributor's own reserve), never the querying
node's own earnings and never summed/cross-attributed across distributors.
This is the defect class a sibling adversarial gate found in dig-app#403's
rewards pane, which rendered a distributor total as one mirror operator's
personal earnings and overstated by up to 250x.

Checked: rewards/state.rs, rewards/port.rs and rewards/mod.rs contain no
Eligible/verdict/payout_hash symbol, so nothing in this mapping surfaces a
persisted EligiblePayoutHash verdict.

Refs #3269

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(rpc): silence dead_code on register_reward_prover_status pending #3265

Clippy's non-test lib target has no production caller for
register_reward_prover_status yet, because #3265 (the always-on prover loop
that would call it from bring-up) has not landed -- only tests call it today.
cfg_attr(not(test), allow(dead_code)) stands in for that missing caller
until #3265 wires a real one.

Refs #3269

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(rpc): make the all-zero identity guard non-silent and cover all three fields

Security (blocking) and the adversarial leg both found the same defect in the
zero-launcher_id filter: it checked only launcher_id, so a registration bug
that zeroed store_id or root beside a valid launcher_id would pass through as
a plausible record, and dropping the bad record silently destroyed the
evidence a registration bug happened at all -- SPEC Sec2.4 clause 1's exact
prohibition.

zeroed_identity_fields() now checks launcher_id, store_id AND root. The
dispatch filter still excludes a record with any zeroed field (never renders
an uninitialised slot as a real distributor), but first fires a
tracing::warn! naming which field(s) were zero, so a bad registration is
observable rather than swallowed. Kept isolated in dispatch.rs rather than
woven into the wire mapping, since this belongs at #3265's writer once that
lands.

Replaced get_reward_prover_status_omits_an_all_zero_launcher_id (which
proved the omission but not the observability, and never exercised a zeroed
store_id/root beside a valid launcher_id) with
get_reward_prover_status_logs_and_excludes_a_zeroed_identity_field, covering
both a zeroed launcher_id and a zeroed store_id beside a valid launcher_id,
and asserting the tracing::warn! output via the crate's existing
capture_sync_logs test utility.

Fixed a now-false "Known-red" doc comment on
tests/dependency_tree.rs::the_workspace_carries_exactly_one_module_wire_crate:
the dig-peer 0.14.0 / dig-download 0.23.0 / dig-peer-selector 0.12.0 cascade
already landed in this PR's Cargo.toml/Cargo.lock, so the assertion is green,
not red. Assertion itself untouched -- still exact-version.

Refs #3269

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(rpc): correct a born-false "shipped dig-app 15.5.0" doc claim

dig-app's latest release is v15.4.0 -- there is no v15.5.0 tag -- and
dig-app#403 (the pane that would consume dig.getRewardProverStatus) is OPEN
and unmerged. Point the doc comment at the real, unmerged consumer instead
so a future reader doesn't take this as evidence a shipped consumer depends
on the guard, which would wrongly discourage relocating it to #3265's writer.

Refs #3269

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(rpc): correct doc placement, assert the zeroed field by name, treat root as an observation

Three findings from the correctness gate on PR#595 at 134864a9.

1. The zeroed-identity helper's doc block was spliced onto the end of
   reward_prover_status_to_wire's block with no separator, so the wire-mapping
   rationale documented a boolean predicate and the mapping function was left
   with no doc at all. Each doc block now sits above the item it describes.

2. The log assertion `logs.contains("launcher_id")` was a tautology: the warn
   emits launcher_id as a structured field on every fire, so the property the
   guard exists to add -- naming which field was zeroed -- was unasserted.
   Deleting `zeroed_fields = ?zeroed` from the warn left every assertion green.
   The test now asserts the zeroed_fields value itself, which the fixture makes
   exact and disjoint across cases.

3. `root` is an observation, not an identity. A registered prover that has not
   completed its first cycle plausibly has no root, and a writer that zero-inits
   it would have made a healthy prover invisible. A zeroed launcher_id or
   store_id still excludes the record; a zeroed root alone warns and returns.

Refs #3269

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(rpc): restore zeroed_fields structured field dropped from the pushed warn

The previous commit (080be3df) landed with `zeroed_fields = ?zeroed` missing
from the tracing::warn! call in the GetRewardProverStatus filter -- a
one-line regression introduced while proving the new log assertion goes red
without it, never restored before the commit was made. Without this field
the log line never names WHICH field was zero, so an operator sees only
that something was excluded, and the test asserting `zeroed_fields=[...]`
per case would fail. Restored; all 7 reward-prover-status tests green.

Refs #3269

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(rpc): split zeroed-field logging by level -- WARN for a missing
identity, DEBUG for a zeroed root

A zeroed launcher_id or store_id is a real registration bug: the record is
excluded and now logs at WARN, naming the exact field(s) via
`zeroed_fields=[...]`. A zeroed root alone is an ordinary pre-first-cycle
state, not a fault: the record is still returned, and now logs at DEBUG
instead of WARN, so an operator polling this endpoint sees warn-level
volume proportional to real registration bugs, not to every
not-yet-cycled prover on every poll.

Updated the doc comments on `zeroed_fields`, the dispatch filter and the
test to describe the level split, and extended the regression test to
assert on level (WARN vs DEBUG) as well as the `zeroed_fields` value.
Proved both directions: flipping the DEBUG branch back to WARN turns the
test red on the level assertion; flipping the field-name assertion back to
a bare `contains("launcher_id")` would have passed unconditionally (the
prior tautology) and is no longer possible since the assertions now pin
`zeroed_fields=[...]` plus the level string.

Refs #3269

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>

* feat(rewards): peer-side claim loop -- watch distributors, claim on cadence (#3251) (#594)

* feat(rewards): peer claim loop skeleton -- discovery, cadence, config, claim port

* test(rewards): write all twelve acceptance tests for the peer claim loop

* feat(rewards): wire the seven rewards_claim submodules into the crate

mod.rs declared no submodules, so types.rs/port.rs/config.rs/cadence.rs/
parser.rs/engine.rs/hints.rs (1,435 lines, 25 tests) were never part of the
crate and never compiled. Declare them and re-export the public surface.

* style(rewards): cargo fmt the rewards_claim submodules

* chore(deps): bump dig-node-control-interface 0.33->0.35, dig-rpc-protocol 0.10->0.11.0

dig-rpc-protocol 0.11.0 is merged and tagged upstream; the other dig-*/chia-*
deps of dig-node-service were already at the latest permitted-by-caret version
in Cargo.lock. crates/dig-node-core/Cargo.toml is untouched (#3250's file set).

* chore(deps): revert dig-node-control-interface and dig-rpc-protocol bumps

Both create a duplicate-version split in this PR's scope and neither can be
closed without editing a sibling crate's manifest this lane does not own:

- dig-rpc-protocol 0.11.0 duplicates against dig-node-core/Cargo.toml:194
  ("0.10.2"), which is #3250's live file set (dig-node#593).
- dig-node-control-interface 0.35.0 duplicates against
  dig-wallet/Cargo.toml:81 ("0.33"), a sibling crate this lane does not own;
  the observed Clippy break (BalanceAsset/Asset type-identity mismatch,
  missing url_reconcile/url_current/urls fields) came from THIS duplicate,
  not from dig-rpc-protocol.

Both belong to their own sequenced dep-bump unit of work, not this ticket.

* fix(rewards-claim): fault laundering, permanent no-entry blacklist, fee ceiling magnitude

Three independent gates on dig-node#594 (51516e62) found four logic defects; this
addresses A, B and C per the corrected fix brief (D is documented only, not fixed
here per the brief's own instruction).

Defect A -- the anti-silence surface laundered every real fault into `Nominal`:
- A1: `fault_reported` had no fault-bearing ClaimLoopState to fall through to, so a
  chain adapter erroring every cycle read `Nominal` forever. Added
  `ClaimLoopState::Faulted { cycles }`, outranking Nominal/ClaimableButNotClaiming,
  under ChainSourceUnavailable.
- A2: inverted the test that asserted A1's bug as correct behaviour.
- A3: `ClaimableButNotClaiming` compared a per-cycle snapshot
  (`distributors_claimable`) against a lifetime-cumulative counter
  (`claims_submitted`), so it latched healthy forever after one lifetime success.
  Added `claims_submitted_this_cycle` (per-cycle) as the correct comparand; kept
  `claims_submitted` as a cumulative counter.
- A4: `last_discovery_at`/`last_cycle_at` were stamped even on a failed discovery
  or an all-faulted cycle, destroying the staleness signal a reader depends on.
  Now only stamped on success; added `last_attempt_at` to prove liveness
  separately. `fault_reported` and `distributors_faulted` now reset per cycle
  instead of latching for the process's lifetime.

Defect B -- "terminal, stop retrying" was implemented as a process-lifetime
blacklist (`terminal_no_entry: HashSet<Bytes32>`, never cleared). That blocked
SPEC 12.5 clause 2's re-entry path (evicted, re-challenged, re-admitted never
claims again) and permanently punished a peer that discovered a distributor
before the funder's AddEntry landed. Removed the blacklist entirely -- `own_entry`
is a cheap chain read, re-issued every cycle for every candidate, matching clause
3's "never cache across cycles". `NoEntrySlot` is now a per-cycle observation, not
a lifetime sentence.

Defect C -- the fee ceiling didn't bind anything and there was no aggregate cap:
- C1: default `CLAIM_FEE_CEILING_MOJOS_DEFAULT` lowered from 1_000_000_000
  (transplanted from `MIRROR_SPEND_FEE_CEILING_MOJOS`, sized for a mirror-coin
  spend) to 200_000 -- 2x the observed routine Chia fee range (5,000-100,000
  mojos), so it actually binds instead of leaving 4-5 orders of magnitude of
  slack.
- C2: added a per-cycle aggregate fee budget
  (`max_cycle_fee_budget_mojos`, default 10x the per-claim ceiling) checked
  across all claims in a cycle, closing the attacker-cost gap where funding K
  distributors could force a victim to spend K x the per-claim ceiling per cycle.
  New `ClaimOutcome::SkippedCycleBudgetExhausted`.

Tests: rewards_claim test count 26 -> 37 (11 new: repeated_discovery_faults_never_
read_as_nominal, failed_discovery_leaves_last_discovery_at_unchanged, a_reported_
fault_surfaces_as_faulted_not_nominal, a_lifetime_submission_does_not_mask_a_
later_cycle_that_submits_nothing, no_entry_slot_then_re_admitted_produces_a_claim_
on_the_later_cycle, distributors_each_under_ceiling_do_not_collectively_exceed_
the_cycle_budget, the_default_per_claim_ceiling_actually_binds_a_routine_fee, plus
renamed/rewritten no_entry_slot_is_non_terminal_and_re_checked_every_cycle).

Refs #3251

* fix(rewards-claim): refuse a claim entry for the wrong payout puzzle hash

CI fix: cadence.rs's RewardsClaimConfig literal was missing the
max_cycle_fee_budget_mojos field added in the previous commit (E0063,
caught by CI's Clippy/Test jobs -- the local cargo check for this
workspace is too slow to use as the compiler here).

Defect E (security-gate finding, folded in before this pass closes):
submit_initiate_payout was called with entry.payout_puzzle_hash -- whatever
the chain port handed back -- with no check against this node's own
own_payout_puzzle_hash. UnavailableClaimChainPort is the only production
adapter today so nothing can exploit this yet, but the whole point of the
ClaimChainPort seam is that #3249 swaps in a real adapter with nothing
above it changing, so deferring this would ship the landmine live with no
review pass watching for it. Added an equality guard before the spend:
a mismatch refuses to submit, counts
(ClaimStatus::claims_refused_payout_mismatch), surfaces its own named
outcome (ClaimOutcome::PayoutPuzzleHashMismatch), and is reported as a
fault (a divergent entry means the port is confused or hostile, not that
there is nothing to claim) -- never corrected by substituting our own
hash and proceeding.

Defect D: documented, not wired, per instruction -- added the "not yet
wired into node startup" paragraph to mod.rs's module doc (the PR body
carries the same paragraph) so the next reader arrives at the caveat in
the code, not only in a merged PR description.

Refs #3251

* fix(rewards-claim): B1 -- ClaimableButNotClaiming is a magnitude comparison, not a zero-test

submitted_this_cycle < claimable_this_cycle now fires the anti-silence state, carrying
the shortfall as ClaimableButNotClaiming { claimable, submitted }. The previous
submitted_this_cycle == 0 zero-test let one submission mask any number of same-cycle
skips (claimable=10, submitted=1 read Nominal).

Also folds in B3's precedence fix (ChainSourceUnavailable > Faulted >
ClaimableButNotClaiming > Idle > Nominal) and the per-distributor
payout_hash_mismatches_this_cycle counter so a per-distributor fault can no longer
pin the cycle-wide Faulted state, plus R2's rename of terminal_no_entry_slot to
no_entry_slot_this_cycle now that it is no longer terminal.

* fix(rewards-claim): B2/B3 -- value-ordered budget with rotation, per-distributor fault isolation

B2: run_cycle now splits into a pre-budget phase (asset/entry/hash/threshold checks,
producing the claimable set) and a budget phase, ordering the claimable set by accrued
value descending before applying the fee ceiling and cycle budget. Dust distributors
(low accrued value regardless of attacker-controlled fee) now sort last and are the
ones the budget drops, closing the claim-suppression attack where ten high-fee dust
distributors could consume the whole cycle budget ahead of a victim's real earnings.
A rotation_cursor tie-breaks only WITHIN equal-accrued-value tiers so a genuinely
tied honest tail that exceeds one cycle's budget every cycle still rotates through
and is eventually served, rather than dropping the same tail forever.

B3: the payout-hash mismatch check in evaluate_pre_budget now increments the
per-distributor payout_hash_mismatches_this_cycle counter instead of setting
fault_reported, so one hostile or buggy entry can no longer pin the cycle-wide
Faulted state and bury ClaimableButNotClaiming for every other healthy distributor.

R2: terminal_no_entry_slot -> no_entry_slot_this_cycle throughout.

* fix(rewards-claim): R5 -- document not-yet-wired loop; persist B2 rotation cursor

An operator reading their own rewards-claim.json and seeing enabled: true has no way
to know from that file alone that no startup path constructs a ClaimEngine yet
(#3268) -- mod.rs said so, but a config file reader does not arrive at a module doc.

Also gives RewardsClaimConfig a rotation_cursor: Option<Bytes32> field so B2's
tie-break cursor survives a save/load round-trip -- an in-memory-only cursor resets
on every restart, which would starve a legitimately tied honest tail forever on any
node that restarts daily.

* fix(rewards-claim): clippy collapsible-match + SPEC v0.1.3 wording refresh

Collapses the nested if into the outer match arm in run_cycle (clippy::collapsible_match).
Also refreshes NoEntrySlot / no_entry_slot_this_cycle doc comments now that
dig-rewards-coin v0.1.3's SPEC §12.5 amendment is merged and tagged: absence is
terminal for one claim attempt only, never for the distributor, must not be cached,
and must not accumulate into a permanent exclusion set -- confirming rather than
diverging from the re-read-every-cycle behaviour already implemented.

* fix(rewards-claim): add missing rotation_cursor field in cadence.rs test literal

Struct literal in the cadence test module was not updated when RewardsClaimConfig
gained rotation_cursor (R5 commit) -- CI's Clippy/Test jobs caught the missing field
(E0063) that a local cargo check could not (killed by memory pressure before this
workspace-wide build completed).

* fix(rewards-claim): F1 -- ChainSourceUnavailable is per-cycle, never a latch

compute_state() compared against self.state -- last cycle's OWN computed
output -- so once any cycle took an Unavailable port path, every later
cycle re-asserted ChainSourceUnavailable forever, even after the chain
came back and real claims were submitting. A node still syncing, or one
dropped connection, was enough to trip this permanently.

Add ClaimStatus::chain_unavailable_this_cycle, reset to false at the top
of every run_cycle and set true only on a cycle that actually took the
Unavailable path; compute_state now reads that flag instead of
self.state, so the reading is live again.

Test: a_transient_unavailable_cycle_does_not_latch_state_for_the_rest_of_the_process
(engine.rs) drives cycle 1 unavailable, cycle 2 healthy with a
submission, and asserts cycle 2 reads Nominal. Plus a compute_state-level
regression in types.rs.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(rewards-claim): F3/F4/F5 -- fix stale counters, dedup candidates, correct version doc

F3: reset EVERY per-cycle counter (distributors_known/with_own_entry/
claimable/faulted, claims_submitted_this_cycle, no_entry_slot_this_cycle)
at the TOP of run_cycle, before any early return. The three
ChainUnavailable early-return paths skip the end-of-function assignment
block entirely, so a cycle that hit one used to leave the PRIOR cycle's
counts sitting on self.status while last_attempt_at stamped fresh for
THIS cycle -- a stale count under a fresh timestamp, exactly what SPEC
§2.4's staleness reasoning forbids. types.rs's doc sentence for
no_entry_slot_this_cycle now correctly says it is dated by
last_attempt_at (the field stamped unconditionally every cycle), not
last_cycle_at.

F4: dedup `candidates` by launcher id before phase 2. A real adapter
scanning §1.3 launch comments across every (store_id, root) this node
mirrors can plausibly return the same launcher id twice; without dedup
phase 2 would evaluate it twice and submit InitiatePayout twice against
one entry slot in one cycle -- the second spend is invalid but the fee
is paid anyway.

F5: dig-rewards-coin is v0.1.3, published on crates.io -- correct the
stale "v0.1.1" module-doc claim.

Tests: a_chain_unavailable_cycle_does_not_leave_prior_cycles_counters_stale
(F3), a_duplicated_launcher_id_submits_exactly_once (F4).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(rewards_claim): fold payout-hash mismatches into the shortfall predicate (F2)

A payout-hash mismatch never enters the eligible set, so it was counted in
NEITHER distributors_claimable NOR claims_submitted_this_cycle -- the
shortfall lived in neither term of compute_state's magnitude comparison.
All-K-distributors mismatching therefore read Nominal (falsely healthy).

Fold payout_hash_mismatches_this_cycle into the comparison's denominator:
submitted < claimable + mismatches. The result is ClaimableButNotClaiming
(a shortfall), never the cycle-wide Faulted -- Defect B3 stays fixed.

Inverts the assertion at what was engine.rs:1305
(a_payout_mismatch_never_sets_the_cycle_wide_fault_or_masks_other_distributors):
it previously asserted ClaimLoopState::Nominal across three cycles of an
ongoing mismatch, which pinned the defect as intended behaviour (an
A2-class test). It now asserts ClaimableButNotClaiming { claimable: 1,
submitted: 1 }.

Adds all_distributors_mismatching_is_a_shortfall_not_nominal, covering the
brief's exact "what if every distributor refuses for the same reason" case.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(rewards-claim): F1/F3 -- AtomicU32 in fake ports, not Mutex, keeps discovery Send

CI's Clippy job (the compiler for this crate, per brief) caught it: holding
a std::sync::MutexGuard across the .await in FlakyThenHealthyPort and
HealthyThenUnavailablePort's discover_distributors made the returned future
not Send, which #[async_trait]'s generated trait signature requires.

Neither fake needs a lock -- each holds one call counter, incremented once
per call, never read-modify-written across an await point. AtomicU32's
fetch_add removes the guard (and the Send bound violation) entirely.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(rewards-claim): F7 -- persist the fee window and cadence gate across restart

The per-cycle aggregate fee budget and the 24h cadence clock both lived only
in memory: `spent_this_cycle_mojos` was a `run_cycle` local and nothing on
disk recorded a completed cycle. Every fresh process got a full
`max_cycle_fee_budget_mojos` and an empty cadence clock, so a node stuck in
a crash-restart loop could spend unbounded XCH on fees, one full budget per
restart.

Adds three `#[serde(default)]` fields to `RewardsClaimConfig`
(`fee_window_start_unix`, `fee_spent_in_window_mojos`,
`last_cycle_completed_at`) and a new opt-in `ClaimEngine::with_persisted_fee_
window(dir, cadence_seconds)` that:
- restores the window/cadence state from `dir` at construction,
- refuses to start a cycle until the cadence has elapsed since the last
  completed one,
- rolls a fresh budget window only once the cadence has elapsed since it
  opened, otherwise keeps enforcing the budget against the persisted spend,
- persists the spend BEFORE every chain submission (write-then-spend), never
  batched to cycle end, and persists the completed-cycle timestamp when a
  cycle finishes.

Engines that never call `with_persisted_fee_window` (every pre-F7 test) are
unaffected -- this is additive, opt-in state beside the existing rotation
cursor, not a change to B2's value-ordering or rotation mechanism.

`ClaimStatus`'s own counters stay in-memory on purpose (observability, meant
to reset on restart); only the spend bound and the cadence gate persist.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(rewards-claim): F7 -- update cadence.rs test literal for new persisted fields

The three new persisted RewardsClaimConfig fields (fee_window_start_unix,
fee_spent_in_window_mojos, last_cycle_completed_at) broke this crate's only
remaining full struct literal outside config.rs/engine.rs's own test
modules -- E0063 missing fields, caught by CI's Clippy job. Switched to
..RewardsClaimConfig::default() so the next added field cannot break this
literal again, the same fix already applied once before for rotation_cursor.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(rewards-claim): F8/F14 -- atomic state write, fail closed on a corrupt window

Salvaged from a lane killed by a weekly cap before it could commit. Uncompiled at
commit time; CI is the compile signal.

Covers the fourth gate pass findings on the F7 persisted spend bound:

- F8: RewardsClaimConfig::save_to now writes atomically (temp file + rename in the
  same directory), reusing the pattern already used by mirror/reconcile_state.rs
  for the same class of state. load_from distinguishes an ABSENT file (clean first
  run, defaults are correct) from a PRESENT but unparsable one, which fails CLOSED:
  the window is treated as fully spent and nothing is submitted. Never Default, and
  never a silent clamp downward, which would hand back the budget the corruption
  was hiding.
- F14: the budget comparison uses saturating arithmetic so a corrupt disk-seeded
  fee_spent_in_window_mojos cannot panic under the release profile's
  overflow-checks.
- F9/F10/F12/F13 in progress in the same files.

Refs #3251

* fix(rewards-claim): negate with ! rather than the unimported Not trait

Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>

* fix(rewards-claim): F13 -- correct stale test literals to the folded shortfall

compute_state (types.rs) already reported the folded shortfall
denominator (distributors_claimable + payout_hash_mismatches_this_cycle)
as `claimable` -- that part of F13 landed in f478516a. The two engine.rs
tests asserting this state were written against the pre-fold, un-folded
numbers and never updated, so CI showed the implementation producing the
correct folded value (`claimable: 2`, `claimable: 1`) while the test
literals still expected the stale un-folded one (`claimable: 1`,
`claimable: 0`).

Update both literals -- and the comments describing them -- to the
folded values the F13 fix actually produces. No production code change;
compute_state's predicate and payload were already correct.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* feat(rewards-claim): add ClaimOutcome::Faulted variant

Add the seventh ClaimOutcome variant: the type could only say a peer was
legitimately not paid, never that a chain call failed. Carries the launcher
id, a bounded (200 char) copy of the chain port's error text, and whether a
pre-committed fee was reversed, so a reader can tell no money moved.

Engine wiring at the two fault arms (engine.rs:332, :377) follows in the
next commit.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(rewards-claim): both fault arms now push ClaimOutcome::Faulted

engine.rs:332 and :377 used to increment `faulted` and discard the
outcome, leaving a definitively-failed claim absent from the outcome
stream -- indistinguishable from a cycle that never touched that
distributor. Both PreBudgetResult::Fault and BudgetPhaseResult::Fault
now carry the chain port's (bounded) error text, and the
submit_initiate_payout failure path also carries the fee it reversed,
so a reader can tell no money moved. The counter stays; it is not a
substitute for the outcome.

7 call sites needed updating: 3 PreBudgetResult::Fault constructions
(reserve_asset_id, own_entry, payout_threshold), 2 BudgetPhaseResult::Fault
constructions (required_fee_mojos, submit_initiate_payout), and the 2
consuming match arms -- exactly the set that was silently discarding a
failure before this change.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(rewards-claim): a failed submission produces a Faulted outcome

Regression for the rework: reuses F12's fixture (a submission that
definitely never broadcast) to prove both facts from one cycle -- the
outcome exists and carries the reversed fee, and the persisted window
still reflects zero net spend. Also fixes a rustfmt diff on the
PreBudgetResult::Fault variant Clippy's Rustfmt job flagged.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(rewards-claim): delete fee_window_poisoned, stop latching self-healing state

Finding 1 (dig-node#594 pass 6): a future-dated clock is self-healing by
construction (`t > now` goes false the moment real time passes it), but the
engine ORed it into `self.fee_window_poisoned` and set that field `true`
permanently -- an RTC glitch or VM resume froze the claim loop forever instead
of until the skew passed. This is the third instance of one mechanism (pass 3
latched ChainSourceUnavailable, pass 4 left a stale cadence-gate `state`), so
the fix removes the FIELD, not just the bug: with no `fee_window_poisoned` on
`ClaimEngine`, `self.fee_window_poisoned = true` is a compile error, not a
convention to remember.

Per-cycle conditions (corrupt + future-dated-clock) now live in a
`CycleConditions` value built fresh at the top of every `run_cycle` from `now`
plus a freshly reloaded `RewardsClaimConfig`, used, and dropped -- never
stored on the engine. `corrupt` is now re-read from disk every cycle too (it
previously latched at construction only), matching what
`ClaimLoopState::PersistedStateCorrupt`'s doc already claimed but the code
never did.

Rewrites the single-cycle f10 regression into a two-cycle test: cycle 1 with a
future-dated clock refuses; cycle 2, after the clock catches up and the
cadence elapses, MUST claim. The old one-cycle version was green whether the
latch bug was present or not.

Refs #594

* fix(rewards-claim): satisfy clippy doc-list indent and rustfmt

Clippy failed with 3x doc_lazy_continuation on the PersistedStateCorrupt
doc comment (types.rs:165-167): continuation lines of a `-` bullet must
be indented under the marker, not left flush. Indent them.

Rustfmt failed on the new fail_reserve_asset_for early-return in
FakeChainPort::reserve_asset_id (engine.rs:888): the Err(...) call
exceeded the line-length limit unwrapped. Let rustfmt wrap it.

Refs #594

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* test(rewards-claim): red proof for corrupt-then-repaired stale read

Cycle 1 refuses a corrupt fee-window file; the file is then repaired to
valid values with a fully-spent window and a recent completed-cycle
time. Cycle 2 must neither grant a fresh budget nor skip the cadence
gate. Fails against current `with_persisted_fee_window`, which loads
the three fee-window fields once at construction and never refreshes
them from the per-cycle `cfg` -- see engine.rs:149-157, #594.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* fix(rewards-claim): resync fee-window fields from disk every cycle

`with_persisted_fee_window` only loaded fee_window_start_unix,
fee_spent_in_window_mojos and last_cycle_completed_at once, at
construction. Once the now-deleted fee_window_poisoned latch stopped
masking it, a file corrupt at construction and repaired later left
those three fields stuck on poisoned()'s None/0/None placeholders --
a fresh budget and a skipped cadence gate, and persist_fee_window then
overwrote the repaired disk values with them.

CycleConditions now carries the three fields from the SAME freshly
reloaded cfg it already used for the corrupt/future-dated check, and
run_cycle copies them onto self before the cadence gate or window-roll
logic runs, but only on a read that is neither corrupt nor future-
dated. This also fixes Finding 2b: future_dated_clock now reads cfg's
own clocks instead of self's stale ones. Corrects the doc claim at the
old lines 236-238 to describe what the code now does for both halves.

Closes #594.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

* refactor(rewards-claim): make disk the sole store for the fee window

Delete `fee_window_start_unix`, `fee_spent_in_window_mojos` and
`last_cycle_completed_at` from `ClaimEngine`. `run_cycle` already re-reads
`RewardsClaimConfig` fresh every cycle for the corrupt/future-dated check,
so caching a copy on the engine bought nothing and cost exactly the
stale-read defect class F16 just fixed. A local `FeeWindowState`, scoped to
one `run_cycle` call, now threads the in-flight values through
`evaluate_budget_phase`/`uncommit_fee`/`persist_fee_window` instead. With
no field left to cache into, a future `self.fee_window_start_unix = ...`
outside this file is an E0609 compile error, the same enforcement
`fee_window_poisoned`'s removal already has.

No behaviour change: every early return, the corrupt/future-dated fail-
closed path, the cadence gate, the window roll, write-then-spend
pre-commit/uncommit and the per-claim ceiling are unchanged -- only where
the three values live changed.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>

* feat(rewards): chain port + listRewardDistributors (unit 2) (#604)

* chore: open lane for #3269 (unit 2 -- rewards chain port + listRewardDistributors)

* chore(rewards): add dig-rewards-coin 0.2 dep; record blocked-reader finding

dig-rewards-coin 0.2.0 is published but ships no chain reader (its own
state.rs module doc: SPEC 12.1's read_distributor is withheld pending
DIG-Network/dig_ecosystem#3267). Separately, no registry in this codebase
records which distributors this node funds. A "real" RewardsChainPort
adapter over 0.2.0 therefore has no honest way to answer any of the four
trait methods with live data yet -- reimplementing read_distributor or
inventing a funded-distributor registry would be exactly the unreviewed
money-shape guess kernel invariant 6 says to escalate instead of build.
UnavailableChainPort remains the only production adapter; port.rs records
the finding for the next unit.

Refs #3269

* docs(rewards): revert dep add, name both blockers with evidence in port.rs

Per L1 direction: an unused dig-rewards-coin dep with no consumer is inert
weight and would want whichever version ships the reader (0.3.0+, PR#6 open
against DIG-Network/dig-rewards-coin), not 0.2 -- so it's reverted here and
belongs in the unit that actually consumes it.

Expanded the port.rs module doc to name both blockers explicitly with what
was read (state.rs:1-31, #3267, the open reader PR) and the negative grep
that found no funder-ownership registry anywhere in the tree, plus why
serving dig.listRewardDistributors through UnavailableChainPort was
considered and rejected (false capability signal; the exact "dispatch
surface with no function behind it" pattern dig-node#593 was the last PR
allowed to land on).

No RewardsChainPort adapter, no Node wiring, no dispatch arm -- all three
reward methods stay -32601 pending #3267 and a funder-ownership registry
(parallel tickets, both required).

Refs #3269

* feat(rewards): durable funder-ownership registry (identity only) (#606)

* feat(rewards): durable funder-ownership registry (identity only)

Records WHICH reward distributors this node funds -- launcher id plus the
store id when the funding act knew it -- and nothing else. No amount can
be recorded: every money figure here is chain-derived and goes stale, and
dig_ecosystem#3286's wrapping u64 share multiply means a figure crossing
this boundary can already be wrong. Durable storage would make it
permanent.

Persistence mirrors rewards_claim::engine::ClaimEngine: an optional state
directory (absent = inert, so tests and default builds need no disk),
atomic write, and a corrupt record is never overwritten. The set is never
cached on the registry -- every read re-reads the file -- so no transient
state lives on the struct across calls (the engine's F16/F18 discipline).

The read outcome is closed and distinguishes funds-nothing from every
unknown: NotConfigured (no state dir / dir missing / nothing written yet),
PersistedStateCorrupt and IoFailed. A corrupt record is quarantined by
COPY and left in place, so the next read is corrupt too rather than
decaying into an empty list -- SPEC 2.4 clause 1 in the place it costs
most, since an empty dig.listRewardDistributors tells an operator it funds
no distributors.

Node carries it in a OnceLock slot with pub(crate) accessors, mirroring
mirror_pointers and reward_prover_statuses. Nothing installs it in
production yet: no dig-node code funds a distributor, and the startup
wiring belongs to dig_ecosystem#3268, so the slot is marked the same way
register_reward_prover_status is.

Refs #3285

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(rewards): drop a duplicated funded_distributors initializer

Two test-only `Node` literals got the slot twice (E0062), because the
inserted line's own indentation made the wider-indented site match twice.

Refs #3285

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(rewards): wire the peer claim loop onto a cadence driver from real startup (#3268) (#605)

* feat(rewards): wire the peer claim loop onto a cadence driver from real startup (#3268)

The peer reward-claim engine shipped complete and tested in #594 but INERT:
nothing constructed it, so the 86400s cadence never fired while
`rewards_claim.enabled` defaulted to `true` -- a config asserting a subsystem
is on while nothing runs.

`rewards_claim/driver.rs` is a SCHEDULER, not a chain adapter: it derives this
node's own payout puzzle hash, loads `RewardsClaimConfig`, builds a
`ClaimEngine` against the only production port that exists
(`UnavailableClaimChainPort`, until #3249 lands a real one) and drives
`run_cycle` every `cadence_seconds + jitter`, jitter drawn from the OS CSPRNG.
`server.rs`'s `serve_with_shutdown` makes exactly one call into it, beside
`self_heal::spawn_driver_if_service()`.

`enabled = true` now means: a background task exists, drives a counted cycle
per interval, and its outcome is readable in-process as a NAMED state. With
`UnavailableClaimChainPort` every cycle honestly reports
`ChainSourceUnavailable` -- the gap is loud instead of silent.

Anti-silence: `ClaimLoopHandle` carries a monotonic `cycles_driven` counter
alongside the status, because `Idle` before the first cycle is correct and
honest, so status alone cannot tell "scheduler never fired" from "nothing was
claimable". The gate takes an INJECTED handle rather than reading the
process-wide singleton, so `ClaimDriverRefusal::{Disabled, ChainSyncDisabled,
NoOperatorWallet}` and "spawned but never ticked" are four pairwise-distinct
readings a test asserts in-process.

Nothing goes on the wire: no RPC method, dispatch row, handler or OpenRPC
entry. `ClaimStatus` stays off the wire until #3249's real adapter lets the
status surface be re-derived against it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(rewards): silence the deliberately-ignored fake-port argument (#3268)

`OneDistributorPort::own_entry` ignores the puzzle hash the engine passes in
on purpose -- the fake always returns the entry keyed to `entry_keyed_to` so
the ENGINE's own comparison is what decides claimable vs. refused. Named it
`_payout_puzzle_hash` (clippy `-D unused-variables`) and moved the rationale
onto the parameter, where the next reader meets it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* test(rewards): close the untested joint between the claim gate and the drive loop (#3268)

`decide_claim_driver` was tested and `drive` was tested, but the production
body joining them -- load the config from the state dir, derive the engine,
reach `drive` -- was exercised by nothing. That is the exact shape of #594,
which shipped a complete, fully-tested and entirely inert claim engine: had
this body returned early, built the engine wrong, or never reached `drive`,
every test on this change would still have passed and a real node would still
never claim.

Split `run_claim_driver` on the same `load` / `load_from` pattern the config
itself uses: `run_claim_driver_in(state_dir, own_payout_puzzle_hash, port,
handle)` holds the whole body and is generic over the port, and
`run_claim_driver` is reduced to the wallet-derivation adapter that cannot be
reached from a test. Adds two tests through the real body: counted cycles from
a written config (zero before the interval, exactly one per interval after),
and `UnavailableClaimChainPort` reporting `ChainSourceUnavailable` by name on a
driven cycle -- proving the production adapter path is reached, not only a fake.

No behaviour change: same config, same engine construction, same port.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(rewards): settle before advancing, and keep the wrapped assertion out of rustfmt's reach (#3268)

Two repairs to the new composition tests:

- The `ChainSourceUnavailable` test advanced the paused clock before the
  spawned body had reached its first `sleep`, so the timer was not yet
  registered and the advance bought no cycle at all -- it read zero cycles, not
  a driven one. A `settle()` first, mirroring the counted-cycles test.
- rustfmt rejoined a `\`-continued assertion message into one line, leaving 14
  literal spaces mid-sentence and tripping the repo's own
  `continuation_guard`. `concat!` states the wrap explicitly, so no formatter
  pass can reintroduce the run.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* feat(rewards): emit a per-cycle event so the claim loop has a reader (#3268)

The adversarial gate blocked #605 on this: the PR justified itself by making
an inert subsystem loud, but nothing in the shipped binary could hear it.
ClaimLoopHandle had no caller outside driver.rs tests, drive() emitted no
event, and all three tracing calls fired only on paths where the loop does
NOT run -- so on the default path (enabled=true, chain sync on) the
observable output was identical to before the PR: silence. Today that
silence covers a permanent ChainSourceUnavailable; after #3249 it would also
cover Faulted, PersistedStateCorrupt and ClaimableButNotClaiming.

log_cycle() now names the state and the cycle count after every cycle --
info for Nominal, warn for everything else, because "this peer is earning
nothing and here is why" is a warning, not routine chatter. Tested by
capturing the subscriber output rather than asserting the call site exists,
since this ticket exists because a guarantee that cannot be observed in a
running node is not a guarantee.

Refs DIG-Network/dig_ecosystem#3268

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(rewards): stop a u64::MAX jitter bound panicking the claim driver

`OsJitter::jitter_seconds` computed `bound + 1` for its modulus. `jitter_seconds`
comes from the node's persisted `rewards_claim` config and is not clamped, so a
config carrying `u64::MAX` overflow-panicked inside the detached claim-driver
task -- which has no restart and emits no further log output, so the claim loop
would die silently for the rest of the process lifetime.

`saturating_add(1)` keeps the draw within `0..=bound` for every input; the
composed `next_interval_seconds` range is unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(rewards): sanitize the claim schedule so no config value silently disables the loop

`next_interval_seconds` saturates instead of panicking, so a persisted
`jitter_seconds = u64::MAX` no longer crashes the driver -- it schedules the
next cycle ~585 billion years out. The claim loop then never fires again: no
cycle, no `log_cycle` line, and a permanent, reassuring `0` cycle count. That is
#594's inert-but-green shape reopened one level up, in the config file.

`run_claim_driver_in` now sanitizes both schedule fields where it reads them,
before either reaches the engine's fee window or `drive`:

- `CLAIM_SCHEDULE_SECONDS_MAX = 31 * 24 * 60 * 60` (31 days) -- above every
  documented default (86,400s cadence, 3,600s jitter) and above "claim
  monthly", while excluding everything that means never.
- out of range (or a zero cadence, which would busy-loop) substitutes the
  published default and emits `tracing::warn!` naming the field, the rejected
  value and the substituted one. Nothing is accepted silently.

`config.rs` is untouched: it keeps reporting what is on disk.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(release): v0.257.0 -- the reward distributor lifecycle starts running

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant