Repository navigation
fix(incentive): persist voucher state across restart (#527) - #567
Conversation
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]>
Coverage reportTotal: 88.93% (was 89.00%, ▼ 0.07%) — 14329/16112 lines
History
|
There was a problem hiding this comment.
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+StoreErrorseam (with an in-memory test impl) and require a store inChannelState::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.
There was a problem hiding this comment.
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.
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]>
Summary
ChannelStateheldlast_noncein memory only; after a restart, a client could resubmit a previously-accepted voucher and the node would deliver bytes a second time.ChannelStateStoreseam incrates/incentive(trait + in-memory impl for tests) and a redb-backedPersistentChannelStateStoreincrates/nodeunder<data_dir>/channels.redb.apply_vouchernow validates → builds candidate →store.record(&next)?(fsynced) → only onOkadvances in-memory state, makingOk(())the protocol-level commit point.Off-chain voucher state persistencesubsection pinning the ordering invariant; the persistence rule is now SoT-level, with backend choice deferred to implementation. Bug was latent (nocdn/client/v1handler exists yet — that's Implement cdn/client/v1 paid delivery protocol (StreamRequest, StreamResponse, ChunkData, vouchers) #317); aTODO(#317)on the router builder spells out the four-step checklist the future handler must follow.Notable defensive choices
Durability::Immediateis set explicitly on every commit so a future redb default change cannot silently weaken the guarantee.openrejects zero-length files (redb otherwise treats them as "create a fresh DB" — a truncate-to-0 would silently reopen the replay window).tighten_permissionsremoves 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::Storecarries 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 --workspacecargo clippy --workspace --all-targets -- -D warningscargo fmt --checkcargo 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 runon touched filesCanonical regression test:
replay_after_restart_is_rejectedincrates/node/tests/channel_state_store.rs. Strict-durability invariant:store_failure_leaves_in_memory_state_unchangedincrates/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::CommitFsyncdistinguishing fsync failures from other backend errors.🤖 Generated with Claude Code