carbonado 0.7.1

Apocalypse-resistant archival format for consensus-critical data. One portable file: AES-256-CTR + HMAC-SHA512, keyed Bao, Reed-Solomon 4/8, optional zstd, SLH-DSA sidecars.
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
//! Carbonado streaming encode pipelines (inboard + outboard).

use std::io::{Read, Seek, SeekFrom, Write};

use bao::Hash;

use crate::{
    constants::{FEC_K, FEC_M, Format, SLICE_LEN},
    error::CarbonadoError,
    stream::{
        compress::{ZstdEncode, require_zstd_level, stream_compress_with_dict},
        crypto_stream::{
            stream_encrypt, stream_encrypt_embedded_with_nonce, stream_encrypt_with_nonce_seek,
        },
        fec::{
            FecStripesReadAt, feed_inboard_fec_stripes, write_inboard_stripe, write_outboard_parity,
        },
        spool::SeekableSpool,
    },
    structs::{EncodeInfo, OutboardEncoded},
};

use crate::stream::bao::stream_verification_outboard;
use crate::stream::{
    bao::{verification_inboard_buffer, verification_outboard_buffer},
    compress::{compress_buffer, compress_buffer_with_dict},
    crypto_stream::stream_encrypt_with_nonce,
    fec::{encode_inboard_buffer, encode_outboard_parity_buffer},
};

struct CountingReader<R> {
    inner: R,
    count: u64,
}

impl<R: Read> Read for CountingReader<R> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        let n = self.inner.read(buf)?;
        self.count += n as u64;
        Ok(n)
    }
}

/// Statistics from [`stream_preprocess`].
#[derive(Clone, Copy, Debug)]
pub struct PreprocessStats {
    pub bare_len: u64,
    pub input_len: u64,
    pub bytes_compressed: u32,
}

/// Run compress → encrypt into `body_sink`.
///
/// When `header_path_encrypt` is true (file layer), encrypted output is `[tag|ct]` with
/// nonce written to `payload_nonce`. When false (CLI/low-level), nonce is embedded
/// in the sink as `[nonce|tag|ct]`.
///
/// **`fixed_nonce`:** when `Some(n)` and Encryption is set, use `n` literally (including
/// all-zero). When `None`, draw a CSPRNG nonce (production).
/// Prefer CSPRNG for live archives; fixed nonces are for tests/determinism only — see
/// AGENTS §2.1.4 (nonce uniqueness; reuse under the same master is catastrophic).
#[allow(clippy::too_many_arguments)]
pub fn stream_preprocess<R: Read, W: Read + Write + Seek>(
    master_key: &[u8],
    format: Format,
    mut input: R,
    body_sink: &mut W,
    payload_nonce: &mut [u8; 16],
    header_path_encrypt: bool,
    fixed_nonce: Option<[u8; 16]>,
    zstd: &ZstdEncode,
) -> Result<PreprocessStats, CarbonadoError> {
    body_sink
        .seek(std::io::SeekFrom::Start(0))
        .map_err(CarbonadoError::StdIoError)?;
    let mut input_len = 0u64;
    if format.contains(Format::Compression) {
        let level = require_zstd_level(zstd)?;
        let mut counter = CountingReader {
            inner: &mut input,
            count: 0,
        };
        stream_compress_with_dict(&mut counter, &mut *body_sink, level, zstd.dict.as_deref())?;
        input_len = counter.count;
        body_sink.rewind().map_err(CarbonadoError::StdIoError)?;
    } else {
        let mut buf = [0u8; 64 * 1024];
        loop {
            let n = input.read(&mut buf).map_err(CarbonadoError::StdIoError)?;
            if n == 0 {
                break;
            }
            input_len += n as u64;
            body_sink
                .write_all(&buf[..n])
                .map_err(CarbonadoError::StdIoError)?;
        }
    }
    body_sink.rewind().map_err(CarbonadoError::StdIoError)?;
    let bytes_compressed = if format.contains(Format::Compression) {
        reader_len(body_sink)? as u32
    } else {
        0
    };

    let bare_len = if format.contains(Format::Encryption) {
        let comp_len = reader_len(body_sink)?;
        body_sink
            .seek(SeekFrom::Start(0))
            .map_err(CarbonadoError::StdIoError)?;
        if header_path_encrypt {
            match fixed_nonce {
                Some(n) => *payload_nonce = n,
                None => {
                    getrandom::getrandom(payload_nonce)
                        .map_err(|_| CarbonadoError::RandomnessError)?;
                }
            }
            encrypt_preprocess_sink(master_key, *payload_nonce, body_sink, comp_len)?;
        } else {
            let mut encrypted_spool = SeekableSpool::new()?;
            match fixed_nonce {
                Some(n) => {
                    stream_encrypt_embedded_with_nonce(
                        master_key,
                        n,
                        std::io::Read::by_ref(body_sink).take(comp_len),
                        &mut encrypted_spool,
                    )?;
                    *payload_nonce = n;
                }
                None => {
                    let (_len, nonce) = stream_encrypt(
                        master_key,
                        std::io::Read::by_ref(body_sink).take(comp_len),
                        &mut encrypted_spool,
                    )?;
                    *payload_nonce = nonce;
                }
            }
            replace_preprocess_encrypted(body_sink, &mut encrypted_spool)?;
        }
        reader_len(body_sink)?
    } else {
        reader_len(body_sink)?
    };
    body_sink.rewind().map_err(CarbonadoError::StdIoError)?;
    Ok(PreprocessStats {
        bare_len,
        input_len,
        bytes_compressed,
    })
}

/// [`stream_preprocess`] for [`SeekableSpool`] sinks — encrypt replace uses
/// [`SeekableSpool::overwrite_from`] so file size matches ciphertext (no stale tail bytes).
#[allow(clippy::too_many_arguments)]
pub(crate) fn stream_preprocess_spool<R: Read>(
    master_key: &[u8],
    format: Format,
    mut input: R,
    body_sink: &mut SeekableSpool,
    payload_nonce: &mut [u8; 16],
    header_path_encrypt: bool,
    fixed_nonce: Option<[u8; 16]>,
    zstd: &ZstdEncode,
) -> Result<PreprocessStats, CarbonadoError> {
    body_sink.rewind()?;
    let mut input_len = 0u64;
    if format.contains(Format::Compression) {
        let level = require_zstd_level(zstd)?;
        let mut counter = CountingReader {
            inner: &mut input,
            count: 0,
        };
        stream_compress_with_dict(&mut counter, &mut *body_sink, level, zstd.dict.as_deref())?;
        input_len = counter.count;
        body_sink.rewind()?;
    } else {
        let mut buf = [0u8; 64 * 1024];
        loop {
            let n = input.read(&mut buf).map_err(CarbonadoError::StdIoError)?;
            if n == 0 {
                break;
            }
            input_len += n as u64;
            body_sink
                .write_all(&buf[..n])
                .map_err(CarbonadoError::StdIoError)?;
        }
    }
    body_sink.rewind()?;
    let bytes_compressed = if format.contains(Format::Compression) {
        body_sink.content_len()? as u32
    } else {
        0
    };

    let bare_len = if format.contains(Format::Encryption) {
        let comp_len = body_sink.content_len()?;
        body_sink.rewind()?;
        if header_path_encrypt {
            match fixed_nonce {
                Some(n) => *payload_nonce = n,
                None => {
                    getrandom::getrandom(payload_nonce)
                        .map_err(|_| CarbonadoError::RandomnessError)?;
                }
            }
            encrypt_preprocess_spool(master_key, *payload_nonce, body_sink, comp_len)?;
        } else {
            let mut encrypted_spool = SeekableSpool::new()?;
            match fixed_nonce {
                Some(n) => {
                    stream_encrypt_embedded_with_nonce(
                        master_key,
                        n,
                        std::io::Read::by_ref(body_sink).take(comp_len),
                        &mut encrypted_spool,
                    )?;
                    *payload_nonce = n;
                }
                None => {
                    let (_len, nonce) = stream_encrypt(
                        master_key,
                        std::io::Read::by_ref(body_sink).take(comp_len),
                        &mut encrypted_spool,
                    )?;
                    *payload_nonce = nonce;
                }
            }
            body_sink.overwrite_from(&mut encrypted_spool)?;
        }
        body_sink.content_len()?
    } else {
        body_sink.content_len()?
    };
    body_sink.rewind()?;
    Ok(PreprocessStats {
        bare_len,
        input_len,
        bytes_compressed,
    })
}

/// Encrypt `len` bytes from `sink` in place via a temp spool (no full-body `Vec`).
fn encrypt_preprocess_sink<W: Read + Write + Seek>(
    master_key: &[u8],
    nonce: [u8; 16],
    sink: &mut W,
    len: u64,
) -> Result<(), CarbonadoError> {
    sink.seek(SeekFrom::Start(0))
        .map_err(CarbonadoError::StdIoError)?;
    let mut encrypted = SeekableSpool::new()?;
    stream_encrypt_with_nonce_seek(
        master_key,
        nonce,
        std::io::Read::by_ref(sink).take(len),
        &mut encrypted,
    )?;
    replace_preprocess_encrypted(sink, &mut encrypted)
}

/// Header-path encrypt for [`SeekableSpool`] preprocess sinks (uses [`SeekableSpool::overwrite_from`]).
pub(crate) fn encrypt_preprocess_spool(
    master_key: &[u8],
    nonce: [u8; 16],
    sink: &mut SeekableSpool,
    len: u64,
) -> Result<(), CarbonadoError> {
    sink.rewind()?;
    let mut encrypted = SeekableSpool::new()?;
    stream_encrypt_with_nonce_seek(
        master_key,
        nonce,
        std::io::Read::by_ref(sink).take(len),
        &mut encrypted,
    )?;
    sink.overwrite_from(&mut encrypted)
}

/// Copy encrypted spool back into a seekable preprocess sink (no full-body `Vec`).
fn replace_preprocess_encrypted<W: Read + Write + Seek>(
    sink: &mut W,
    src: &mut SeekableSpool,
) -> Result<(), CarbonadoError> {
    src.rewind()?;
    sink.seek(SeekFrom::Start(0))
        .map_err(CarbonadoError::StdIoError)?;
    std::io::copy(src, sink).map_err(CarbonadoError::StdIoError)?;
    sink.seek(SeekFrom::Start(0))
        .map_err(CarbonadoError::StdIoError)?;
    Ok(())
}

fn reader_len<R: Read + Seek>(r: &mut R) -> Result<u64, CarbonadoError> {
    r.seek(std::io::SeekFrom::End(0))
        .map_err(CarbonadoError::StdIoError)
}

/// Primary inboard encode (buffer). Used by [`crate::encoding::encode`].
///
/// Encrypted formats draw a random nonce (embedded layout). For a fixed nonce
/// (G9 fixtures), use [`stream_encode_buffer_with_nonce`].
pub fn stream_encode_buffer(
    master_key: &[u8],
    input: &[u8],
    format: u8,
) -> Result<(Vec<u8>, Hash, EncodeInfo), CarbonadoError> {
    stream_encode_buffer_with_zstd(master_key, input, format, None, &ZstdEncode::default())
}

/// Inboard buffer encode with explicit zstd parameters (required when Compression is set).
pub fn stream_encode_buffer_with_zstd(
    master_key: &[u8],
    input: &[u8],
    format: u8,
    explicit_nonce: Option<[u8; 16]>,
    zstd: &ZstdEncode,
) -> Result<(Vec<u8>, Hash, EncodeInfo), CarbonadoError> {
    stream_encode_buffer_with_nonce(master_key, input, format, explicit_nonce, zstd)
}

/// Inboard body encode with optional fixed nonce for encrypted formats.
///
/// When `explicit_nonce` is `Some(n)` and the Encryption bit is set, the low-level
/// embedded layout is `[nonce(16) | tag(64) | ct]` with `n` (including all-zero).
/// When `None`, encrypted formats use a CSPRNG nonce. Public formats ignore the nonce.
///
/// Production defaults are unchanged: [`stream_encode_buffer`] / [`crate::encode`] pass `None`.
///
/// # Safety / intended use
///
/// Fixed nonces are for **tests and determinism only**. Prefer [`stream_encode_buffer`]
/// for production. Nonce reuse under the same master is catastrophic (AGENTS §2.1.4).
pub fn stream_encode_buffer_with_nonce(
    master_key: &[u8],
    input: &[u8],
    format: u8,
    explicit_nonce: Option<[u8; 16]>,
    zstd: &ZstdEncode,
) -> Result<(Vec<u8>, Hash, EncodeInfo), CarbonadoError> {
    let fmt = Format::from(format);
    let input_len = input.len() as u32;
    let mut body = input.to_vec();
    let mut bytes_compressed = 0u32;
    let mut bytes_encrypted = 0u32;

    if fmt.contains(Format::Compression) {
        let level = require_zstd_level(zstd)?;
        body = if let Some(dict) = zstd.dict.as_deref().filter(|d| !d.is_empty()) {
            compress_buffer_with_dict(input, level, dict)?
        } else {
            compress_buffer(input, level)?
        };
        bytes_compressed = body.len() as u32;
    }
    if fmt.contains(Format::Encryption) {
        body = {
            let mut out = SeekableSpool::new()?;
            match explicit_nonce {
                Some(nonce) => {
                    stream_encrypt_embedded_with_nonce(
                        master_key,
                        nonce,
                        std::io::Cursor::new(&body),
                        &mut out,
                    )?;
                }
                None => {
                    let (_len, _nonce) =
                        stream_encrypt(master_key, std::io::Cursor::new(&body), &mut out)?;
                }
            }
            let mut buf = Vec::new();
            out.rewind()?;
            std::io::copy(&mut out, &mut buf).map_err(CarbonadoError::StdIoError)?;
            buf
        };
        bytes_encrypted = body.len() as u32;
    }

    let (after_fec, padding_len, chunk_len, bytes_ecc) = if fmt.contains(Format::Fec) {
        let (encoded, pl, cl) = encode_inboard_buffer(&body)?;
        let be = encoded.len() as u32;
        (encoded, pl, cl, be)
    } else {
        (body, 0, 0, 0)
    };

    let verifiable_slice_count = if fmt.contains(Format::Fec) {
        bytes_ecc / SLICE_LEN
    } else {
        0
    };
    if fmt.contains(Format::Fec) && !verifiable_slice_count.is_multiple_of(8) {
        return Err(CarbonadoError::InvalidVerifiableSliceCount(
            verifiable_slice_count,
        ));
    }

    let (verifiable, hash) = if fmt.contains(Format::Verification) {
        verification_inboard_buffer(&after_fec, format)?
    } else {
        (after_fec, Hash::from([0u8; 32]))
    };

    let bytes_verifiable = verifiable.len() as u32;
    Ok((
        verifiable,
        hash,
        EncodeInfo {
            input_len,
            output_len: bytes_verifiable,
            bytes_compressed,
            bytes_encrypted,
            bytes_ecc,
            bytes_verifiable,
            compression_factor: bytes_compressed as f32 / input_len.max(1) as f32,
            amplification_factor: bytes_verifiable as f32 / input_len.max(1) as f32,
            padding_len,
            chunk_len,
            verifiable_slice_count,
            chunk_slice_count: verifiable_slice_count / 8,
        },
    ))
}

/// Primary outboard encode (buffer). Used by [`crate::encoding::encode_outboard`].
///
/// When `explicit_nonce` is `Some`, encrypted output is `[tag(64) | ct]` (header path).
/// When `None`, encrypted output embeds the nonce (low-level path).
pub fn stream_encode_outboard_buffer(
    master_key: &[u8],
    input: &[u8],
    format: u8,
    explicit_nonce: Option<[u8; 16]>,
    zstd: &ZstdEncode,
) -> Result<OutboardEncoded, CarbonadoError> {
    let fmt = Format::from(format);
    let input_len = input.len() as u32;
    let mut bytes_compressed = 0u32;

    let compressed = if fmt.contains(Format::Compression) {
        let level = require_zstd_level(zstd)?;
        let c = if let Some(dict) = zstd.dict.as_deref().filter(|d| !d.is_empty()) {
            compress_buffer_with_dict(input, level, dict)?
        } else {
            compress_buffer(input, level)?
        };
        bytes_compressed = c.len() as u32;
        c
    } else {
        input.to_vec()
    };

    let post_comp_or_enc;
    let bytes_encrypted;
    if fmt.contains(Format::Encryption) {
        post_comp_or_enc = {
            let mut out = SeekableSpool::new()?;
            if let Some(nonce) = explicit_nonce {
                stream_encrypt_with_nonce(
                    master_key,
                    nonce,
                    std::io::Cursor::new(&compressed),
                    &mut out,
                )?;
            } else {
                stream_encrypt(master_key, std::io::Cursor::new(&compressed), &mut out)?;
            }
            let mut buf = Vec::new();
            out.rewind()?;
            std::io::copy(&mut out, &mut buf).map_err(CarbonadoError::StdIoError)?;
            buf
        };
        bytes_encrypted = post_comp_or_enc.len() as u32;
    } else {
        post_comp_or_enc = compressed;
        bytes_encrypted = 0;
    }

    let (post_fec_or_bare, padding_len, chunk_len, bytes_ecc, fec_parity, vslice, cslice) =
        if fmt.contains(Format::Fec) {
            let (pl, cl, parity) = encode_outboard_parity_buffer(&post_comp_or_enc)?;
            let vs = if cl == 0 {
                0
            } else {
                (parity.len() as u32 / ((FEC_M - FEC_K) as u32 * SLICE_LEN)) * FEC_M as u32
            };
            if !vs.is_multiple_of(8) {
                return Err(CarbonadoError::InvalidVerifiableSliceCount(vs));
            }
            (
                post_comp_or_enc,
                pl,
                cl,
                parity.len() as u32,
                Some(parity),
                vs,
                vs / 8,
            )
        } else {
            (post_comp_or_enc, 0, 0, 0, None, 0, 0)
        };

    let (main_for_return, bao_out, hash, bytes_verifiable) = if fmt.contains(Format::Verification) {
        let bv = post_fec_or_bare.len() as u32;
        let (ob, h) = verification_outboard_buffer(&post_fec_or_bare, format)?;
        (post_fec_or_bare, Some(ob), h, bv)
    } else {
        let bv = post_fec_or_bare.len() as u32;
        (post_fec_or_bare, None, Hash::from([0; 32]), bv)
    };

    Ok(OutboardEncoded {
        main: main_for_return,
        verification_outboard: bao_out,
        fec_parity,
        hash,
        info: EncodeInfo {
            input_len,
            output_len: bytes_verifiable,
            bytes_compressed,
            bytes_encrypted,
            bytes_ecc,
            bytes_verifiable,
            compression_factor: bytes_compressed as f32 / input_len.max(1) as f32,
            amplification_factor: bytes_verifiable as f32 / input_len.max(1) as f32,
            padding_len,
            chunk_len,
            verifiable_slice_count: vslice,
            chunk_slice_count: cslice,
        },
    })
}

/// Stream outboard encode to writers (public + encrypted).
///
/// Peak RAM is **O(chunk/stripe)** on the S4 geometric path (compress streams).
///
/// Encrypted formats always draw a CSPRNG nonce for this stream API. For a fixed nonce
/// (tests/G9), use [`stream_encode_outboard_buffer`] with `Some(nonce)` (header-path
/// layout when `Some`).
#[allow(clippy::too_many_arguments)]
pub fn stream_encode_outboard<M: Read + Write + Seek, O: Write, P: Write>(
    master_key: &[u8],
    input: impl Read,
    format: u8,
    main_out: &mut M,
    bao_out: Option<&mut O>,
    parity_out: Option<&mut P>,
    payload_nonce: &mut [u8; 16],
    header_path_encrypt: bool,
    zstd: &ZstdEncode,
) -> Result<(Hash, EncodeInfo), CarbonadoError> {
    stream_encode_outboard_s4(
        master_key,
        input,
        format,
        main_out,
        bao_out,
        parity_out,
        payload_nonce,
        header_path_encrypt,
        zstd,
    )
}

/// S4 outboard encode: O(chunk/stripe) peak RAM (geometric + encrypted EtM spool).
#[allow(clippy::too_many_arguments)]
fn stream_encode_outboard_s4<M: Read + Write + Seek, O: Write, P: Write>(
    master_key: &[u8],
    input: impl Read,
    format: u8,
    main_out: &mut M,
    mut bao_out: Option<&mut O>,
    mut parity_out: Option<&mut P>,
    payload_nonce: &mut [u8; 16],
    header_path_encrypt: bool,
    zstd: &ZstdEncode,
) -> Result<(Hash, EncodeInfo), CarbonadoError> {
    let fmt = Format::from(format);
    // Fail-closed: required sidecar writers when format bits demand them.
    if fmt.contains(Format::Verification) && bao_out.is_none() {
        return Err(CarbonadoError::MissingVerificationOutboard);
    }
    if fmt.contains(Format::Fec) && parity_out.is_none() {
        return Err(CarbonadoError::MissingFecParity);
    }
    // Stream outboard uses CSPRNG when encrypted (`fixed_nonce = None`). Deterministic
    // encrypted outboard goldens use [`stream_encode_outboard_buffer`] with `Some(nonce)`.
    let stats = stream_preprocess(
        master_key,
        fmt,
        input,
        main_out,
        payload_nonce,
        header_path_encrypt,
        None,
        zstd,
    )?;
    let bare_len = stats.bare_len;
    main_out.rewind().map_err(CarbonadoError::StdIoError)?;

    let (padding_len, chunk_len, bytes_ecc, _fec_parity_len) = if fmt.contains(Format::Fec) {
        if bare_len == 0 {
            (0, 0, 0, 0)
        } else {
            let (stripes, pl, cl) = feed_inboard_fec_stripes(bare_len as usize, &mut *main_out)?;
            let par = parity_out
                .as_mut()
                .ok_or(CarbonadoError::MissingFecParity)?;
            let mut par_len = 0u64;
            for stripe in &stripes {
                par_len += write_outboard_parity(stripe, par)?;
            }
            main_out.rewind().map_err(CarbonadoError::StdIoError)?;
            (pl, cl, par_len as u32, par_len as u32)
        }
    } else {
        (0, 0, 0, 0)
    };

    let hash = if fmt.contains(Format::Verification) {
        let ob = bao_out
            .as_mut()
            .ok_or(CarbonadoError::MissingVerificationOutboard)?;
        stream_verification_outboard(&mut *main_out, bare_len, format, ob)?
    } else {
        Hash::from([0u8; 32])
    };

    let verifiable_slice_count = if fmt.contains(Format::Fec) {
        if chunk_len == 0 {
            0
        } else {
            (bytes_ecc / (FEC_M as u32 - FEC_K as u32).max(1)) * FEC_M as u32 / SLICE_LEN
        }
    } else {
        0
    };
    if fmt.contains(Format::Fec) && !verifiable_slice_count.is_multiple_of(8) {
        return Err(CarbonadoError::InvalidVerifiableSliceCount(
            verifiable_slice_count,
        ));
    }

    Ok((
        hash,
        EncodeInfo {
            input_len: stats.input_len as u32,
            output_len: bare_len as u32,
            bytes_compressed: stats.bytes_compressed,
            bytes_encrypted: if fmt.contains(Format::Encryption) {
                bare_len as u32
            } else {
                0
            },
            bytes_ecc,
            bytes_verifiable: bare_len as u32,
            compression_factor: stats.bytes_compressed as f32 / stats.input_len.max(1) as f32,
            amplification_factor: bare_len as f32 / stats.input_len.max(1) as f32,
            padding_len,
            chunk_len,
            verifiable_slice_count,
            chunk_slice_count: verifiable_slice_count / 8,
        },
    ))
}

/// Stream inboard encode body from an in-memory staging buffer.
pub fn stream_encode_inboard_body_from_bytes<W: Write>(
    body: &[u8],
    preprocess: PreprocessStats,
    format: u8,
    output: &mut W,
) -> Result<(Hash, EncodeInfo), CarbonadoError> {
    stream_encode_inboard_body(std::io::Cursor::new(body), preprocess, format, output)
}

/// Stream inboard encode body to `output` from post-preprocess source.
///
/// `preprocess` carries original [`PreprocessStats::input_len`] plus post-compress/encrypt
/// [`PreprocessStats::bare_len`] for accurate [`EncodeInfo`] bookkeeping.
///
/// FEC (`Format::Fec`) feeds `data` incrementally via [`FecInboardEncoder`] — peak encode
/// memory is O(stripe), not O(bare_len). Verification reads stripes via
/// [`FecStripesReadAt`] without flattening to a staging `Vec` (S3).
pub fn stream_encode_inboard_body<D: Read + Seek, W: Write>(
    mut data: D,
    preprocess: PreprocessStats,
    format: u8,
    output: &mut W,
) -> Result<(Hash, EncodeInfo), CarbonadoError> {
    let fmt = Format::from(format);
    let content_len = preprocess.bare_len;

    let (padding_len, chunk_len, bytes_ecc, hash, bytes_verifiable) = if fmt.contains(Format::Fec) {
        if content_len == 0 {
            let (hash, bytes_verifiable) = if fmt.contains(Format::Verification) {
                let (h, written) =
                    crate::stream::bao::stream_verification_inboard(&[][..], 0, format, output)?;
                (h, written as u32)
            } else {
                (Hash::from([0; 32]), 0)
            };
            (0, 0, 0, hash, bytes_verifiable)
        } else {
            data.rewind().map_err(CarbonadoError::StdIoError)?;
            let (stripes, padding_len, chunk_len) =
                feed_inboard_fec_stripes(content_len as usize, &mut data)?;
            let bytes_ecc = stripes.len() as u32 * FEC_M as u32 * chunk_len;

            if fmt.contains(Format::Verification) {
                let stripe_view = FecStripesReadAt::new(&stripes);
                let fec_len = stripe_view.len();
                let (h, written) = crate::stream::bao::stream_verification_inboard(
                    stripe_view,
                    fec_len,
                    format,
                    output,
                )?;
                (padding_len, chunk_len, bytes_ecc, h, written as u32)
            } else {
                let mut written = 0u32;
                for stripe in &stripes {
                    written += write_inboard_stripe(stripe, output)? as u32;
                }
                (
                    padding_len,
                    chunk_len,
                    bytes_ecc,
                    Hash::from([0; 32]),
                    written,
                )
            }
        }
    } else if fmt.contains(Format::Verification) {
        data.rewind().map_err(CarbonadoError::StdIoError)?;
        let (h, written) = crate::stream::bao::stream_verification_inboard(
            crate::stream::bao::SeekReadAt::new(data, content_len),
            content_len,
            format,
            output,
        )?;
        (0, 0, 0, h, written as u32)
    } else {
        data.rewind().map_err(CarbonadoError::StdIoError)?;
        let written = stream_copy(&mut data, content_len, output)? as u32;
        (0, 0, 0, Hash::from([0; 32]), written)
    };

    let verifiable_slice_count = if fmt.contains(Format::Fec) {
        bytes_ecc / SLICE_LEN
    } else {
        0
    };
    if fmt.contains(Format::Fec) && !verifiable_slice_count.is_multiple_of(8) {
        return Err(CarbonadoError::InvalidVerifiableSliceCount(
            verifiable_slice_count,
        ));
    }

    let bytes_compressed = if fmt.contains(Format::Compression) {
        preprocess.bytes_compressed
    } else {
        0
    };
    let bytes_encrypted = if fmt.contains(Format::Encryption) {
        preprocess.bare_len as u32
    } else {
        0
    };
    let compression_factor = if fmt.contains(Format::Compression) {
        preprocess.bytes_compressed as f32 / preprocess.input_len.max(1) as f32
    } else {
        0.0
    };

    Ok((
        hash,
        EncodeInfo {
            input_len: preprocess.input_len as u32,
            output_len: bytes_verifiable,
            bytes_compressed,
            bytes_encrypted,
            bytes_ecc,
            bytes_verifiable,
            compression_factor,
            amplification_factor: bytes_verifiable as f32 / preprocess.input_len.max(1) as f32,
            padding_len,
            chunk_len,
            verifiable_slice_count,
            chunk_slice_count: verifiable_slice_count / 8,
        },
    ))
}

fn stream_copy<R: Read, W: Write>(
    data: &mut R,
    len: u64,
    output: &mut W,
) -> Result<u64, CarbonadoError> {
    let mut remaining = len;
    let mut buf = [0u8; 64 * 1024];
    let mut copied = 0u64;
    while remaining > 0 {
        let cap = buf.len().min(remaining as usize);
        let n = data
            .read(&mut buf[..cap])
            .map_err(CarbonadoError::StdIoError)?;
        if n == 0 {
            return Err(CarbonadoError::StdIoError(std::io::Error::new(
                std::io::ErrorKind::UnexpectedEof,
                "stream_copy: short read",
            )));
        }
        output
            .write_all(&buf[..n])
            .map_err(CarbonadoError::StdIoError)?;
        remaining -= n as u64;
        copied += n as u64;
    }
    Ok(copied)
}

/// Fused inboard encode: preprocess into a disk spool, then FEC/Bao directly to `output`.
///
/// Encrypted formats draw a CSPRNG nonce. For a fixed nonce (including all-zero), use
/// [`stream_encode_inboard_with_nonce`].
pub fn stream_encode_inboard<R: Read, W: Write>(
    master_key: &[u8],
    input: R,
    format: u8,
    output: &mut W,
    payload_nonce: &mut [u8; 16],
    header_path_encrypt: bool,
    zstd: &ZstdEncode,
) -> Result<(Hash, EncodeInfo, PreprocessStats), CarbonadoError> {
    stream_encode_inboard_with_nonce(
        master_key,
        input,
        format,
        output,
        payload_nonce,
        header_path_encrypt,
        None,
        zstd,
    )
}

/// Like [`stream_encode_inboard`], with optional fixed AES-CTR nonce when encrypted.
///
/// When `fixed_nonce` is `Some(n)`, this uses `n` literally (including all-zero).
/// When `None`, a CSPRNG nonce is drawn. **Test/determinism only** for fixed nonces —
/// nonce reuse under the same master is catastrophic (AGENTS §2.1.4). Prefer
/// [`stream_encode_inboard`] for production.
#[allow(clippy::too_many_arguments)]
pub fn stream_encode_inboard_with_nonce<R: Read, W: Write>(
    master_key: &[u8],
    input: R,
    format: u8,
    output: &mut W,
    payload_nonce: &mut [u8; 16],
    header_path_encrypt: bool,
    fixed_nonce: Option<[u8; 16]>,
    zstd: &ZstdEncode,
) -> Result<(Hash, EncodeInfo, PreprocessStats), CarbonadoError> {
    let fmt = Format::from(format);
    let mut spool = SeekableSpool::new()?;
    let stats = stream_preprocess_spool(
        master_key,
        fmt,
        input,
        &mut spool,
        payload_nonce,
        header_path_encrypt,
        fixed_nonce,
        zstd,
    )?;
    let (hash, info) = stream_encode_inboard_body(&mut spool, stats, format, output)?;
    Ok((hash, info, stats))
}