1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
//! Append-only download-receipt log for the node runtime (issue #248).
//!
//! A node enqueues one structured [`DownloadReceipt`] per served-and-paid blob
//! at the voucher-acceptance point (see
//! [`crate::handlers::client::ClientHandler`]); the disk write happens off the
//! delivery path in a background writer (see the Seam note below, #803). The
//! log gives the operator an on-disk, off-chain record of which blobs were
//! delivered and paid for — enabling revenue audit, cross-restart double-spend
//! triage, and dispute evidence without relying solely on on-chain state.
//!
//! # Seam
//!
//! There are two layers. [`ReceiptLog`] is the *disk* boundary — a small trait
//! (mirroring the trait+impl pattern of
//! [`decdn_incentive::store::PoolStateStore`] / [`crate::pool_store`])
//! whose runtime impl is the disk-backed [`JsonlReceiptLog`], appending one JSON
//! object per line to `<data_dir>/download_receipts.jsonl` (JSON Lines).
//! [`ReceiptSink`] is the *hot-path* boundary: the paid-delivery path does not
//! call [`ReceiptLog::append`] directly — it enqueues through the non-blocking
//! [`ReceiptSink::record`], and a single background [`spawn_receipt_writer`]
//! task owns the `JsonlReceiptLog` and performs the actual `append` off the
//! delivery path (#803), so a slow or full disk can never back-pressure
//! delivery. Both seams take an in-memory fake in unit/loopback tests.
//!
//! # Durability
//!
//! Each [`ReceiptLog::append`] writes one line straight to the file — one
//! `write_all`, which lands the bytes in the OS page cache — and does **not**
//! fsync per record. The receipt log is an *audit* artifact, not the
//! voucher-replay guard. That guard is the lane watermark in
//! [`crate::pool_store::PersistentPoolStateStore`], which
//! advances **in memory** the moment a voucher or preimage is accepted, reaches
//! disk on the runtime's periodic lane flush
//! (`payment.voucher_commit_interval_ms`, 5 s by default), and is flushed again
//! before every on-chain redemption.
//!
//! Neither side fsyncs on the delivery path, so after a crash the two tails
//! **can** disagree, in either direction, and neither direction is guaranteed.
//! The audit log runs ahead when the background writer has already written a
//! line whose lane advance is still buffered — a restart then finds a receipt
//! whose watermark the lane store no longer holds. It runs behind when the
//! crash catches receipts still queued in [`RECEIPT_LOG_CAPACITY`] (that queue
//! is process memory and dies with the process, and only a graceful shutdown
//! drains it), or when a hard crash drops page-cache lines the 5 s lane flush
//! had already fsynced past.
//!
//! Both directions are safe. Ahead costs revenue, not correctness: the node
//! forfeits at most one flush interval of *frontier* (value it has not yet
//! redeemed), which ADR 003 §Off-chain voucher state persistence accepts.
//! Behind is a gap in the audit record and nothing more.
//!
//! Replay protection rests on the *redeemed* watermark instead, which the
//! pre-redemption flush floors. That floor holds wherever the node can afford
//! to wait for it: the periodic sweep and the redeem-hint path skip their
//! submit when the flush fails, while the shutdown sweep redeems anyway,
//! because forfeiting the claim across the stop is worse than a bounded
//! re-serve risk (see [`crate::payment_settlement`]). Skipping the
//! per-line fsync keeps the cost off the hot delivery path (ADR 003).
//!
//! The append is also crash-atomic at the line level only in the usual POSIX
//! sense (a torn final line is possible after a hard crash); JSONL readers MUST
//! tolerate a truncated trailing line.
//!
//! # Rotation (issue #802)
//!
//! Left unbounded the log grows for the entire process lifetime and across
//! restarts (`O_APPEND`), eventually exhausting `data_dir`. [`JsonlReceiptLog`]
//! therefore takes a [`RotationPolicy`] (`max_file_bytes`, `retained_files`):
//! once the live file would exceed `max_file_bytes` it is rotated to a numbered
//! backup (`download_receipts.jsonl.1`, `.2`, …, oldest = highest), a fresh
//! live file is opened, and any backup beyond `retained_files` is deleted. This
//! bounds `data_dir` to roughly `(retained_files + 1) * max_file_bytes`.
//! `retained_files == 0` keeps no backups — the live file is truncated in place
//! on rotation. Rotation is **best-effort**: a rename/open failure mid-rotation
//! never leaves the log without a writable handle and never aborts paid
//! delivery (the background writer treats an `append` error as non-fatal, and
//! delivery is decoupled from it by the bounded queue, #803), it only trims or
//! skips a backup that cycle.
use ;
use Write;
use ;
use ;
use U256;
use Hash;
use ;
use mpsc;
use CancellationToken;
use crateMetrics;
use crateStopHandle;
/// File name of the receipt log within `data_dir`. Canonical name lives in
/// `decdn_common` so the daemon writer and the `config validate` summary can't
/// disagree on where receipts land (#964).
const RECEIPT_LOG_FILE: &str = RECEIPT_LOG_FILE;
/// On-disk file mode (`0o600` — owner-only read+write). Same defense-in-depth
/// rationale as [`crate::pool_store`]: `data_dir` is already `0o700`, but the
/// receipt log can carry per-client delivery metadata, so the file mode is
/// tightened independently in case the directory ACL is widened out-of-band.
const RECEIPT_LOG_FILE_MODE: u32 = 0o600;
/// One durable record of a served-and-paid blob (issue #248).
///
/// The on-disk shape. The paid-delivery path captures a [`RawReceipt`] at the
/// voucher-acceptance point and the background writer renders it into this
/// value (`RawReceipt::render`, #1792 item 2), so every receipt still
/// corresponds to a cumulative payment the node verified and committed — the
/// rendering just happens off the hot path. All identifier fields are lower-hex
/// strings (no `0x` prefix) so the log is self-describing and greppable without
/// a schema:
///
/// - `hash` — BLAKE3 content hash of the delivered blob (raw 32 bytes, hex).
/// - `client_node_id` — iroh `NodeId` (ed25519 public key) of the paying peer
/// (raw 32 bytes, hex).
/// - `voucher_amount` — the accepted voucher's cumulative amount (its sole
/// ordering key; there is no nonce), as a decimal string. A decimal `uint256`
/// (not hex) so an auditor reads the same value the on-chain `PaymentPool` and
/// operator dashboards show; it is reconstructed from the 32-byte big-endian
/// wire amount.
///
/// `size` is the byte count covered by *this* payment proof (the newly
/// delivered, now-paid bytes), and `timestamp_secs` is the node's wall-clock
/// Unix time (seconds) read where the receipt is rendered — the background
/// writer stamps it as it dequeues, which lags the acceptance point only by the
/// queue-drain latency (#1792 item 2).
///
/// # Invariants
///
/// The fields are **private** and the only public constructor is [`new`], which
/// renders the hex and decimal-`uint256` strings from typed inputs. This makes
/// the invariants type-owned: a receipt cannot be built field-wise, and serde's
/// derived `Deserialize` cannot synthesize one with a malformed `hash` /
/// `client_node_id` / `voucher_amount` from outside the crate (the fields stay
/// private to readers). Accessor methods expose the rendered values read-only.
///
/// Field-wise construction from outside the crate does not compile (the fields
/// are private), so the validating [`new`] is the only public path in:
///
/// ```compile_fail
/// use decdn_node::receipt_log::DownloadReceipt;
/// // ERROR: fields `hash`, `size`, ... are private — invariant cannot be bypassed.
/// let _ = DownloadReceipt {
/// hash: "not-a-hash".to_string(),
/// size: 1,
/// client_node_id: "nope".to_string(),
/// voucher_amount: "0xdeadbeef".to_string(),
/// timestamp: 0,
/// };
/// ```
///
/// [`new`]: DownloadReceipt::new
/// One receipt as the paid-delivery hot path produces it: raw typed
/// identifiers, no rendering and no clock read.
///
/// This is what [`ReceiptSink::record`] takes and what rides the writer queue,
/// so enqueuing a receipt on the delivery path is a handful of `Copy` field
/// moves — no hex encoding, no `U256` decimal formatting, and no
/// `SystemTime::now()` (issue #1792 item 2). The background writer
/// ([`spawn_receipt_writer`]) turns it into the on-disk [`DownloadReceipt`] via
/// `RawReceipt::render`, which is where the two 64-char hex renders, the
/// decimal-`uint256` render, and the acceptance timestamp are applied — off the
/// hot path, in the same task that already owns the disk write (#803).
/// Lower-hex encode a 32-byte array without a `0x` prefix. Delegates to
/// `alloy::primitives::hex::encode` (the `const-hex` re-export already pulled in
/// via the `alloy` dependency), which emits lowercase with no `0x` prefix —
/// byte-identical to the prior hand-rolled `{:02x}` loop, and locked against
/// drift by the `serialized_line_is_wire_stable` test.
/// Append-only sink for [`DownloadReceipt`]s.
///
/// The trait exists so the voucher-accept path can be exercised against an
/// in-memory fake in unit tests; the runtime uses [`JsonlReceiptLog`].
/// Implementations MUST be cheap enough to call inline on the delivery path
/// (one buffered line write + flush — no fsync; see the module durability note).
/// Size-based rotation policy for [`JsonlReceiptLog`] (issue #802).
///
/// `max_file_bytes` is the size at which the live file is rotated;
/// `retained_files` is how many numbered backups (`.1`..=`.N`) to keep (`0`
/// truncates the live file in place instead of keeping backups). A
/// `max_file_bytes` of `0` disables rotation entirely (the live file grows
/// unbounded) — a degenerate value the engine accepts but production never
/// produces.
///
/// The engine deliberately accepts any values (the rotation guards in
/// [`JsonlReceiptLog::append`] cope with a sub-line cap, and tests use tiny
/// caps to exercise rotation deterministically). Production policies are built
/// *only* from a [`decdn_common::config::ResolvedReceipts`] via the [`From`]
/// impl below, and that config type is range-validated by
/// `decdn_common::config::resolve_config` — so every live policy is within the
/// operator-facing safe bounds (`[MIN_RECEIPT_MAX_FILE_BYTES,
/// MAX_RECEIPT_MAX_FILE_BYTES]`, `retained_files <= MAX_RECEIPT_RETAINED_FILES`).
/// Mutex-guarded writer state: the live append handle plus the in-memory byte
/// count used to decide rotation without an extra `stat` per append.
/// JSON-Lines, append-only [`ReceiptLog`] backed by a single rotating file
/// under `data_dir`.
///
/// One [`File`] handle is held open for the process lifetime behind a [`Mutex`]
/// so concurrent delivery streams cannot interleave partial lines. The handle
/// is opened in append mode (`O_APPEND`), so even across the (already
/// serialized) writes each `write_all` lands at the current end of file.
/// Rotation (issue #802) swaps that handle under the same lock; see the
/// module-level rotation note.
/// Open (or create) an append-mode handle at `path`, applying the `0o600` mode
/// on Unix and tightening an existing file's mode. Shared by `open` and the
/// post-rotation reopen so both honour the same permissions invariant.
/// Tighten the on-disk file mode to `0o600`. Idempotent: skips the syscall when
/// the mode already matches so a read-only mount with the correct mode (e.g.
/// from a prior boot) does not fail startup. Mirrors
/// [`crate::pool_store::PersistentPoolStateStore`]'s tightening.
/// A [`ReceiptLog`] that drops every receipt. Used as the runtime fallback when
/// [`JsonlReceiptLog::open`] fails at bring-up: the audit log is best-effort, so
/// the node serves paid delivery without it rather than refusing to start (the
/// replay guard lives in the separate lane store, which the periodic flush
/// mirrors to disk). The operator gets one `error!` at startup naming the open
/// failure.
;
/// Non-blocking enqueue boundary for [`RawReceipt`]s on the paid-delivery
/// hot path (#803).
///
/// The voucher-accept path records a receipt through this seam as each voucher
/// is accepted (acceptance is implicit — delivery simply continues), so the
/// implementation MUST NOT block on disk I/O: a backed-up sink drops the
/// receipt (best-effort, audit-only) rather than stall the payment, which
/// already advanced the lane watermark. The runtime uses [`ChannelReceiptSink`]
/// (hands off to the background [`spawn_receipt_writer`] task); tests use a
/// synchronous fake behind the `test-support` `DirectReceiptSink`.
///
/// The seam carries a [`RawReceipt`], not the rendered [`DownloadReceipt`]: the
/// hex/decimal rendering and the timestamp are applied downstream, off the hot
/// path (#1792 item 2).
/// Capacity of the receipt-writer queue. Receipts are roughly one per voucher
/// interval (~1 MiB served), so this absorbs a large burst of voucher
/// acceptances while a disk stall (a slow or full `data_dir`, the realistic
/// end-state of #802) is worked off, without ever back-pressuring paid
/// delivery. On overflow the *audit* receipt is dropped (counted via
/// [`Metrics::receipt_write_dropped`]) rather than the *payment* stalling — the
/// payment already advanced the lane watermark. Rotation (#802) bounds the log
/// on disk; this bounds it in memory.
pub const RECEIPT_LOG_CAPACITY: usize = 1024;
/// Production [`ReceiptSink`]: enqueues to the background writer over a bounded
/// channel. Mirrors the redeem-hint sink (#751): a `Full` channel drops the
/// receipt and counts it (`decdn_receipt_writes_dropped_total`); a `Closed`
/// channel — the writer stopped during shutdown — is silently ignored (the tail
/// drain has already run, or is bounded by the shutdown deadline).
/// Synchronous [`ReceiptSink`] that appends inline to a [`ReceiptLog`],
/// swallowing the write error. Test/loopback support only: lets the unit and
/// `client_loopback` tests keep a deterministic in-memory [`ReceiptLog`] fake
/// behind the sink seam the handler depends on, without standing up the
/// background writer or polling for an async drain. Production never uses it —
/// the runtime always routes through [`spawn_receipt_writer`] so disk I/O cannot
/// block paid delivery.
///
/// It deliberately *violates* the [`ReceiptSink`] non-blocking contract (it
/// appends inline on the caller's thread), so it must never be wired onto the
/// paid-delivery path. The `test-support` feature gate keeps it out of every
/// production build: it compiles only for this crate's own tests and for the
/// cross-crate integration tests in `tests/`, which cannot see `#[cfg(test)]`
/// items. The field is private and the type is `#[doc(hidden)]` so it does not
/// read as a production knob.
;
/// Spawn the single background task that owns the on-disk [`ReceiptLog`] and
/// drains the receipt queue, returning the [`ReceiptSink`] the delivery path
/// enqueues through plus the [`StopHandle`] that stops the task at graceful
/// shutdown.
///
/// Decouples the audit write from the paid-delivery hot path (#803): the
/// voucher-accept path does only a non-blocking [`ReceiptSink::record`] (a
/// bounded `try_send`) as each voucher is accepted, while this task performs
/// the actual `append` on the blocking pool. A slow or full disk can only fill
/// the queue (and drop audit records, counted) — it can never delay delivery
/// or serialize delivery on the receipt-log mutex. The writer is the *only*
/// caller of [`ReceiptLog::append`], so the log's internal mutex sees no
/// cross-stream contention.
///
/// On its stop signal ([`StopHandle::cancel`], fired after the router has
/// drained, so no further receipts are produced) the task flushes whatever is
/// already enqueued and exits; complete [`StopHandle::shutdown`] within the
/// shutdown deadline to preserve the audit tail. The `StopHandle` owns the stop
/// token beside the task handle, so the join cannot hang on sinks that outlive
/// shutdown — [`crate::handlers::client::ClientHandler`] holds one for the
/// whole runtime.
/// Drain loop for the background receipt writer (see [`spawn_receipt_writer`]).
/// Appends each receipt FIFO until the queue closes or `shutdown` fires, then
/// flushes the already-enqueued tail before returning.
async
/// Render one raw receipt and append it on the blocking pool, logging a
/// non-fatal failure.
///
/// The delivery task only enqueued a [`RawReceipt`]; the hex/decimal rendering
/// happens here (#1792 item 2), off the paid-delivery path. The timestamp is
/// read at dequeue — so it lags the acceptance point only by the queue-drain
/// latency and stays in FIFO order — while the render itself runs *inside* the
/// [`tokio::task::spawn_blocking`] closure, so no formatting or allocation
/// touches a runtime worker thread either.
///
/// The blocking pool is also where the synchronous `write_all`/`flush` (and any
/// disk stall under a full or slow `data_dir`) runs, never on a runtime worker.
/// The single writer awaits each append before the next, preserving receipt
/// order. An append error is non-fatal — the payment already advanced the lane
/// watermark — so it is logged at `warn`, counted into
/// `decdn_receipt_write_failures_total`, and the loop continues.
async