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
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
//! Wire message payload types for the `cdn/client/v1` paid-delivery protocol.
//!
//! `cdn/client/v1` is the paid byte-transfer path (ADR 005 §`cdn/client/v1`):
//! a payer opens a bidirectional QUIC stream, sends a [`StreamRequest`], and
//! the delivering node answers with a [`StreamResponse`] followed by a loop of
//! [`ChunkData`] interleaved with cumulative payment [`Voucher`]s, terminating
//! in [`ClientMessage::StreamEnd`]. Acceptance of a voucher is implicit —
//! delivery simply continues; only rejection is signalled, via
//! [`ClientMessage::StreamError`]. A delivery or payment fault is signalled by
//! [`StreamError`].
//!
//! Like [`crate::message`] this is a leaf crate with **no crypto dependency**.
//! The two signed artifacts on this protocol are produced/verified by
//! `decdn_incentive`:
//! - `StreamResponse.slash_sig` — an EIP-712 secp256k1 signature over the
//! signed body fields `{hash, ok, rate_per_mb, total_bytes, pool_id,
//! timestamp_us}` (ADR 014 §1), produced by the stream-response slash
//! signer in `decdn_incentive` (analogous to its `ProbeSlashData`).
//! `error` is unsigned.
//! - `Voucher.signature` — an EIP-712 secp256k1 voucher signature; the wire
//! carries `{signature, amount}` and the receiver reconstructs the full typed
//! data `{poolId, signer, provider, amount, bytesDelivered}` from stream
//! context (ADR 005 §Voucher wire format, `decdn_incentive::Voucher`).
//!
//! # Signed-field freezing (ADR 013 §Signed Field Freezing)
//!
//! The signed set on [`StreamResponseBody`] is the `cdn/client/v1` v1 baseline.
//! Any change to it is a Tier-3 ALPN bump. New unsigned fields go on
//! [`StreamResponse`] as optional fields, following the `total_bytes` exemplar
//! on [`crate::message::ProbeResponse`].
//!
//! # Variant order
//!
//! [`ClientMessage`], [`StreamError`], and [`VoucherRejectReason`] all have
//! **frozen** variant order — postcard encodes each variant as its
//! declaration-order index. Reordering is a wire-breaking change; the
//! `*_discriminant_is_*` / `*_variant_order` tests lock the assignments.
use ;
use crate;
/// One megabyte in bytes (ADR 003: 1 MB = 1,048,576 bytes, exactly). The unit
/// of `rate_per_mb` and, by the identity below, of [`CHUNK_BYTES`].
pub const MB_BYTES: u64 = 1_048_576;
/// The payment quantum: one chunk of delivery, 1 MiB (ADR 003 §Chunk Cadence).
///
/// A protocol constant, never negotiated. No message carries it, no node
/// advertises it, and governance does not move it — a chunk is the unit one
/// hash-chain tick pays for, so payer and node disagreeing on it would make one
/// released preimage worth two different amounts.
///
/// `CHUNK_BYTES == MB_BYTES` by identity, which is what makes a chunk cost
/// exactly the advertised `rate_per_mb` with no rounding at any rate.
pub const CHUNK_BYTES: u64 = MB_BYTES;
/// The highest chain index: the hash chain's incremental range over its anchor
/// (ADR 003 §Chain length and rollover).
///
/// The index space is the `u8` domain `0..=255` — 256 slots, exactly one byte.
/// Index 0 names `chain_root` and resolves to the voucher's own `amount`, so
/// the base voucher is payable with no chain at all; it adds no increment,
/// which is why it never travels the wire. Indices `1..=255` each release one
/// preimage and add one `chunk_price` over that anchor, so a chain adds up to
/// 255 MiB at [`CHUNK_BYTES`]. 256 slots = one payable base + 255 increments.
pub const MAX_CHAIN_LENGTH: u8 = 255;
/// Exact byte length of an EOA secp256k1 voucher signature (`r‖s‖v`, 32+32+1).
/// Mirrors [`SLASH_SIG_LEN`]; both are the EOA off-chain signing form (ADR 024
/// §Off-Chain Signature Verification — EOA Recovery Only). Carried as a `Vec<u8>` on the wire (serde
/// derives array impls only up to `[T; 32]`), with the length pinned by
/// [`Voucher::validate`].
pub const VOUCHER_SIG_LEN: usize = 65;
/// Exact byte length of a `BindNodeId` client-binding signature (`r‖s‖v`,
/// 32+32+1). The same EOA off-chain EIP-712 signing form as [`SLASH_SIG_LEN`] /
/// [`VOUCHER_SIG_LEN`] (ADR 024 §Off-Chain Signature Verification — EOA Recovery Only); pinned by
/// [`ClientBinding::validate`].
pub const BINDING_SIG_LEN: usize = 65;
/// Top-level protocol enum for `cdn/client/v1`. Variant order is frozen per
/// ADR 013 — new variants MUST be appended at the end.
///
/// ⚠️ **VARIANT ORDER FROZEN — ADR 013 §Protocol Enums**
/// Postcard encodes each variant as its declaration-order index. Reordering,
/// inserting, or removing a variant is a wire-breaking change requiring an ALPN
/// version bump (`cdn/client/v2`). The discriminant assignments are locked by
/// the `client_message_*_discriminant_is_*` tests.
/// Payer → node request opening a paid delivery (ADR 005 §`cdn/client/v1`).
///
/// `timestamp_us` is a requester-generated microsecond timestamp echoed back in
/// [`StreamResponseBody::timestamp_us`]; it both correlates the response and
/// drives rate-manipulation slashing (ADR 005, ADR 014). `byte_offset` supports
/// seek/resume on failover — the requester reconnects to another node and
/// resumes from the last BLAKE3-verified byte.
///
/// This struct holds **only the frozen base fields** (ADR 013 §Tier 1). The
/// optional [`StreamRequestExt`] is carried as **separate trailing bytes** after
/// this message in the frame, parsed via [`parse_stream_request_ext`] — *not* as
/// an embedded field. This is the ADR 005 §Client identity binding two-phase
/// deserialization pattern: keeping the base frozen and parsing extension bytes
/// separately means a future field added to [`StreamRequestExt`] stays
/// backward-compatible (old senders simply emit fewer trailing bytes; new
/// optional fields are appended and old receivers skip them). Embedding `ext` as
/// a nested struct field instead would break old `Some(...)` senders the moment
/// a field is added (postcard would hit EOF inside the nested struct). Use
/// [`encode_stream_request`] to build the wire payload with an optional `ext`.
/// The reserved "no namespace" [`StreamRequest::namespace_id`] value (all-zero
/// big-endian `uint256`): content published without a namespace, served
/// best-effort from cache / DHT with no authorized origins (ADR 002 §Namespace 0).
pub const NO_NAMESPACE: = ;
/// Optional [`StreamRequest`] extension fields (ADR 005 §Client identity
/// binding), carried as trailing bytes after the `StreamRequest` message via the
/// two-phase pattern (see [`encode_stream_request`] / [`parse_stream_request_ext`]).
/// Off-chain ephemeral client identity binding (ADR 003 §Off-Chain Ephemeral
/// Binding), carried inside [`StreamRequestExt`]. The address and its attesting
/// signature are paired so neither can appear without the other.
/// A pool owner's spending capability, carried inside [`StreamRequestExt`]
/// (ADR 003 §Capability delegation). `signer` and `pool_id` are not on the
/// wire — they are derived from stream context, exactly like a [`Voucher`]'s
/// implicit fields: `signer` is the request's bound Ethereum address
/// ([`ClientBinding::ethereum_address`], or the registered on-chain signer
/// when `binding` is absent) and `pool_id` is [`StreamRequest::pool_id`].
/// Encode a `cdn/client/v1` `StreamRequest` frame payload with an optional
/// trailing [`StreamRequestExt`] (ADR 005 §Client identity binding, two-phase).
///
/// The result is the full frame payload to pass to [`crate::write_frame`]: the
/// postcard-encoded `ClientMessage::StreamRequest(req)` followed, when `ext` is
/// `Some`, by the postcard-encoded extension. The receiver recovers `req` from
/// [`crate::decode_message`] and the extension from that call's returned
/// remainder via [`parse_stream_request_ext`].
///
/// # Errors
///
/// Propagates a [`postcard::Error`] if serialization fails.
/// Parse the trailing [`StreamRequestExt`] bytes returned as the remainder by
/// [`crate::decode_message`] after a `ClientMessage::StreamRequest`.
///
/// An empty remainder ⇒ [`StreamRequestExt::default`] (no client binding, no
/// capability). Trailing bytes beyond the known fields are tolerated for
/// forward compatibility (ADR 013 §Tier 1): a future optional field appended to
/// [`StreamRequestExt`] is read by new receivers and skipped by old ones.
///
/// # Errors
///
/// Returns a [`postcard::Error`] if a non-empty remainder is not a valid
/// `StreamRequestExt` prefix.
/// Node → payer response to a [`StreamRequest`] (ADR 005 §`cdn/client/v1`).
///
/// **This struct holds only the frozen base** (ADR 013 §Tier 1): the signed
/// [`StreamResponseBody`] and the `slash_sig` covering it. Unsigned fields live
/// in [`StreamResponseExt`], which travels as separate trailing bytes — see
/// [`encode_stream_response`] / [`parse_stream_response_ext`].
///
/// `slash_sig` is mandatory and non-empty (exactly [`SLASH_SIG_LEN`] bytes);
/// requesters MUST reject missing/zero-length or zero-`rate_per_mb` responses
/// (enforced via [`StreamResponse::validate`]).
/// Optional [`StreamResponse`] extension fields, carried as trailing bytes after
/// the `StreamResponse` message via the two-phase pattern (ADR 013 §Tier 1; see
/// [`encode_stream_response`] / [`parse_stream_response_ext`]).
///
/// Nothing here is covered by `slash_sig`. New fields are appended to the END
/// and MUST be `Option<T>` or have a meaningful `Default`; insertions and
/// reordering are Tier-3.
/// Encode a [`StreamResponse`] with its optional trailing [`StreamResponseExt`]
/// (ADR 013 §Tier 1, two-phase). See [`encode_stream_request`] for why the two
/// values are encoded separately.
///
/// # Errors
///
/// Propagates a [`postcard::Error`] if serialization fails.
/// Parse the trailing [`StreamResponseExt`] bytes returned as the remainder by
/// [`crate::decode_message`] after a `ClientMessage::StreamResponse`.
///
/// An empty remainder ⇒ [`StreamResponseExt::default`] (no error code, which is
/// only valid alongside `ok == true`). Trailing bytes beyond the known fields
/// are tolerated for forward compatibility (ADR 013 §Tier 1).
///
/// # Errors
///
/// Returns a [`postcard::Error`] if a non-empty remainder is not a valid
/// `StreamResponseExt` prefix.
/// Signed fields of a [`StreamResponse`] (ADR 014 §1). Layout is frozen per
/// ADR 013 — future additions go on [`StreamResponse`] as optional unsigned
/// fields, not here.
///
/// `rate_per_mb` is bounded by [`MAX_RATE_PER_MB`] at the wire boundary via the
/// shared `deserialize_rate_per_mb` hook (#378), keeping the bound bilateral
/// with the node's config layer.
/// Node → payer chunk of blob bytes. The payload carries at least one byte; its
/// length is the sender's choice, bounded above by the framing layer's
/// [`MAX_MESSAGE_SIZE`](crate::framing::MAX_MESSAGE_SIZE); ADR 005
/// §`cdn/client/v1` additionally requires a sender not to cross a `CHUNK_BYTES`
/// payment boundary, so in practice a frame runs to at most one interval. Frames need not be uniform, and the frame before
/// [`ClientMessage::StreamEnd`] is commonly shorter than the ones before it.
///
/// Frame size is independent of both verification and payment. The bao codec is
/// the sole verifier and resolves chunk-group boundaries itself (ADR 038), and
/// the payment meter ticks on cumulative bytes crossing [`CHUNK_BYTES`] rather
/// than on frames. A sender therefore picks whatever size suits it; nothing is
/// negotiated and no message carries the choice.
///
/// The lower bound is load-bearing, not cosmetic (#1088). A shorter final frame is
/// permitted, never an *empty* one: an empty frame carries no
/// payload, so it advances neither the receiver's cumulative byte count nor its
/// voucher accounting. An unbounded run of them therefore drives the receive
/// loops without making application-level progress, and the `cumulative >
/// expected_wire` overrun guard — which only ever trips on bytes — never fires.
/// An empty frame cannot be obtained at all — [`ChunkData::new`], the `try_from` decode
/// gate, and every `encode_chunk_*` helper ([`encode_chunk_frame`],
/// [`encode_chunk_frame_headers`], and the crate-private one the latter builds on)
/// each reject one, and between them they are every route to a frame body. That is the invariant the pull
/// paths' inactivity deadline rests on: with empty frames banned, "a frame arrived" and
/// "bytes made progress" are the same statement, so a peer cannot refresh the deadline
/// with padding.
///
/// # The bounds are enforced by construction
///
/// The field is private and [`ChunkData::new`] is the only constructor, so an invalid
/// frame cannot be built — and `#[serde(try_from)]` routes decoding through the same
/// check, so it cannot be *decoded* either. A receive loop therefore holds a valid frame
/// by having one at all, and a serve path cannot emit an empty frame even by accident.
///
/// The invariant lives on the type, not in a convention, because a convention here is
/// silently skippable. Were the floor an advisory `validate()`, it would ride on every
/// receive loop remembering to call it and every emitter avoiding an empty frame — and
/// the serve side avoids one only *incidentally*, differently on each path:
///
/// each serve path cuts its byte stream into frames and emits whatever has
/// accumulated, so an empty frame is avoided only because an exhausted stream yields
/// nothing to emit. The empty blob (whose bao encoding is zero bytes — see
/// `decdn_bao_range::align_range`) reaches [`ClientMessage::StreamEnd`] the same way,
/// with no frame sent first (#1054).
///
/// That is a fact about unrelated code, and it could change without anyone noticing
/// which invariant they had just removed — while the requester's receive loop depends on it
/// (#1797): an empty frame advances neither the cumulative delivered bytes nor the voucher
/// accounting, so a run of them would drive that loop without delivering any content. The
/// requester's throughput floor counts bytes off the wire, envelopes included, so it is this
/// floor — not that counter — that keeps wire progress equal to content progress.
/// That is too much weight for a convention, so the type carries the floor instead: the field
/// is private, both `ChunkData` doors reject an empty payload, and the
/// `encode_chunk_*` helpers — which build no `ChunkData`, and among them
/// [`encode_chunk_frame_headers`] is the door both serve paths use — restate the same
/// check on `payload_len`. Every route is closed.
/// Decode shape for [`ChunkData`], which cannot deserialize directly without giving up
/// its private field and with it the invariant. Structurally identical, so the wire
/// format is unchanged; it exists only to be validated on the way in.
/// The `ClientMessage::ChunkData` discriminant, as postcard writes it: the
/// declaration index, varint-encoded, which is one byte for indices 0..=127.
/// Pinned by `client_message_discriminants_are_frozen`.
const CHUNK_DATA_DISCRIMINANT: u8 = 2;
/// Stack-buffer size for a `ChunkData` header (discriminant + varint payload
/// length). Sized to the unconditioned `u32` varint width — 1 + 5 — so the buffer
/// needs no reasoning about [`crate::framing::MAX_MESSAGE_SIZE`]. That cap keeps
/// the bytes actually written to at most 5.
pub const CHUNK_DATA_HEADER_MAX: usize = 6;
/// Stack-buffer size for the full framing + `ChunkData` header: varint
/// `postcard_len` + the one-byte `ChunkData` discriminant + varint `payload_len`.
/// Sized to
/// the unconditioned `u32` varint width — 5 + 1 + 5 — for the same reason as the
/// `ChunkData` header buffer; the cap keeps the bytes actually written to at most 9.
pub const CHUNK_FRAME_HEADERS_MAX: usize = 11;
/// Encode one [`ClientMessage::ChunkData`] frame body directly from its payload.
///
/// Byte-identical to `encode_message(&ClientMessage::ChunkData(ChunkData::new(payload)?))`
/// — pinned by `encode_chunk_frame_matches_the_generic_encoder` — but it copies the
/// payload once instead of twice. The generic path owns the bytes to build the frame
/// (`Vec<u8>`) and postcard copies them again into its output buffer.
///
/// This is the single-buffer door, for callers that need the whole frame as one
/// `Vec<u8>`. The serve paths do not use it: they encode headers only
/// ([`encode_chunk_frame_headers`]) and send the payload uncopied beside them.
///
/// The non-empty floor is checked here rather than inherited from [`ChunkData::new`],
/// since no [`ChunkData`] is built. That keeps the ADR 005 §Non-empty chunk invariant
/// true of every frame this crate can emit, by either door.
///
/// # Errors
///
/// [`MessageValidationError::EmptyChunk`] for a zero-length payload, or
/// [`MessageValidationError::ChunkTooLarge`] if the frame would exceed
/// [`crate::framing::MAX_MESSAGE_SIZE`].
/// Encode the bare `ChunkData` postcard prefix (discriminant + varint payload
/// length) into `out`, returning the number of bytes written.
///
/// There is no framing length in front of it, so this alone is not a valid frame
/// and must never be written to a stream. [`encode_chunk_frame_headers`] builds on
/// it and is what the serve paths send.
///
/// # Errors
///
/// [`MessageValidationError::EmptyChunk`] for `payload_len == 0`, or
/// [`MessageValidationError::ChunkTooLarge`] if the frame would exceed
/// [`crate::framing::MAX_MESSAGE_SIZE`].
pub
/// Encode the full frame headers for a `ChunkData` payload of `payload_len`
/// bytes: the framing varint `postcard_len` followed by the `ChunkData` header
/// (discriminant + varint `payload_len`). The payload itself is **not**
/// included — the caller sends it as `Bytes` alongside this header via a
/// vectored write.
///
/// Returns the number of header bytes written into `out` (≤
/// [`CHUNK_FRAME_HEADERS_MAX`]).
///
/// # Errors
///
/// [`MessageValidationError::EmptyChunk`] for `payload_len == 0`, or
/// [`MessageValidationError::ChunkTooLarge`] if the frame would exceed
/// [`crate::framing::MAX_MESSAGE_SIZE`].
/// Length of the postcard payload (`CHUNK_DATA_DISCRIMINANT` + varint
/// `payload_len` + payload) for a given `payload_len`. This is the size gate the
/// encoders admit on; `encode_chunk_frame_headers` sizes its framing varint from the
/// header it measured rather than from a second guess at the same number.
///
/// Every caller rejects `payload_len == 0` before reaching here, but the answer for
/// it is still right: postcard writes a zero-length sequence as a single `0x00`
/// varint, so an empty `ChunkData` body is 2 bytes.
pub const
/// Payer → node cumulative payment voucher (ADR 005 §Voucher wire format).
///
/// The wire carries `{signature, amount, bytes_delivered, chain_root,
/// chunk_price}`; the receiver reconstructs the full EIP-712 typed data
/// `{poolId, signer, provider, amount, bytesDelivered, chainRoot, chunkPrice}`
/// from stream context (`poolId`/`signer`/`provider` fixed for the stream) plus
/// the self-described fields. There is no nonce: `amount` is the sole ordering
/// and replay key — a voucher whose `amount` is no greater than the highest
/// accepted is stale. `bytes_delivered` is an additional signed, monotone
/// cumulative that must not regress below the highest accepted; it is what the
/// node verifies against (rather than reconstructing) so same-lane vouchers
/// settle independent of arrival order. Both are `u64` cumulative totals
/// matching the contract's on-chain `uint64` `Lane`/`LaneVoucher` storage; the
/// node zero-extends them to `uint256` to reconstruct the EIP-712 signature.
///
/// `amount` is the **settlement anchor**, and `chain_root` heads the optional
/// hash chain that advances it between signatures (ADR 003 §Hash-chain metering
/// (`PayWord`)). Redemption resolves both with one formula:
/// `claimed = amount + chain_index × chunk_price`.
/// Payer → node released hash-chain preimage, advancing the lane's claim by one
/// chunk with no signature (ADR 003 §Hash-chain metering (`PayWord`), ADR 005
/// §Payment quantum and credit window).
///
/// Released after the payer has received and verified the chunk it pays for, so
/// the payer's exposure stays at zero. Preimage resistance makes the value
/// self-proving: nobody derives `keccak^(N−k−1)(s)` from `keccak^(N−k)(s)`
/// without the seed, so a deeper preimage **is** the receipt for every chunk
/// below it.
///
/// # Wire encoding
///
/// `preimage ‖ index`, 33 bytes flat — postcard writes a `[u8; 32]` raw and a
/// `u8` as one byte, so there is no length prefix and no varint. The byte IS
/// the index, with no offset on send and no increment on receipt.
///
/// # Index domain
///
/// Releasable indices are `1..=`[`MAX_CHAIN_LENGTH`]. `index == 0` is a
/// protocol error — index 0 names `chain_root` and is the settlement case at
/// redemption, so it proves nothing the voucher does not already say. It is
/// rejected **in band** by the delivery handler as
/// [`VoucherRejectReason::ChainIndexZero`] rather than at decode, so the
/// payer learns why instead of seeing an opaque stream close. An index above
/// [`MAX_CHAIN_LENGTH`] cannot be encoded at all: the walk is bounded at 255
/// hashes by the type, which is stronger than a runtime comparison.
/// The node's true watermark for a pool capability, echoed back on a gated
/// [`StreamError::VoucherRejected`] so a wallet-less client can self-heal
/// (issue #1481). `amount`/`bytes_delivered` mirror the seller-side
/// `PoolState::last_*` fields as `u64` cumulative totals, for the same reason
/// as [`Voucher`] — matching the contract's on-chain `uint64` storage.
/// `last_signature` is the node's stored last-accepted **client** signature
/// (`r‖s‖v`, exactly [`VOUCHER_SIG_LEN`]) — not a node signature over this
/// bundle — so the client can confirm which of its own vouchers the node
/// holds.
/// A stream failure code (ADR 005 §Open-time refusal classes).
///
/// `NotFound`, `Declined`, and `Unfunded` are the open-time refusal classes and
/// ride in [`StreamResponseExt::error`] alongside `ok: false`.
/// `VoucherRejected` is the only variant delivered mid-stream, inside a
/// [`ClientMessage::StreamError`]. All codes are unsigned and informational,
/// never on-chain evidence. A node keeps its finer refusal reason in its own
/// per-reason metrics. The wire carries only the class, because a requester
/// acts on the class alone.
///
/// Every refusal scopes to the node that sent it, for the current fetch. A
/// requester never ends a fetch on the word of one node.
///
/// Postcard encodes a struct variant's payload positionally, in declaration
/// order, so `VoucherRejected`'s `bundle` field sits after `reason` and any
/// further field appends after `bundle`.
/// Why a [`Voucher`] was rejected (ADR 005 §`VoucherRejected` semantics).
///
/// The first seven variants, [`Self::BadPreimage`], and [`Self::UnderFold`]
/// mirror `decdn_incentive::PoolError` ∪ `VoucherError` one-to-one; the
/// handler-side conversion `voucher_reject_reason` matches those exhaustively
/// so a new `PoolError` variant fails to compile until this enum is extended
/// (ADR 005 §Mirror obligation). The other variants are emitted directly by the
/// `cdn/client/v1` handler: [`Self::CapabilityExpired`] fires when the signer's
/// capability has passed its expiry; [`Self::PoolExhausted`] fires when the
/// pool's remaining deposit can no longer fund further credit;
/// [`Self::SignerCapExhausted`] fires when the signer's shared cap headroom can
/// no longer cover a serve floor; the three remaining hash-chain reasons
/// ([`Self::ChainIndexZero`], [`Self::UnanchoredPreimage`],
/// [`Self::ChunkPriceMismatch`]) are raised where the handler holds the
/// per-stream chain anchor or quoted rate a validation enum cannot see; and
/// [`Self::Underpaid`] fires when the span a voucher adds over the lane's
/// accepted watermark pays below the quoted `rate_per_mb`.
/// Variant order is the postcard wire discriminant, so a reorder is a
/// wire-breaking change.