Skip to content

fix(incentive): persist voucher state across restart (#527) - #567

Merged
alpergundogdu merged 3 commits into
mainfrom
fix-527-voucher-replay-persistence
May 15, 2026
Merged

alpergundogdu merged 3 commits into
mainfrom
fix-527-voucher-replay-persistence

Conversation

@thiras

@thiras thiras commented May 14, 2026

Copy link
Copy Markdown
Contributor

Summary

Notable defensive choices

  • Durability::Immediate is set explicitly on every commit so a future redb default change cannot silently weaken the guarantee.
  • open rejects zero-length files (redb otherwise treats them as "create a fresh DB" — a truncate-to-0 would silently reopen the replay window).
  • A failed tighten_permissions removes the partial redb file so the next start sees a clean state, not an out-of-spec file with umask-default mode.
  • forget's read-txn probe avoids implicitly creating the table on a never-written store.
  • ChannelError::Store carries a PROTOCOL NOTE distinguishing retry-eligible failures from permanent rejection variants so Implement cdn/client/v1 paid delivery protocol (StreamRequest, StreamResponse, ChunkData, vouchers) #317's wire encoding can't conflate them.

Test plan

  • cargo build --workspace
  • cargo clippy --workspace --all-targets -- -D warnings
  • cargo fmt --check
  • cargo nextest run --workspace — 800/800 passing (was 794, +6 new)
  • cargo deny check — advisories / bans / licenses / sources all OK (redb 4.x dual-licensed MIT/Apache-2.0)
  • pre-commit run on touched files

Canonical regression test: replay_after_restart_is_rejected in crates/node/tests/channel_state_store.rs. Strict-durability invariant: store_failure_leaves_in_memory_state_unchanged in crates/incentive/src/channel.rs. Empty-file bypass guard: zero_length_file_refuses_to_start.

Out of scope (follow-up issues to track)

  • SchemaVersion(u32) newtype around the on-disk schema field.
  • StoreError::CommitFsync distinguishing fsync failures from other backend errors.
  • U256::MAX boundary test, forget-then-replay documentation-test, same-channel concurrency test.

🤖 Generated with Claude Code

ChannelState tracked last_nonce in memory only — after a node restart the
fresh ChannelState::new() reset to last_nonce=0 and a client could replay
a previously-accepted voucher for a second byte delivery. The on-chain
EIP-712 + monotonic-nonce protections in ADR 003 only constrain what the
contract accepts at settlement; they do not stop a node from re-delivering
bytes off-chain.

Introduce a ChannelStateStore seam in crates/incentive with a redb-backed
PersistentChannelStateStore in crates/node under <data_dir>/channels.redb.
apply_voucher now validates -> builds a candidate state -> store.record
(fsynced via Durability::Immediate) -> only on Ok advances in-memory
state, so Ok(()) is the protocol-level commit point. Runtime opens the
store during start_node on a blocking thread; failure aborts bring-up.

ADR 003 gains an `Off-chain voucher state persistence` subsection
specifying the ordering invariant and the absent-entry==never-seen-channel
semantics. The redb file is rejected if zero-length (truncate-to-0
otherwise bypasses the guard), corrupt, or truncated; tighten_permissions
failures remove the partial file so the next start sees a clean state.

Test coverage:
- replay_after_restart_is_rejected — canonical #527 regression
- store_failure_leaves_in_memory_state_unchanged — FailingStore proves
  apply_voucher does not advance in-memory state when record() fails
- future_schema_version / corrupt_value_bytes / key_value_mismatch —
  guard the UnsupportedSchema / Corrupt branches of load_all
- zero_length_file_refuses_to_start — redb empty-file bypass guard
- concurrent_vouchers_across_distinct_channels — tokio multi-thread
- corrupt_file / truncated_file / bad_permissions — refuse-to-start

A TODO(#317) on the router builder spells out the four-step checklist
the future cdn/client/v1 handler must follow so the replay guard stays
in force by construction.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 14, 2026 22:53
@github-actions

github-actions Bot commented May 14, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 88.93% (was 89.00%, ▼ 0.07%) — 14329/16112 lines

File Coverage Lines Δ
crates/incentive/src/channel.rs 95.97% 286/298 ▼ 3.15%
crates/incentive/src/store.rs 92.22% 83/90 new
crates/node/src/channel_store.rs 89.44% 415/464 new
crates/node/src/runtime/mod.rs 52.50% 388/739 ▼ 1.24%
History
Commit Total Δ vs base
cdf32a1 88.94% ▼ 0.06%
2318769 88.94% ▼ 0.07%
0014cb2 (HEAD) 88.93% ▼ 0.07%

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR closes the voucher replay window across node restarts (issue #527) by introducing a durable ChannelStateStore abstraction in crates/incentive, implementing a redb-backed persistent store in crates/node, and making ChannelState::apply_voucher persist the post-acceptance state before advancing in-memory state (making Ok(()) the commit point). It also updates ADR 003 to codify the persistence/ordering invariant and adds regression tests for restart + corruption scenarios.

Changes:

  • Add ChannelStateStore + StoreError seam (with an in-memory test impl) and require a store in ChannelState::apply_voucher.
  • Add PersistentChannelStateStore (redb, fsync-on-commit) and open/smoke-test it during node startup.
  • Add ADR + end-to-end tests covering replay-after-restart, strict durability ordering, and corrupt/truncated/empty-file guards.

Reviewed changes

Copilot reviewed 10 out of 11 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
crates/node/tests/channel_state_store.rs End-to-end regression tests for restart replay and store corruption/truncation/permission cases.
crates/node/src/runtime/mod.rs Opens the channel state store at startup and documents the required future handler wiring steps (#317).
crates/node/src/lib.rs Exposes the new channel_store module for integration tests/consumers.
crates/node/src/channel_store.rs Implements PersistentChannelStateStore on redb with durability and corruption guards.
crates/node/Cargo.toml Adds the redb dependency to the node crate.
crates/incentive/src/store.rs Defines the ChannelStateStore trait, StoreError, and an in-memory implementation for tests.
crates/incentive/src/lib.rs Exports the new store module and types from the incentive crate.
crates/incentive/src/channel.rs Makes voucher acceptance durably persisted before in-memory advancement; adds ChannelError::Store.
Cargo.toml Adds workspace dependency on redb = "4".
Cargo.lock Locks redb v4 for the new persistent store.
adr/003-payments.md Adds protocol-level “Off-chain voucher state persistence” ordering invariant.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/node/src/channel_store.rs Resolved
Comment thread crates/node/src/channel_store.rs Resolved

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Code Review

This pull request implements off-chain voucher state persistence to prevent replay attacks across node restarts, addressing issue #527. It introduces a ChannelStateStore trait and a redb-backed persistent implementation in crates/node. The ChannelState::apply_voucher method now requires a store and ensures that state is durably committed before advancing in-memory fields. Feedback focuses on ensuring forward-compatibility of the on-disk format; specifically, the reviewer noted that postcard::from_bytes is too strict for additive schema changes and suggested using postcard::take_from_bytes to correctly ignore trailing unknown bytes from future versions.

Comment thread crates/node/src/channel_store.rs Resolved
Comment thread crates/node/src/channel_store.rs Resolved
thiras and others added 2 commits May 15, 2026 02:07
Three review-driven fixes to `PersistentChannelStateStore::open`:

1. Chmod-cleanup data-loss (Copilot): the previous unconditional
   `remove_file` on `tighten_permissions` failure would delete a live
   voucher store on any transient chmod error (NFS, read-only mount,
   EPERM) on subsequent starts — reopening the issue #527 replay window
   it exists to close. Now stat-and-remember whether the file pre-existed
   and only remove on cleanup for freshly-created files.

2. Postcard forward-compat (Gemini): `postcard::from_bytes` is strict and
   errors with `DeserializeTrailingBytes` if the input is not fully
   consumed, so the struct doc's claim about "tolerating trailing unknown
   bytes" was false as implemented — an additive field added by a future
   writer would be misclassified as `Corrupt` by an older reader. Switch
   to `postcard::take_from_bytes` returning `(T, &[u8])`, discard the
   remainder, and update the doc to match. New regression test
   `extra_trailing_bytes_are_tolerated` writes a real record plus 8
   trailing bytes and asserts `load_all` decodes the prefix cleanly.

3. Doc/code mismatch on `# Errors` (Copilot): `open()`'s docstring
   claimed `StoreError::Io` for data_dir security check failures, but
   the impl wraps `ensure_data_dir` in `StoreError::Backend`. Rewrote
   the `# Errors` block to enumerate each variant against the path
   that actually returns it.

Tests: 9/9 integration + all unit pass; clippy/fmt clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Second-round review surfaced four real failure modes in the chmod
cleanup path; this commit addresses all of them plus several nits.

Critical / Important fixes:

1. Idempotent chmod: tighten_permissions now stats the current mode
   first and skips the set_permissions syscall when it already matches
   DB_FILE_MODE. A read-only mount (EROFS) where a prior successful boot
   left the file at 0o600 now boots cleanly instead of bricking.

2. Atomic file-creation claim: replaced the stat-only TOCTOU detection
   with OpenOptions::create_new(true). A sibling process restoring a
   backup between our initial NotFound stat and Database::create now
   flips file_existed_before_open to true (AlreadyExists error from
   create_new), so the cleanup branch correctly preserves the sibling's
   work rather than deleting it.

3. Injectable chmod for testability: open() now delegates to
   pub(crate) open_with(data_dir, chmod_fn). Two new regression tests
   inject a failing chmod_fn:
     - fresh_file_chmod_failure_removes_file: cleanup deletes the
       partial file when no prior data exists.
     - pre_existing_file_chmod_failure_preserves_file: cleanup preserves
       the file and the prior voucher state survives a re-open with a
       healthy chmod.

4. New StoreError::PermissionTighten { path, source } variant
   distinguishes "operator must chmod" from transient Io for log
   triage — separate recovery actions deserve separate types.

5. Log severity: chmod-failure branches now use tracing::error! (was
   warn!) with a stable event= field and the observed file mode in the
   message, so an operator chasing a sticky chmod fault can see what
   they need to chmod to without re-stating the file themselves.

6. Bounded forward-compat trailer: when postcard::take_from_bytes
   leaves more than SANE_TRAILER_MAX_BYTES (256) of unconsumed bytes,
   log a warn with channel_id + remainder length. Forward-compat for
   additive fields is preserved; malicious unbounded padding is
   observable.

7. Doc honesty: the take_from_bytes comment no longer claims the
   schema_version check "gates whether to reject the record entirely"
   — intra-record bit-flips on fixed-shape fields are NOT caught at
   this layer; redb's page checksum is the real defense one layer
   down. Comment now says so.

8. Minor nits: # Errors block now lists Backend twice (data_dir
   security vs Database::create) with different recovery actions;
   "typically already 0o600" replaced with the honest "usually but
   not verified here"; the drop(db) before remove_file now has a
   comment about Windows mandatory file locking; the non-Unix
   tighten_permissions emits a one-shot debug! log so the no-op is
   auditable on a future Windows target.

Tests: 12/12 channel_store unit (+2 new injection tests, +1 new
idempotent-chmod test); 804/804 workspace; clippy/fmt/deny clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@thiras
thiras requested a review from alpergundogdu May 14, 2026 23:21
@alpergundogdu
alpergundogdu merged commit 6fa4e84 into main May 15, 2026
12 checks passed
@alpergundogdu
alpergundogdu deleted the fix-527-voucher-replay-persistence branch May 15, 2026 11:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

3 participants