Repository navigation
feat(node): per-blob download receipt log (#248) - #790
Conversation
Add an append-only, structured download-receipt log so a node has a
durable off-chain record of every served-and-paid blob — enabling revenue
audit, cross-restart double-spend triage, and dispute evidence without
relying solely on on-chain state.
New `crates/node/src/receipt_log.rs`:
- `DownloadReceipt { hash, size, client_node_id, voucher_nonce, timestamp }`
(hash + node id as lower-hex, nonce as decimal uint256 string).
- `ReceiptLog` trait (mockable, mirrors the ChannelStateStore seam) with a
JSON-Lines `JsonlReceiptLog` writing one record per line to
`<data_dir>/download_receipts.jsonl` (append + flush, 0o600, no per-line
fsync — the #527 replay guard is the separate fsynced channel store).
- `NoopReceiptLog` runtime fallback.
Hook: `ClientHandler::collect_voucher` appends a receipt in the
voucher-accept `Ok` arm (after the payment commits), threading `hash` and
`client_node_id` down from the stream context. A receipt-log write failure
is non-fatal — logged, never failing the stream or double-charging.
Wiring: runtime opens the log under `data_dir`; a failed open logs at
error and falls back to the no-op log (non-fatal, audit-only).
Tests: round-trip + durability-across-reopen + 0o600 unit tests; loopback
tests asserting a receipt per accepted voucher with correct fields and that
a failing receipt log does not fail delivery.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request introduces an append-only download-receipt audit log (ReceiptLog) to record served-and-paid blobs upon voucher acceptance. It adds the receipt_log module with a JSON Lines implementation (JsonlReceiptLog) and integrates it into the ClientHandler and node runtime. The feedback suggests offloading the synchronous file I/O in record_receipt to a blocking threadpool using tokio::task::spawn_blocking to prevent blocking the async executor, and replacing the custom hex-encoding function with the existing alloy::primitives::hex::encode utility.
Important
The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.
There was a problem hiding this comment.
Pull request overview
This PR adds a durable, append-only “download receipt” audit log to the node so operators can later verify which paid blob deliveries occurred (including blob hash, client node id, voucher nonce, interval byte count, and acceptance timestamp), independent of on-chain state.
Changes:
- Introduces
ReceiptLog+JsonlReceiptLog(JSONL file under<data_dir>/download_receipts.jsonl) andDownloadReceiptencoding helpers. - Wires the receipt log into the runtime and records one receipt per accepted voucher interval in the client delivery handler (non-fatal on write failures).
- Adds loopback/integration test coverage for receipt emission and for “receipt log write failure does not break delivery”.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| crates/node/src/receipt_log.rs | New receipt-log module (trait + JSONL implementation + unit tests). |
| crates/node/src/runtime/mod.rs | Opens the receipt log at startup (best-effort) and wires it into ClientHandler. |
| crates/node/src/handlers/client.rs | Records a receipt after successful voucher acceptance (non-fatal if append fails). |
| crates/node/src/lib.rs | Exposes the new receipt_log module. |
| crates/node/tests/support/mod.rs | Adds in-memory ReceiptLog fakes for tests and threads receipt log into handler builder. |
| crates/node/tests/client_loopback.rs | Adds loopback tests asserting receipts are appended and write failures don’t fail delivery. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Coverage reportTotal: 86.59% (was 86.58%, ▲ +0.01%) — 26188/30243 lines
History
|
… + typed constructor (#790 review) A multi-agent review of #790 flagged invariant-enforcement gaps on the DownloadReceipt type (correctness/silent-failure dimensions were clean). Apply the minimal "Option A" hardening; the JSONL wire format is unchanged. - Make fields private with read-only accessors (hash/size/client_node_id/ voucher_nonce/timestamp_secs). Field-wise construction and out-of-crate serde-bypass can no longer defeat the validating constructor; a compile_fail doctest locks this. - new() now takes &iroh_blobs::Hash (distinct from the [u8;32] node id) so the two 32-byte identifiers cannot be transposed silently, and a U256 nonce it renders to the decimal-uint256 string internally — the "decimal uint256" invariant is now type-owned, not caller-owned. - Rename the Rust field to timestamp_secs for unit clarity; the on-disk JSON key stays `timestamp` via #[serde(rename)]. A wire-stability test asserts the serialized line is byte-identical to the original for a known input. - record_receipt passes the typed Hash/U256 and adds client_node_id + voucher_nonce to the download_receipt_write_failed warn line. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…shot (#790 review) Address PR #790 bot review on the download-receipt log: - receipt_log: replace the hand-rolled `{:02x}` hex loop with `alloy::primitives::hex::encode` (already pulled in via the `alloy` dep). Byte-identical lowercase, no-`0x` output; locked by the existing `serialized_line_is_wire_stable` wire test, so the JSONL format is unchanged. - tests/support: `VecReceiptLog::snapshot` now recovers the inner Vec on a poisoned mutex via `PoisonError::into_inner()` instead of `unwrap_or_default()`, so a failing assertion sees the receipts that were actually collected rather than a misleading empty list (anti-panic policy rules out unwrap/expect). - handlers/client: keep `record_receipt` inline (no `spawn_blocking`) and document why — the append is a no-fsync single write bounded to ~one per voucher interval; a fire-and-forget offload would drop the audit tail on shutdown and reorder receipts vs acceptance, while awaiting one only moves (not removes) the same write and adds a task hop. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…erde error map (#790 review) Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alpergundogdu
left a comment
There was a problem hiding this comment.
Review — per-blob download-receipt log
Solid and well-tested; no blocking issues. The durability story is the right one and clearly documented: the receipt log is an audit artifact written after apply_voucher commits to the fsynced channel store (the #527 replay guard), so a non-fsynced receipt tail lost to a crash can't reopen a replay window — at worst the audit log trails by a few entries. The non-fatal failure handling (warn + swallow, never failing the stream or double-charging) is correct and proven by receipt_log_write_failure_does_not_fail_delivery.
Good craftsmanship:
- The
DownloadReceipthardening (private fields + read-only accessors +compile_faildoctest, transposition-proofnew(&Hash, ..., &[u8;32])so content-hash and node-id can't be swapped, type-owned decimal-uint256rendering) is the right amount — and theserialized_line_is_wire_stabletest locks the JSONL wire format byte-for-byte against the refactor and the#[serde(rename = "timestamp")]. 0o600with idempotent re-tighten (skip-when-already-correct so a read-only mount doesn't brick startup),O_APPENDunder aMutex<File>so concurrent streams can't interleave partial lines, serialize-then-write so a serialization error never writes a partial record.- Anti-panic clean; runtime falls back to
NoopReceiptLogwith oneerror!rather than refusing to start.
One consideration (not blocking, and you do acknowledge it): record_receipt is awaited on the delivery hot path — a spawn_blocking hop + buffered write + flush per accepted voucher interval (~1 MiB). Awaiting is deliberate (preserves receipt-vs-ack ordering and avoids dropping the tail on shutdown), and at testnet scale the cost is negligible, but it does serialize each interval's VoucherAck behind a disk write. If receipt throughput ever becomes a concern, a bounded async channel to a dedicated writer task would decouple it while keeping ordering. Fine to defer.
LGTM.
Generated by Claude Code
Closes #248
Summary
Nodes had no durable record of which blobs they served and got paid for. This adds an append-only, structured download-receipt log so an operator can audit revenue, triage cross-restart double-spend, and produce dispute evidence without relying solely on on-chain state.
crates/node/src/receipt_log.rs:DownloadReceipt { hash, size, client_node_id, voucher_nonce, timestamp }—hash+client_node_idas lower-hex (raw 32 bytes),voucher_nonceas a decimaluint256string,size= bytes covered by the voucher interval,timestamp= Unix seconds at acceptance.ReceiptLogtrait (mockable, mirroring theChannelStateStoretrait+impl seam) with a JSON-LinesJsonlReceiptLogwriting one record per line to<data_dir>/download_receipts.jsonl. Append + flush, file mode0o600. No per-line fsync — the incentive: no replay-protection window enforced on incoming voucher nonces, allowing a client to resubmit a previously accepted voucher after a node restart and receive a second byte-delivery for the same payment #527 voucher-replay guard is the separate, fsynced channel store; the receipt log is an audit artifact and the payment is committed there before a receipt is written.NoopReceiptLogis the runtime fallback.crates/node/src/handlers/client.rs):collect_voucherappends a receipt in the voucher-acceptOkarm via a smallrecord_receipthelper, threadinghashandclient_node_iddown from the stream context. A receipt-log write failure is non-fatal — logged atwarn!with a structuredeventkey, never failing the stream or double-charging.crates/node/src/runtime/mod.rs): opens the log underdata_diron the blocking pool; a failed open logs aterror!and falls back to the no-op log (non-fatal — paid delivery is unaffected).Review
Dispatched a multi-lens review (code-reviewer, silent-failure-hunter, pr-test-analyzer, type-design-analyzer, comment-analyzer) on the uncommitted diff.
FailingReceiptLog+receipt_log_write_failure_does_not_fail_delivery, which proves delivery completes and the channel state still advances despite an always-erroring log.eventkeys, comments verified against behavior.Type-design follow-up (commit
0118b2e)A second multi-agent review re-examined
DownloadReceiptand found that, despite the validatingnew(), the type's invariants were not actually enforced —pubfields + derivedDeserializelet an invalid receipt be built field-wise or viafrom_str, two indistinguishable&[u8;32]args could be transposed silently, and the decimal-uint256nonce was rendered by the caller. Resolved with the minimal "Option A" hardening (heavier "separate validated type + DTO +TryFrom" Option B was explicitly declined as over-engineering). The JSONL wire format is unchanged — a new wire-stability test asserts the serialized line is byte-identical to the original for a known input.hash(),size(),client_node_id(),voucher_nonce(),timestamp_secs()): field-wise construction and out-of-crate serde-bypass can no longer defeat the constructor. Acompile_faildoctest locks this.new()now takes&iroh_blobs::Hash(the call site already holds it) instead of a second bare&[u8;32], so the content hash and node id are distinct types and a swap won't compile.new()takes aU256and renders the decimal string internally;record_receiptpasses the typed value instead of a pre-rendered string.timestamp_secs; the on-disk JSON key staystimestampvia#[serde(rename = "timestamp")].client_node_id+voucher_nonceadded to thedownload_receipt_write_failedwarn line so a dropped audit entry is individually identifiable. Thevschema-version field was skipped (declined — would change the locked wire format for no current consumer).Tests
cargo build,cargo clippy --workspace --all-targets -- -D warnings,cargo fmt -- --check,cargo nextest run -p decdn-node(403 tests), and thecompile_faildoctest all green.0o600mode, and a wire-stability test (serialized line byte-identical to the original schema).compile_fail): field-wiseDownloadReceipt { .. }construction no longer compiles outside the crate.🤖 Generated with Claude Code