Skip to content

feat(node): per-blob download receipt log (#248) - #790

Merged
thiras merged 4 commits into
mainfrom
feat/248-download-receipt-log
Jun 3, 2026
Merged

thiras merged 4 commits into
mainfrom
feat/248-download-receipt-log

Conversation

@thiras

@thiras thiras commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

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.

  • New crates/node/src/receipt_log.rs:
  • Hook (crates/node/src/handlers/client.rs): collect_voucher appends a receipt in the voucher-accept Ok arm via a small record_receipt helper, threading hash and client_node_id down from the stream context. A receipt-log write failure is non-fatal — logged at warn! with a structured event key, never failing the stream or double-charging.
  • Wiring (crates/node/src/runtime/mod.rs): opens the log under data_dir on the blocking pool; a failed open logs at error! 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.

  • pr-test-analyzer (addressed): the "receipt-log write failure is non-fatal" guarantee was untested. Added FailingReceiptLog + receipt_log_write_failure_does_not_fail_delivery, which proves delivery completes and the channel state still advances despite an always-erroring log.
  • code-reviewer / silent-failure-hunter / comment-analyzer (clean): anti-panic compliant (no unwrap/expect/panic/indexing), both failure paths logged with structured event keys, comments verified against behavior.

Type-design follow-up (commit 0118b2e)

A second multi-agent review re-examined DownloadReceipt and found that, despite the validating new(), the type's invariants were not actually enforced — pub fields + derived Deserialize let an invalid receipt be built field-wise or via from_str, two indistinguishable &[u8;32] args could be transposed silently, and the decimal-uint256 nonce 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.

  • Private fields + 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 constructor. A compile_fail doctest locks this.
  • Transposition-proof constructor: 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.
  • Nonce invariant is type-owned: new() takes a U256 and renders the decimal string internally; record_receipt passes the typed value instead of a pre-rendered string.
  • Timestamp unit: Rust field renamed to timestamp_secs; the on-disk JSON key stays timestamp via #[serde(rename = "timestamp")].
  • Audit-line identifiability (optional, applied): client_node_id + voucher_nonce added to the download_receipt_write_failed warn line so a dropped audit entry is individually identifiable. The v schema-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 the compile_fail doctest all green.

  • Unit: field rendering via accessors, append→read round-trip, durability across reopen, 0o600 mode, and a wire-stability test (serialized line byte-identical to the original schema).
  • Doctest (compile_fail): field-wise DownloadReceipt { .. } construction no longer compiles outside the crate.
  • Loopback: a receipt per accepted voucher with correct hash/node-id/nonce/size (read via accessors); failing log does not fail delivery.

🤖 Generated with Claude Code

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]>
Copilot AI review requested due to automatic review settings June 2, 2026 19:24

@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 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.

Comment thread crates/node/src/handlers/client.rs Resolved
Comment thread crates/node/src/receipt_log.rs Resolved

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 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) and DownloadReceipt encoding 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.

Comment thread crates/node/src/receipt_log.rs Resolved
Comment thread crates/node/tests/support/mod.rs Resolved
@github-actions

github-actions Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Coverage report

Total: 86.59% (was 86.58%, ▲ +0.01%) — 26188/30243 lines

File Coverage Lines Δ
crates/node/src/handlers/client.rs 76.87% 452/588 ▲ +2.01%
crates/node/src/receipt_log.rs 94.77% 145/153 new
crates/node/src/runtime/mod.rs 45.25% 515/1138 ▼ 0.60%
History
Commit Total Δ vs base
061325f 86.58% ▲ +0.01%
0118b2e 86.60% ▲ +0.02%
c4bc150 86.60% ▲ +0.02%
a86e0ce (HEAD) 86.59% ▲ +0.01%

thiras and others added 3 commits June 3, 2026 01:55
… + 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 alpergundogdu left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 DownloadReceipt hardening (private fields + read-only accessors + compile_fail doctest, transposition-proof new(&Hash, ..., &[u8;32]) so content-hash and node-id can't be swapped, type-owned decimal-uint256 rendering) is the right amount — and the serialized_line_is_wire_stable test locks the JSONL wire format byte-for-byte against the refactor and the #[serde(rename = "timestamp")].
  • 0o600 with idempotent re-tighten (skip-when-already-correct so a read-only mount doesn't brick startup), O_APPEND under a Mutex<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 NoopReceiptLog with one error! 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

@thiras
thiras merged commit 303acc6 into main Jun 3, 2026
19 checks passed
@thiras
thiras deleted the feat/248-download-receipt-log branch June 3, 2026 13:40
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.

Implement a per-blob download receipt log that records hash, size, client node ID, and payment voucher nonce to a structured file in data_dir

3 participants