bblock 0.3.0

Persistent checksummed blocks built on top of bstack
Documentation
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
//! AES-256-GCM authenticated-encryption blocks.
//!
//! # Overview
//!
//! This module wraps any [`BStackAllocator`] and stores every allocation as
//! an authenticated ciphertext.  Reads decrypt transparently; writes encrypt
//! with a caller-supplied nonce generator.  The AEAD authentication tag
//! provides strong integrity guarantees — no separate checksum layer is needed.
//!
//! The main types:
//!
//! | Type                   | Role                                                         |
//! |------------------------|--------------------------------------------------------------|
//! | [`BAESBlockAllocator`] | Wraps a `BStackAllocator`; produces [`BAESBlock`]s           |
//! | [`BAESBlock`]          | Encrypted block handle; source of readers and writers        |
//! | [`BAESBlockReader`]    | Cursor-based `io::Read + io::Seek` over decrypted plaintext  |
//! | [`BAESBlockWriter`]    | Buffered `io::Write + io::Seek`; encrypts on `flush()`/drop  |
//!
//! # On-disk format
//!
//! ```text
//! [algo: 4 bytes = b"A2GM"][nonce: 12 bytes][ciphertext: n bytes][tag: 16 bytes]
//! ```
//!
//! Total overhead: [`AES_OVERHEAD`] = 32 bytes per block.
//!
//! # Security
//!
//! AES-256-GCM is an AEAD cipher with hardware acceleration on platforms with
//! AES-NI.  The authentication tag covers both the ciphertext and the nonce,
//! so any tampering with any byte of the stored block is detected on the next
//! read or [`BAESBlock::verify`].
//!
//! **Nonce uniqueness is critical**: never reuse the same (key, nonce) pair for
//! different plaintexts.  The [`BAESBlockAllocator`] calls the provided
//! `nonce_gen` function for every fresh encryption (each `write` / `alloc` /
//! size-changing `realloc`); it is the caller's responsibility to supply a
//! generator that returns unique nonces (e.g. a CSPRNG).
//!
//! # Detection, not recovery
//!
//! A failed [`BAESBlock::verify`] or a decryption error means the data must
//! not be trusted.  This module provides no repair or rollback mechanism.

use crate::{BStackRawAllocator, BlockStart};
use aes_gcm::{
    Aes256Gcm, Key, Nonce,
    aead::{Aead, KeyInit},
};
use bstack::{BStack, BStackAllocator, BStackGuardedSlice, BStackGuardedSliceSubview, BStackSlice};
use std::cmp::Ordering;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::io;
use std::marker::PhantomData;

/// Four-byte magic identifying the AES-256-GCM algorithm.
const AES_MAGIC: &[u8; 4] = b"A2GM";

/// Number of extra bytes stored per block:
/// 4 (magic) + 12 (nonce) + 16 (tag).
pub const AES_OVERHEAD: u64 = 32;

// ── Allocator ────────────────────────────────────────────────────────────────

/// Wraps any [`BStackAllocator`] and transparently encrypts every allocation
/// with AES-256-GCM.
///
/// Each allocation stores [`AES_OVERHEAD`] (32) extra bytes on disk, so
/// `alloc(n)` allocates `n + 32` bytes in the underlying stack.
///
/// The `nonce_gen` function is called for every fresh encryption.  It must
/// return a unique 12-byte nonce; use a CSPRNG in production code.
pub struct BAESBlockAllocator<A: BStackAllocator> {
    inner: A,
    key: [u8; 32],
    nonce_gen: fn() -> [u8; 12],
}

impl<A: BStackAllocator> BAESBlockAllocator<A> {
    /// Create a new allocator wrapping `inner`.
    ///
    /// `key` is the 256-bit AES-256-GCM key used for all blocks.
    /// `nonce_gen` is called on every write to produce a fresh 12-byte nonce.
    pub fn new(inner: A, key: [u8; 32], nonce_gen: fn() -> [u8; 12]) -> Self {
        Self {
            inner,
            key,
            nonce_gen,
        }
    }

    /// Return a shared reference to the inner allocator.
    pub fn inner(&self) -> &A {
        &self.inner
    }

    /// Consume the wrapper and return the inner allocator.
    pub fn into_inner(self) -> A {
        self.inner
    }
}

// ── Block handle ─────────────────────────────────────────────────────────────

/// A handle to an AES-256-GCM encrypted block.
///
/// **Backing layout:** `[b"A2GM": 4][nonce: 12][ciphertext: len][tag: 16]`
///
/// `BAESBlock` is `Copy`: every copy refers to the same physical region.
///
/// ## Reading and writing
///
/// Use the inherent [`read`](BAESBlock::read) method to decrypt and return
/// the full plaintext.  For streaming I/O use [`reader`](BAESBlock::reader)
/// and [`writer`](BAESBlock::writer).
///
/// [`BStackGuardedSlice::write`] and [`BStackGuardedSlice::zero`] are also
/// available (requires `use bstack::BStackGuardedSlice`).  `as_slice()` is
/// intentionally unsupported — exposing raw ciphertext as a plaintext slice
/// has no safe semantics.
///
/// ## Integrity
///
/// [`verify`](BAESBlock::verify) attempts a full decryption; it returns
/// `Ok(false)` (not `Err`) if the authentication tag fails, so callers can
/// distinguish corruption from I/O errors.
pub struct BAESBlock<'a, A: BStackAllocator> {
    slice: BStackSlice<'a, A>,
    len: u64,
    key: [u8; 32],
    nonce_gen: fn() -> [u8; 12],
}

impl<'a, A: BStackAllocator> Copy for BAESBlock<'a, A> {}

impl<'a, A: BStackAllocator> Clone for BAESBlock<'a, A> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'a, A: BStackAllocator> fmt::Debug for BAESBlock<'a, A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BAESBlock")
            .field("start", &self.slice.start())
            .field("len", &self.len)
            .finish_non_exhaustive()
    }
}

impl<'a, A: BStackAllocator> PartialEq for BAESBlock<'a, A> {
    fn eq(&self, other: &Self) -> bool {
        self.slice == other.slice && self.len == other.len
    }
}

impl<'a, A: BStackAllocator> Eq for BAESBlock<'a, A> {}

impl<'a, A: BStackAllocator> Hash for BAESBlock<'a, A> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.slice.hash(state);
        self.len.hash(state);
    }
}

impl<'a, A: BStackAllocator> PartialOrd for BAESBlock<'a, A> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<'a, A: BStackAllocator> Ord for BAESBlock<'a, A> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.slice.cmp(&other.slice).then(self.len.cmp(&other.len))
    }
}

impl<'a, A: BStackAllocator> From<BAESBlock<'a, A>> for [u8; 16] {
    fn from(block: BAESBlock<'a, A>) -> [u8; 16] {
        block.to_bytes()
    }
}

impl<'a, A: BStackAllocator> BAESBlock<'a, A> {
    /// Serialize this block reference as a 16-byte array `[offset: u64 LE | len: u64 LE]`.
    pub fn to_bytes(&self) -> [u8; 16] {
        let mut out = [0u8; 16];
        out[..8].copy_from_slice(&self.slice.start().to_le_bytes());
        out[8..].copy_from_slice(&self.len.to_le_bytes());
        out
    }

    /// Return `true` if the block decrypts successfully (magic matches and tag
    /// is valid).  Returns `Ok(false)` for corruption, `Err` for I/O errors.
    pub fn verify(&self) -> io::Result<bool> {
        match self.decrypt_read() {
            Ok(_) => Ok(true),
            Err(e) if e.kind() == io::ErrorKind::InvalidData => Ok(false),
            Err(e) => Err(e),
        }
    }

    /// Decrypt and return the full plaintext.
    pub fn read(&self) -> io::Result<Vec<u8>> {
        self.decrypt_read()
    }

    /// Return a cursor-based reader over the decrypted plaintext.
    ///
    /// The full block is decrypted once on construction; subsequent reads and
    /// seeks operate on the in-memory buffer.
    pub fn reader(&self) -> io::Result<BAESBlockReader<'a, A>> {
        Ok(BAESBlockReader {
            buf: self.decrypt_read()?,
            pos: 0,
            _marker: PhantomData,
        })
    }

    /// Return a buffered writer over the plaintext.
    ///
    /// The current plaintext is decrypted into an in-memory buffer on
    /// construction.  Writes and seeks modify the buffer only.  The buffer is
    /// re-encrypted and written to disk when [`flush`](io::Write::flush) is
    /// called or when the writer is dropped.
    pub fn writer(&self) -> io::Result<BAESBlockWriter<'a, A>> {
        Ok(BAESBlockWriter {
            block: *self,
            buf: self.decrypt_read()?,
            pos: 0,
            dirty: false,
        })
    }

    /// Return a [`BAESBlockView`] covering the full plaintext region.
    ///
    /// The view can be narrowed with [`BAESBlockView::subview`].
    pub fn view(&self) -> BAESBlockView<'a, A> {
        BAESBlockView {
            block: *self,
            start: 0,
            end: self.len,
        }
    }

    /// Consume the block and return the raw underlying [`BStackSlice`].
    ///
    /// # Safety
    ///
    /// Any mutation through the returned slice bypasses encryption and will
    /// corrupt or forge the stored ciphertext.
    pub unsafe fn into_slice(self) -> BStackSlice<'a, A> {
        self.slice
    }

    // ── Private helpers ──────────────────────────────────────────────────────

    fn encrypt_write(&self, plaintext: &[u8]) -> io::Result<()> {
        let nonce_bytes = (self.nonce_gen)();
        let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&self.key));
        let ct = cipher
            .encrypt(Nonce::from_slice(&nonce_bytes), plaintext)
            .map_err(|_| io::Error::other("AES-GCM encryption failed"))?;
        self.slice.subslice(0, 4).write(*AES_MAGIC)?;
        self.slice.subslice(4, 16).write(nonce_bytes)?;
        self.slice.subslice(16, self.len + AES_OVERHEAD).write(&ct)
    }

    fn decrypt_read(&self) -> io::Result<Vec<u8>> {
        let mut magic = [0u8; 4];
        self.slice.subslice(0, 4).read_into(&mut magic)?;
        if &magic != AES_MAGIC {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "wrong algo magic: expected A2GM",
            ));
        }
        let mut nonce_bytes = [0u8; 12];
        self.slice.subslice(4, 16).read_into(&mut nonce_bytes)?;
        let ct = self.slice.subslice(16, self.len + AES_OVERHEAD).read()?;
        let cipher = Aes256Gcm::new(Key::<Aes256Gcm>::from_slice(&self.key));
        cipher
            .decrypt(Nonce::from_slice(&nonce_bytes), ct.as_slice())
            .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "AES-GCM decryption failed"))
    }
}

#[allow(private_bounds)]
impl<'a, A> BAESBlock<'a, BAESBlockAllocator<A>>
where
    A: BStackAllocator<Error = io::Error> + BStackRawAllocator,
    for<'b> A::Allocated<'b>: BlockStart + Copy,
{
    /// Reconstruct a block from a 16-byte array produced by
    /// [`BAESBlock::to_bytes`].
    pub fn from_bytes(allocator: &'a BAESBlockAllocator<A>, bytes: [u8; 16]) -> Self {
        let offset = u64::from_le_bytes(bytes[..8].try_into().unwrap());
        let len = u64::from_le_bytes(bytes[8..].try_into().unwrap());
        BAESBlock {
            slice: unsafe { BStackSlice::from_raw_parts(allocator, offset, len + AES_OVERHEAD) },
            len,
            key: allocator.key,
            nonce_gen: allocator.nonce_gen,
        }
    }
}

// ── View ─────────────────────────────────────────────────────────────────────

/// A read/write sub-range view over a [`BAESBlock`].
///
/// A full-range view is obtained via [`BAESBlock::view`];
/// a sub-range via [`BAESBlockView::subview`]. All coordinates are
/// **relative** to the current view's start.
///
/// ## Write semantics
///
/// Because AES-256-GCM is a full-block AEAD cipher, every write —
/// even a single byte — decrypts the full plaintext, patches the covered
/// range, and re-encrypts with a fresh nonce. The authentication tag always
/// covers the entire block.
///
/// ## `BStackGuardedSlice` and `BStackGuardedSliceSubview`
///
/// `BAESBlockView` implements [`bstack::BStackGuardedSlice`]: `write()`
/// and `zero()` operate on the view's sub-range while re-encrypting the full
/// block. `as_slice()` is intentionally unsupported. It also implements
/// [`bstack::BStackGuardedSliceSubview`] for use in generic guarded-I/O
/// contexts.
pub struct BAESBlockView<'a, A: BStackAllocator> {
    block: BAESBlock<'a, A>,
    start: u64,
    end: u64,
}

impl<'a, A: BStackAllocator> Copy for BAESBlockView<'a, A> {}

impl<'a, A: BStackAllocator> Clone for BAESBlockView<'a, A> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'a, A: BStackAllocator> fmt::Debug for BAESBlockView<'a, A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BAESBlockView")
            .field("start", &self.start)
            .field("end", &self.end)
            .finish_non_exhaustive()
    }
}

impl<'a, A: BStackAllocator> PartialEq for BAESBlockView<'a, A> {
    fn eq(&self, other: &Self) -> bool {
        self.block == other.block && self.start == other.start && self.end == other.end
    }
}

impl<'a, A: BStackAllocator> Eq for BAESBlockView<'a, A> {}

impl<'a, A: BStackAllocator> Hash for BAESBlockView<'a, A> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.block.hash(state);
        self.start.hash(state);
        self.end.hash(state);
    }
}

impl<'a, A: BStackAllocator> PartialOrd for BAESBlockView<'a, A> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl<'a, A: BStackAllocator> Ord for BAESBlockView<'a, A> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.block
            .cmp(&other.block)
            .then(self.start.cmp(&other.start))
            .then(self.end.cmp(&other.end))
    }
}

impl<'a, A: BStackAllocator> BAESBlockView<'a, A> {
    /// Return a view covering `[start, end)` within this view's coordinate space.
    ///
    /// Coordinates are relative: `subview(0, 3)` on a view starting at byte 5
    /// produces a view covering bytes 5–7 of the block's plaintext.
    pub fn subview(&self, start: u64, end: u64) -> Self {
        BAESBlockView {
            block: self.block,
            start: self.start + start,
            end: self.start + end,
        }
    }

    /// Return `true` if the block decrypts and authenticates successfully.
    pub fn verify(&self) -> io::Result<bool> {
        self.block.verify()
    }

    /// Decrypt and return the bytes covered by this view.
    pub fn read(&self) -> io::Result<Vec<u8>> {
        let plaintext = self.block.decrypt_read()?;
        Ok(plaintext[self.start as usize..self.end as usize].to_vec())
    }

    fn patch_and_encrypt(&self, data: &[u8]) -> io::Result<()> {
        let mut plaintext = self.block.decrypt_read()?;
        plaintext[self.start as usize..self.end as usize].copy_from_slice(data);
        self.block.encrypt_write(&plaintext)
    }

    fn zero_and_encrypt(&self) -> io::Result<()> {
        let mut plaintext = self.block.decrypt_read()?;
        plaintext[self.start as usize..self.end as usize].fill(0);
        self.block.encrypt_write(&plaintext)
    }
}

impl<'a, A: BStackAllocator + 'a> BStackGuardedSliceSubview<'a, A> for BAESBlockView<'a, A> {
    fn subview(&self, start: u64, end: u64) -> impl BStackGuardedSliceSubview<'a, A> + '_ {
        BAESBlockView {
            block: self.block,
            start: self.start + start,
            end: self.start + end,
        }
    }
}

impl<'a, A: BStackAllocator + 'a> BStackGuardedSlice<'a, A> for BAESBlockView<'a, A> {
    fn len(&self) -> u64 {
        self.end - self.start
    }

    unsafe fn raw_block(&self) -> BStackSlice<'a, A> {
        self.block.slice
    }

    // as_slice() left at default — ciphertext has no safe plaintext mapping

    fn write(&self, data: impl AsRef<[u8]>) -> io::Result<()> {
        self.patch_and_encrypt(data.as_ref())
    }

    fn zero(&self) -> io::Result<()> {
        self.zero_and_encrypt()
    }
}

// ── Reader ───────────────────────────────────────────────────────────────────

/// A cursor-based reader over the decrypted plaintext of a [`BAESBlock`].
///
/// The full plaintext is decrypted once at construction time and held in an
/// in-memory buffer.  `Read` and `Seek` operations work on that buffer; no
/// further I/O is performed.
///
/// Constructed via [`BAESBlock::reader`].
pub struct BAESBlockReader<'a, A: BStackAllocator> {
    buf: Vec<u8>,
    pos: usize,
    _marker: PhantomData<BAESBlock<'a, A>>,
}

impl<'a, A: BStackAllocator> fmt::Debug for BAESBlockReader<'a, A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BAESBlockReader")
            .field("len", &self.buf.len())
            .field("pos", &self.pos)
            .finish_non_exhaustive()
    }
}

impl<'a, A: BStackAllocator> io::Read for BAESBlockReader<'a, A> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        let remaining = self.buf.len().saturating_sub(self.pos);
        let n = buf.len().min(remaining);
        buf[..n].copy_from_slice(&self.buf[self.pos..self.pos + n]);
        self.pos += n;
        Ok(n)
    }
}

impl<'a, A: BStackAllocator> io::Seek for BAESBlockReader<'a, A> {
    fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
        let new_pos = match pos {
            io::SeekFrom::Start(n) => n as i64,
            io::SeekFrom::End(n) => self.buf.len() as i64 + n,
            io::SeekFrom::Current(n) => self.pos as i64 + n,
        };
        if new_pos < 0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "seek to negative position",
            ));
        }
        self.pos = new_pos as usize;
        Ok(self.pos as u64)
    }
}

// ── Writer ───────────────────────────────────────────────────────────────────

/// A buffered writer over the plaintext of a [`BAESBlock`].
///
/// On construction the current plaintext is decrypted into an in-memory
/// buffer.  `Write` and `Seek` operate on that buffer.  When
/// [`flush`](io::Write::flush) is called (or the writer is dropped), the
/// buffer is re-encrypted with a fresh nonce and written back to disk.
///
/// Drop silently discards flush errors; call [`flush`](io::Write::flush)
/// explicitly if you need to observe errors.
///
/// Constructed via [`BAESBlock::writer`].
pub struct BAESBlockWriter<'a, A: BStackAllocator> {
    block: BAESBlock<'a, A>,
    buf: Vec<u8>,
    pos: usize,
    dirty: bool,
}

impl<'a, A: BStackAllocator> fmt::Debug for BAESBlockWriter<'a, A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("BAESBlockWriter")
            .field("len", &self.buf.len())
            .field("pos", &self.pos)
            .field("dirty", &self.dirty)
            .finish_non_exhaustive()
    }
}

impl<'a, A: BStackAllocator> io::Write for BAESBlockWriter<'a, A> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        let remaining = self.buf.len().saturating_sub(self.pos);
        let n = buf.len().min(remaining);
        if n == 0 {
            return Ok(0);
        }
        self.buf[self.pos..self.pos + n].copy_from_slice(&buf[..n]);
        self.pos += n;
        self.dirty = true;
        Ok(n)
    }

    fn flush(&mut self) -> io::Result<()> {
        if self.dirty {
            self.block.encrypt_write(&self.buf)?;
            self.dirty = false;
        }
        Ok(())
    }
}

impl<'a, A: BStackAllocator> io::Seek for BAESBlockWriter<'a, A> {
    fn seek(&mut self, pos: io::SeekFrom) -> io::Result<u64> {
        let new_pos = match pos {
            io::SeekFrom::Start(n) => n as i64,
            io::SeekFrom::End(n) => self.buf.len() as i64 + n,
            io::SeekFrom::Current(n) => self.pos as i64 + n,
        };
        if new_pos < 0 {
            return Err(io::Error::new(
                io::ErrorKind::InvalidInput,
                "seek to negative position",
            ));
        }
        self.pos = new_pos as usize;
        Ok(self.pos as u64)
    }
}

impl<'a, A: BStackAllocator> Drop for BAESBlockWriter<'a, A> {
    fn drop(&mut self) {
        let _ = io::Write::flush(self);
    }
}

// ── BStackAllocator impl ─────────────────────────────────────────────────────

impl<A> BStackAllocator for BAESBlockAllocator<A>
where
    A: BStackAllocator<Error = io::Error> + BStackRawAllocator,
    for<'a> A::Allocated<'a>: BlockStart + Copy,
{
    type Error = io::Error;
    type Allocated<'a>
        = BAESBlock<'a, BAESBlockAllocator<A>>
    where
        A: 'a;

    fn stack(&self) -> &BStack {
        self.inner.stack()
    }

    fn into_stack(self) -> BStack {
        self.inner.into_stack()
    }

    fn alloc(&self, len: u64) -> io::Result<BAESBlock<'_, BAESBlockAllocator<A>>> {
        let inner = self.inner.alloc(len + AES_OVERHEAD)?;
        let offset = inner.block_start();
        let slice = unsafe { BStackSlice::from_raw_parts(self, offset, len + AES_OVERHEAD) };
        let block = BAESBlock {
            slice,
            len,
            key: self.key,
            nonce_gen: self.nonce_gen,
        };
        block.encrypt_write(&vec![0u8; len as usize])?;
        Ok(block)
    }

    fn realloc<'a>(
        &'a self,
        block: BAESBlock<'a, BAESBlockAllocator<A>>,
        new_len: u64,
    ) -> io::Result<BAESBlock<'a, BAESBlockAllocator<A>>> {
        let offset = block.slice.start();
        let inner_old_slice =
            unsafe { BStackSlice::from_raw_parts(&self.inner, offset, block.len + AES_OVERHEAD) };
        let inner_old: A::Allocated<'_> = unsafe { A::from_raw(inner_old_slice) };

        if new_len == block.len {
            let inner_new = self.inner.realloc(inner_old, new_len + AES_OVERHEAD)?;
            let new_offset = inner_new.block_start();
            let slice =
                unsafe { BStackSlice::from_raw_parts(self, new_offset, new_len + AES_OVERHEAD) };
            return Ok(BAESBlock {
                slice,
                len: new_len,
                key: block.key,
                nonce_gen: block.nonce_gen,
            });
        }

        let mut plaintext = block.decrypt_read()?;
        let inner_new = self.inner.realloc(inner_old, new_len + AES_OVERHEAD)?;
        let new_offset = inner_new.block_start();
        let new_slice =
            unsafe { BStackSlice::from_raw_parts(self, new_offset, new_len + AES_OVERHEAD) };
        let new_block = BAESBlock {
            slice: new_slice,
            len: new_len,
            key: block.key,
            nonce_gen: block.nonce_gen,
        };
        plaintext.resize(new_len as usize, 0);
        new_block.encrypt_write(&plaintext)?;
        Ok(new_block)
    }

    fn dealloc(&self, block: BAESBlock<'_, BAESBlockAllocator<A>>) -> io::Result<()> {
        let offset = block.slice.start();
        let inner_slice =
            unsafe { BStackSlice::from_raw_parts(&self.inner, offset, block.len + AES_OVERHEAD) };
        let inner: A::Allocated<'_> = unsafe { A::from_raw(inner_slice) };
        self.inner.dealloc(inner)
    }
}

impl<'a, A> TryInto<BStackSlice<'a, BAESBlockAllocator<A>>> for BAESBlock<'a, BAESBlockAllocator<A>>
where
    A: BStackAllocator<Error = io::Error> + BStackRawAllocator,
    for<'b> A::Allocated<'b>: BlockStart + Copy,
{
    type Error = std::convert::Infallible;

    fn try_into(self) -> Result<BStackSlice<'a, BAESBlockAllocator<A>>, Self::Error> {
        Ok(self.slice)
    }
}

impl<'a, A: BStackAllocator> BlockStart for BAESBlock<'a, A> {
    fn block_start(&self) -> u64 {
        self.slice.start()
    }
}

// ── BStackGuardedSlice impl ───────────────────────────────────────────────────

/// * `len()` returns the plaintext length.
/// * `write()` encrypts `data` with a fresh nonce and writes the full block.
/// * `zero()` encrypts a zero-filled buffer and writes the full block.
/// * `as_slice()` is intentionally unsupported (exposing ciphertext has no
///   useful plaintext semantics); the default implementation from bstack
///   signals this.
impl<'a, A: BStackAllocator + 'a> BStackGuardedSlice<'a, A> for BAESBlock<'a, A> {
    fn len(&self) -> u64 {
        self.len
    }

    unsafe fn raw_block(&self) -> BStackSlice<'a, A> {
        self.slice
    }

    fn write(&self, data: impl AsRef<[u8]>) -> io::Result<()> {
        self.encrypt_write(data.as_ref())
    }

    fn zero(&self) -> io::Result<()> {
        self.encrypt_write(&vec![0u8; self.len as usize])
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use bstack::{BStack, BStackAllocator, BStackGuardedSlice, LinearBStackAllocator};
    use std::io::{Read, Seek, SeekFrom, Write};
    use tempfile::NamedTempFile;

    fn counter_nonce() -> fn() -> [u8; 12] {
        use std::sync::atomic::{AtomicU64, Ordering};
        static CTR: AtomicU64 = AtomicU64::new(1);
        fn make_nonce() -> [u8; 12] {
            let n = CTR.fetch_add(1, Ordering::Relaxed);
            let mut out = [0u8; 12];
            out[..8].copy_from_slice(&n.to_le_bytes());
            out
        }
        make_nonce
    }

    fn make_allocator() -> (BAESBlockAllocator<LinearBStackAllocator>, NamedTempFile) {
        let file = NamedTempFile::new().unwrap();
        let stack = BStack::open(file.path()).unwrap();
        let key = [0x42u8; 32];
        let alloc =
            BAESBlockAllocator::new(LinearBStackAllocator::new(stack), key, counter_nonce());
        (alloc, file)
    }

    #[test]
    fn test_alloc_len() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(30).unwrap();
        assert_eq!(block.len(), 30);
        let raw_len = unsafe { block.into_slice().len() };
        assert_eq!(raw_len, 30 + AES_OVERHEAD);
    }

    #[test]
    fn test_write_and_read() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(5).unwrap();
        block.write(b"hello").unwrap();
        assert_eq!(block.read().unwrap(), b"hello");
    }

    #[test]
    fn test_verify_passes() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(5).unwrap();
        block.write(b"hello").unwrap();
        assert!(block.verify().unwrap());
    }

    #[test]
    fn test_verify_fails_after_raw_write() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(5).unwrap();
        block.write(b"hello").unwrap();
        let raw = unsafe { block.into_slice() };
        let ct_byte = raw.subslice(16, 17);
        let mut b = [0u8; 1];
        ct_byte.read_into(&mut b).unwrap();
        b[0] ^= 0xff;
        ct_byte.write(b).unwrap();
        assert!(!block.verify().unwrap());
    }

    #[test]
    fn test_wrong_algo_magic() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(4).unwrap();
        block.write(b"data").unwrap();
        unsafe { block.into_slice() }
            .subslice(0, 4)
            .write(*b"XXXX")
            .unwrap();
        assert!(!block.verify().unwrap());
    }

    #[test]
    fn test_zero_encrypts_zeros() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(6).unwrap();
        block.write(b"foobar").unwrap();
        block.zero().unwrap();
        assert_eq!(block.read().unwrap(), vec![0u8; 6]);
        assert!(block.verify().unwrap());
    }

    #[test]
    fn test_to_from_bytes() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(8).unwrap();
        block.write(&b"rustacean"[..8]).unwrap();
        let bytes: [u8; 16] = block.into();
        let block2 = BAESBlock::from_bytes(&alloc, bytes);
        assert_eq!(block2.len(), 8);
        assert!(block2.verify().unwrap());
        assert_eq!(block2.read().unwrap(), &b"rustacean"[..8]);
    }

    #[test]
    fn test_reader() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(4).unwrap();
        block.write(b"abcd").unwrap();
        let mut reader = block.reader().unwrap();
        let mut buf = [0u8; 4];
        reader.read_exact(&mut buf).unwrap();
        assert_eq!(&buf, b"abcd");
    }

    #[test]
    fn test_reader_seek() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(8).unwrap();
        block.write(b"abcdefgh").unwrap();
        let mut reader = block.reader().unwrap();
        reader.seek(SeekFrom::Start(4)).unwrap();
        let mut buf = [0u8; 4];
        reader.read_exact(&mut buf).unwrap();
        assert_eq!(&buf, b"efgh");
    }

    #[test]
    fn test_writer_flush() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(4).unwrap();
        {
            let mut w = block.writer().unwrap();
            w.write_all(b"WXYZ").unwrap();
            w.flush().unwrap();
        }
        assert!(block.verify().unwrap());
        assert_eq!(block.read().unwrap(), b"WXYZ");
    }

    #[test]
    fn test_writer_seek_and_overwrite() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(4).unwrap();
        {
            let mut w = block.writer().unwrap();
            w.write_all(b"abcd").unwrap();
            w.seek(SeekFrom::Start(2)).unwrap();
            w.write_all(b"XY").unwrap();
            w.flush().unwrap();
        }
        assert!(block.verify().unwrap());
        assert_eq!(block.read().unwrap(), b"abXY");
    }

    #[test]
    fn test_writer_drop_flushes() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(4).unwrap();
        {
            let mut w = block.writer().unwrap();
            w.write_all(b"drop").unwrap();
        }
        assert_eq!(block.read().unwrap(), b"drop");
    }

    #[test]
    fn test_realloc_same_size() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(4).unwrap();
        block.write(b"abcd").unwrap();
        let block2 = alloc.realloc(block, 4).unwrap();
        assert_eq!(block2.len(), 4);
        assert!(block2.verify().unwrap());
        assert_eq!(block2.read().unwrap(), b"abcd");
    }

    #[test]
    fn test_realloc_larger() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(4).unwrap();
        block.write(b"abcd").unwrap();
        let block2 = alloc.realloc(block, 8).unwrap();
        assert_eq!(block2.len(), 8);
        assert!(block2.verify().unwrap());
        let data = block2.read().unwrap();
        assert_eq!(&data[..4], b"abcd");
        assert_eq!(&data[4..], &[0u8; 4]);
    }

    #[test]
    fn test_realloc_smaller() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(8).unwrap();
        block.write(b"abcdefgh").unwrap();
        let block2 = alloc.realloc(block, 4).unwrap();
        assert_eq!(block2.len(), 4);
        assert!(block2.verify().unwrap());
        assert_eq!(block2.read().unwrap(), b"abcd");
    }

    #[test]
    fn test_view_read_full() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(8).unwrap();
        block.write(b"abcdefgh").unwrap();
        let view = block.view();
        assert_eq!(view.len(), 8);
        assert_eq!(view.read().unwrap(), b"abcdefgh");
    }

    #[test]
    fn test_view_read_subrange() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(8).unwrap();
        block.write(b"abcdefgh").unwrap();
        let sub = block.view().subview(2, 6);
        assert_eq!(sub.len(), 4);
        assert_eq!(sub.read().unwrap(), b"cdef");
    }

    #[test]
    fn test_view_write_subrange() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(8).unwrap();
        block.write(b"abcdefgh").unwrap();
        block.view().subview(2, 5).write(b"XYZ").unwrap();
        assert!(block.verify().unwrap());
        assert_eq!(block.read().unwrap(), b"abXYZfgh");
    }

    #[test]
    fn test_view_zero_subrange() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(8).unwrap();
        block.write(b"abcdefgh").unwrap();
        block.view().subview(3, 6).zero().unwrap();
        assert!(block.verify().unwrap());
        assert_eq!(block.read().unwrap(), b"abc\x00\x00\x00gh");
    }

    #[test]
    fn test_view_subview_nested() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(8).unwrap();
        block.write(b"abcdefgh").unwrap();
        // subview [2, 6) then [1, 3) of that → block bytes [3, 5)
        let sub = block.view().subview(2, 6).subview(1, 3);
        assert_eq!(sub.len(), 2);
        assert_eq!(sub.read().unwrap(), b"de");
        sub.write(b"XY").unwrap();
        assert!(block.verify().unwrap());
        assert_eq!(block.read().unwrap(), b"abcXYfgh");
    }

    #[test]
    fn test_view_verify() {
        let (alloc, _f) = make_allocator();
        let block = alloc.alloc(4).unwrap();
        block.write(b"test").unwrap();
        assert!(block.view().verify().unwrap());
        let raw = unsafe { block.into_slice() };
        let mut b = [0u8; 1];
        raw.subslice(16, 17).read_into(&mut b).unwrap();
        b[0] ^= 0xff;
        raw.subslice(16, 17).write(b).unwrap();
        assert!(!block.view().verify().unwrap());
    }
}