runsync-transfer 2026.1.0

High-throughput P2P file transfer engine: adaptive compression, end-to-end AEAD, parallel chunked pipeline over QUIC or any async transport.
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
//! End-to-end payload encryption, layered inside the transport's own TLS.
//!
//! Why a second layer at all: QUIC/TLS protects the hop. If a transfer is
//! relayed, or the far endpoint terminates TLS somewhere you do not control,
//! the relay sees plaintext. This layer is keyed by the two endpoints only, so
//! a relay forwards bytes it cannot read.
//!
//! Nonce discipline, which is the part that has to be exactly right:
//! every chunk is sealed under a per-file subkey with
//! `nonce = chunk_index (8 LE) || epoch (4 LE)`. `file_id` is unique within a
//! session and is bound into the subkey; `chunk_index` is unique within a file.
//! `epoch` increments when a chunk is re-encoded (a retry that changed the
//! compression decision), so the same (key, nonce) pair never covers two
//! different plaintexts. Session keys are ephemeral, so a resumed transfer
//! starts from fresh keys rather than replaying an old nonce space.

use crate::config::{Cipher, Secrecy};
use crate::error::{Error, Result};
use aes_gcm::aead::inout::InOutBuf;
use aes_gcm::aead::{AeadInOut, KeyInit};
use aes_gcm::Aes256Gcm;
use chacha20poly1305::ChaCha20Poly1305;
use hkdf::Hkdf;
use rand_core::RngCore;
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use zeroize::Zeroize;

pub const TAG_LEN: usize = 16;
pub const NONCE_LEN: usize = 12;
const KEY_LEN: usize = 32;
pub const HANDSHAKE_MSG_LEN: usize = 2 + 1 + 1 + 32 + 32 + 32;

const PROTOCOL_LABEL: &[u8] = b"runsync-transfer/v1";

/// Which side of the exchange we are. Decides key direction, nothing else.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Role {
    Initiator,
    Responder,
}

#[derive(Clone)]
struct Key([u8; KEY_LEN]);

impl Drop for Key {
    fn drop(&mut self) {
        self.0.zeroize();
    }
}

/// An AEAD instance, selected once per session.
#[derive(Clone)]
enum Aead {
    Aes(Box<Aes256Gcm>),
    ChaCha(Box<ChaCha20Poly1305>),
    /// Transport-only mode: bytes pass through untouched.
    Passthrough,
}

impl Aead {
    fn new(cipher: Cipher, key: &[u8; KEY_LEN]) -> Self {
        match resolve_cipher(cipher) {
            Cipher::Aes256Gcm => Aead::Aes(Box::new(Aes256Gcm::new(key.into()))),
            _ => Aead::ChaCha(Box::new(ChaCha20Poly1305::new(key.into()))),
        }
    }

    fn seal(&self, nonce: &[u8; NONCE_LEN], aad: &[u8], buf: &mut [u8]) -> Result<[u8; TAG_LEN]> {
        let tag = match self {
            Aead::Passthrough => return Ok([0u8; TAG_LEN]),
            Aead::Aes(c) => c
                .encrypt_inout_detached(nonce.into(), aad, InOutBuf::from(buf))
                .map_err(|_| Error::Handshake("aes-gcm seal failed".into()))?,
            Aead::ChaCha(c) => c
                .encrypt_inout_detached(nonce.into(), aad, InOutBuf::from(buf))
                .map_err(|_| Error::Handshake("chacha20 seal failed".into()))?,
        };
        let mut out = [0u8; TAG_LEN];
        out.copy_from_slice(&tag);
        Ok(out)
    }

    fn open(
        &self,
        nonce: &[u8; NONCE_LEN],
        aad: &[u8],
        buf: &mut [u8],
        tag: &[u8; TAG_LEN],
    ) -> std::result::Result<(), ()> {
        match self {
            Aead::Passthrough => Ok(()),
            Aead::Aes(c) => c
                .decrypt_inout_detached(nonce.into(), aad, InOutBuf::from(buf), tag.into())
                .map_err(|_| ()),
            Aead::ChaCha(c) => c
                .decrypt_inout_detached(nonce.into(), aad, InOutBuf::from(buf), tag.into())
                .map_err(|_| ()),
        }
    }
}

/// Which AEAD is actually faster in *this* binary, on *this* machine.
///
/// Measured rather than inferred, and the difference is not academic: whether
/// AES-GCM gets hardware acceleration depends on the backend crate version and
/// on build flags a library cannot control. Guessing from `target_arch` alone
/// once had us picking AES at 208 MB/s over ChaCha20 at 530 MB/s on the same
/// CPU. A 64 KiB timing run costs well under a millisecond and happens once per
/// process.
fn measured_preference() -> Cipher {
    static PREF: std::sync::OnceLock<Cipher> = std::sync::OnceLock::new();
    *PREF.get_or_init(|| {
        let key = [0x42u8; KEY_LEN];
        let nonce = [0u8; NONCE_LEN];
        let mut buf = vec![0u8; 64 * 1024];

        let bench = |a: &Aead, buf: &mut [u8]| -> u128 {
            // Warm the code paths and any lazily-built tables first.
            let _ = a.seal(&nonce, b"", buf);
            let t = std::time::Instant::now();
            for _ in 0..8 {
                let _ = a.seal(&nonce, b"", buf);
            }
            t.elapsed().as_nanos().max(1)
        };

        let aes = Aead::new(Cipher::Aes256Gcm, &key);
        let cha = Aead::new(Cipher::ChaCha20Poly1305, &key);
        let t_aes = bench(&aes, &mut buf);
        let t_cha = bench(&cha, &mut buf);

        if t_aes <= t_cha {
            Cipher::Aes256Gcm
        } else {
            Cipher::ChaCha20Poly1305
        }
    })
}

fn resolve_cipher(c: Cipher) -> Cipher {
    match c {
        Cipher::Auto => measured_preference(),
        other => other,
    }
}

fn cipher_id(c: Cipher) -> u8 {
    match resolve_cipher(c) {
        Cipher::Aes256Gcm => 1,
        _ => 2,
    }
}

fn cipher_from_id(id: u8) -> Result<Cipher> {
    match id {
        0 => Ok(Cipher::Auto),
        1 => Ok(Cipher::Aes256Gcm),
        2 => Ok(Cipher::ChaCha20Poly1305),
        other => Err(Error::Handshake(format!("unknown cipher id {other}"))),
    }
}

// ---------------------------------------------------------------------------
// Handshake
// ---------------------------------------------------------------------------

/// One side's in-progress key exchange. Built, written to the wire, then
/// finished with the peer's message.
pub struct Handshake {
    role: Role,
    secrecy: Secrecy,
    cipher: Cipher,
    // `StaticSecret` rather than `EphemeralSecret`: the key is used for more
    // than one Diffie-Hellman (ee, then es in static mode), which the
    // consume-on-use ephemeral type does not allow. It is still generated per
    // handshake and dropped with the `Handshake`, so it is ephemeral in fact.
    ephemeral: x25519_dalek::StaticSecret,
    our_msg: [u8; HANDSHAKE_MSG_LEN],
}

impl Handshake {
    pub fn new(role: Role, secrecy: &Secrecy, cipher: Cipher) -> Self {
        let ephemeral = x25519_dalek::StaticSecret::random_from_rng(rand_core::OsRng);
        let eph_pub = x25519_dalek::PublicKey::from(&ephemeral);

        let static_pub = match secrecy {
            Secrecy::Static { our_secret, .. } => {
                let s = x25519_dalek::StaticSecret::from(*our_secret);
                x25519_dalek::PublicKey::from(&s).to_bytes()
            }
            _ => [0u8; 32],
        };

        let mut salt = [0u8; 32];
        rand_core::OsRng.fill_bytes(&mut salt);

        let mut msg = [0u8; HANDSHAKE_MSG_LEN];
        msg[0..2].copy_from_slice(&crate::wire::WIRE_VERSION.to_le_bytes());
        msg[2] = cipher_id(cipher);
        msg[3] = match secrecy {
            Secrecy::TransportOnly => 0,
            Secrecy::Psk(_) => 1,
            Secrecy::Static { .. } => 2,
        };
        msg[4..36].copy_from_slice(eph_pub.as_bytes());
        msg[36..68].copy_from_slice(&static_pub);
        msg[68..100].copy_from_slice(&salt);

        Self {
            role,
            secrecy: secrecy.clone(),
            cipher,
            ephemeral,
            our_msg: msg,
        }
    }

    /// The bytes to send to the peer.
    pub fn message(&self) -> &[u8; HANDSHAKE_MSG_LEN] {
        &self.our_msg
    }

    /// Consume the peer's message and derive directional session keys.
    pub fn finish(self, peer_msg: &[u8]) -> Result<SessionCrypto> {
        if peer_msg.len() != HANDSHAKE_MSG_LEN {
            return Err(Error::Handshake(format!(
                "handshake message is {} bytes, expected {HANDSHAKE_MSG_LEN}",
                peer_msg.len()
            )));
        }
        let peer_version = u16::from_le_bytes([peer_msg[0], peer_msg[1]]);
        if peer_version != crate::wire::WIRE_VERSION {
            return Err(Error::Version {
                peer: peer_version,
                ours: crate::wire::WIRE_VERSION,
            });
        }

        let peer_mode = peer_msg[3];
        let our_mode = self.our_msg[3];
        if peer_mode != our_mode {
            // A downgrade to TransportOnly must not be something the peer can
            // pick unilaterally.
            return Err(Error::Handshake(format!(
                "secrecy mode mismatch: we offered {our_mode}, peer offered {peer_mode}"
            )));
        }

        // Both sides advertise a concrete cipher, resolved locally from `Auto`
        // or pinned by config. Agreement wins; disagreement falls back to
        // ChaCha20-Poly1305, which needs no hardware support and is fast
        // everywhere. Computed identically on both ends from the two advertised
        // bytes, so no extra round trip is needed — and a peer whose AES is a
        // software fallback can never drag us onto it.
        let peer_cipher = cipher_from_id(peer_msg[2])?;
        let ours = resolve_cipher(self.cipher);
        let negotiated = if ours == peer_cipher {
            ours
        } else {
            Cipher::ChaCha20Poly1305
        };

        let mut peer_eph = [0u8; 32];
        peer_eph.copy_from_slice(&peer_msg[4..36]);
        let peer_eph_pub = x25519_dalek::PublicKey::from(peer_eph);

        if matches!(self.secrecy, Secrecy::TransportOnly) {
            return Ok(SessionCrypto::passthrough());
        }

        // --- key material -------------------------------------------------
        let mut ikm: Vec<u8> = Vec::with_capacity(96);
        let dh_ee = self.ephemeral.diffie_hellman(&peer_eph_pub);
        if !dh_ee.was_contributory() {
            return Err(Error::Handshake(
                "peer sent a low-order X25519 point".into(),
            ));
        }
        ikm.extend_from_slice(dh_ee.as_bytes());

        if let Secrecy::Static {
            our_secret,
            peer_public,
        } = &self.secrecy
        {
            let mut claimed = [0u8; 32];
            claimed.copy_from_slice(&peer_msg[36..68]);
            // Pinned identity: reject anyone else before deriving anything.
            use subtle::ConstantTimeEq;
            if claimed.ct_eq(peer_public).unwrap_u8() != 1 {
                return Err(Error::Handshake(
                    "peer static public key does not match the pinned value".into(),
                ));
            }
            let our_static = x25519_dalek::StaticSecret::from(*our_secret);
            let peer_static_pub = x25519_dalek::PublicKey::from(*peer_public);

            // es and se, ordered by role so both sides build the same string.
            let dh_es = self.ephemeral.diffie_hellman(&peer_static_pub);
            let dh_se = our_static.diffie_hellman(&peer_eph_pub);
            let (first, second) = match self.role {
                Role::Initiator => (dh_es, dh_se),
                Role::Responder => (dh_se, dh_es),
            };
            ikm.extend_from_slice(first.as_bytes());
            ikm.extend_from_slice(second.as_bytes());
        }

        let salt: [u8; 32] = match &self.secrecy {
            Secrecy::Psk(k) => *k,
            _ => [0u8; 32],
        };

        // Bind both handshake messages into the transcript so neither side's
        // advertised version, cipher, or salt can be tampered with in flight.
        let (a, b) = match self.role {
            Role::Initiator => (&self.our_msg[..], peer_msg),
            Role::Responder => (peer_msg, &self.our_msg[..]),
        };
        let mut h = Sha256::new();
        h.update(PROTOCOL_LABEL);
        h.update(a);
        h.update(b);
        let transcript = h.finalize();

        let hk = Hkdf::<Sha256>::new(Some(&salt), &ikm);
        ikm.zeroize();

        let mut key_i2r = [0u8; KEY_LEN];
        let mut key_r2i = [0u8; KEY_LEN];
        expand(&hk, b"i2r", &transcript, &mut key_i2r)?;
        expand(&hk, b"r2i", &transcript, &mut key_r2i)?;

        let (send, recv) = match self.role {
            Role::Initiator => (key_i2r, key_r2i),
            Role::Responder => (key_r2i, key_i2r),
        };

        Ok(SessionCrypto {
            cipher: negotiated,
            send: Key(send),
            recv: Key(recv),
            passthrough: false,
        })
    }
}

fn expand(hk: &Hkdf<Sha256>, label: &[u8], transcript: &[u8], out: &mut [u8]) -> Result<()> {
    let mut info = Vec::with_capacity(PROTOCOL_LABEL.len() + 1 + label.len() + transcript.len());
    info.extend_from_slice(PROTOCOL_LABEL);
    info.push(b'/');
    info.extend_from_slice(label);
    info.extend_from_slice(transcript);
    hk.expand(&info, out)
        .map_err(|e| Error::Handshake(format!("hkdf expand: {e}")))
}

// ---------------------------------------------------------------------------
// Session
// ---------------------------------------------------------------------------

/// Derived session keys. Cheap to clone into per-worker sealers.
pub struct SessionCrypto {
    cipher: Cipher,
    send: Key,
    recv: Key,
    passthrough: bool,
}

impl SessionCrypto {
    fn passthrough() -> Self {
        Self {
            cipher: Cipher::ChaCha20Poly1305,
            send: Key([0u8; KEY_LEN]),
            recv: Key([0u8; KEY_LEN]),
            passthrough: true,
        }
    }

    pub fn is_passthrough(&self) -> bool {
        self.passthrough
    }

    /// Bytes added per chunk by the AEAD layer.
    pub fn overhead(&self) -> usize {
        if self.passthrough {
            0
        } else {
            TAG_LEN
        }
    }

    pub fn sealer(&self) -> Sealer {
        Sealer::new(self.cipher, &self.send, self.passthrough)
    }

    pub fn opener(&self) -> Sealer {
        Sealer::new(self.cipher, &self.recv, self.passthrough)
    }
}

/// Per-worker AEAD handle. Holds a small cache of per-file subkeys so a
/// multi-file transfer does not run HKDF on every chunk.
pub struct Sealer {
    cipher: Cipher,
    root: Key,
    passthrough: bool,
    files: HashMap<u32, Aead>,
}

impl Sealer {
    fn new(cipher: Cipher, root: &Key, passthrough: bool) -> Self {
        Self {
            cipher,
            root: root.clone(),
            passthrough,
            files: HashMap::new(),
        }
    }

    fn for_file(&mut self, file_id: u32) -> &Aead {
        // Bound the cache; a transfer of millions of tiny files would otherwise
        // hold a cipher instance per file for the life of the worker.
        if self.files.len() > 1024 {
            self.files.clear();
        }
        let cipher = self.cipher;
        let passthrough = self.passthrough;
        let root = self.root.0;
        self.files.entry(file_id).or_insert_with(|| {
            if passthrough {
                return Aead::Passthrough;
            }
            let hk = Hkdf::<Sha256>::from_prk(&root).expect("32-byte prk is valid");
            let mut info = Vec::with_capacity(PROTOCOL_LABEL.len() + 6 + 4);
            info.extend_from_slice(PROTOCOL_LABEL);
            info.extend_from_slice(b"/file");
            info.extend_from_slice(&file_id.to_le_bytes());
            let mut sub = [0u8; KEY_LEN];
            hk.expand(&info, &mut sub)
                .expect("32 bytes is under the hkdf limit");
            let a = Aead::new(cipher, &sub);
            sub.zeroize();
            a
        })
    }

    /// Encrypt `buf` in place and return the authentication tag.
    ///
    /// `aad` must be the exact frame header bytes: the header is authenticated
    /// but not encrypted, so a peer cannot redirect a chunk to a different
    /// file or offset without the tag failing.
    pub fn seal(
        &mut self,
        file_id: u32,
        chunk: u64,
        epoch: u32,
        aad: &[u8],
        buf: &mut [u8],
    ) -> Result<[u8; TAG_LEN]> {
        let nonce = nonce_for(chunk, epoch);
        self.for_file(file_id).seal(&nonce, aad, buf)
    }

    /// Decrypt `buf` in place, verifying `tag` against `aad`.
    pub fn open(
        &mut self,
        file_id: u32,
        chunk: u64,
        epoch: u32,
        aad: &[u8],
        buf: &mut [u8],
        tag: &[u8; TAG_LEN],
    ) -> Result<()> {
        let nonce = nonce_for(chunk, epoch);
        self.for_file(file_id)
            .open(&nonce, aad, buf, tag)
            .map_err(|_| Error::Decrypt { file_id, chunk })
    }

    pub fn is_passthrough(&self) -> bool {
        self.passthrough
    }

    pub fn overhead(&self) -> usize {
        if self.passthrough {
            0
        } else {
            TAG_LEN
        }
    }
}

impl Clone for Sealer {
    fn clone(&self) -> Self {
        // Subkey cache is per-worker state, not shared; start each clone empty.
        Self {
            cipher: self.cipher,
            root: self.root.clone(),
            passthrough: self.passthrough,
            files: HashMap::new(),
        }
    }
}

#[inline]
fn nonce_for(chunk: u64, epoch: u32) -> [u8; NONCE_LEN] {
    let mut n = [0u8; NONCE_LEN];
    n[0..8].copy_from_slice(&chunk.to_le_bytes());
    n[8..12].copy_from_slice(&epoch.to_le_bytes());
    n
}

/// Generate a random 32-byte key, for callers that want a PSK.
pub fn random_key() -> [u8; 32] {
    let mut k = [0u8; 32];
    rand_core::OsRng.fill_bytes(&mut k);
    k
}

/// Generate an X25519 identity as `(secret, public)`.
pub fn generate_identity() -> ([u8; 32], [u8; 32]) {
    let secret = x25519_dalek::StaticSecret::random_from_rng(rand_core::OsRng);
    let public = x25519_dalek::PublicKey::from(&secret);
    (secret.to_bytes(), public.to_bytes())
}

#[cfg(test)]
mod tests {
    use super::*;

    fn exchange(a_sec: &Secrecy, b_sec: &Secrecy) -> Result<(SessionCrypto, SessionCrypto)> {
        let a = Handshake::new(Role::Initiator, a_sec, Cipher::Auto);
        let b = Handshake::new(Role::Responder, b_sec, Cipher::Auto);
        let am = *a.message();
        let bm = *b.message();
        Ok((a.finish(&bm)?, b.finish(&am)?))
    }

    #[test]
    fn psk_handshake_produces_matched_directional_keys() {
        let psk = random_key();
        let (a, b) = exchange(&Secrecy::Psk(psk), &Secrecy::Psk(psk)).unwrap();
        assert!(!a.is_passthrough());

        let mut sealer = a.sealer();
        let mut opener = b.opener();
        let aad = b"header-bytes";
        let mut buf = b"the payload of a chunk".to_vec();
        let orig = buf.clone();
        let tag = sealer.seal(7, 42, 0, aad, &mut buf).unwrap();
        assert_ne!(buf, orig, "ciphertext must differ from plaintext");
        opener.open(7, 42, 0, aad, &mut buf, &tag).unwrap();
        assert_eq!(buf, orig);
    }

    #[test]
    fn wrong_psk_yields_keys_that_cannot_open() {
        let (a, b) = exchange(&Secrecy::Psk(random_key()), &Secrecy::Psk(random_key())).unwrap();
        let mut sealer = a.sealer();
        let mut opener = b.opener();
        let mut buf = b"secret".to_vec();
        let tag = sealer.seal(1, 0, 0, b"h", &mut buf).unwrap();
        assert!(opener.open(1, 0, 0, b"h", &mut buf, &tag).is_err());
    }

    #[test]
    fn static_identity_pinning_rejects_an_impostor() {
        let (a_sec, a_pub) = generate_identity();
        let (b_sec, b_pub) = generate_identity();
        let (impostor_sec, _) = generate_identity();

        exchange(
            &Secrecy::Static {
                our_secret: a_sec,
                peer_public: b_pub,
            },
            &Secrecy::Static {
                our_secret: b_sec,
                peer_public: a_pub,
            },
        )
        .expect("matching pins must succeed");

        let err = exchange(
            &Secrecy::Static {
                our_secret: a_sec,
                peer_public: b_pub,
            },
            &Secrecy::Static {
                our_secret: impostor_sec,
                peer_public: a_pub,
            },
        );
        assert!(
            err.is_err(),
            "an unpinned key must not complete the handshake"
        );
    }

    #[test]
    fn tampered_aad_fails_authentication() {
        let psk = random_key();
        let (a, b) = exchange(&Secrecy::Psk(psk), &Secrecy::Psk(psk)).unwrap();
        let mut sealer = a.sealer();
        let mut opener = b.opener();
        let mut buf = vec![0u8; 128];
        let tag = sealer.seal(3, 9, 0, b"file=3,chunk=9", &mut buf).unwrap();
        // Redirecting the chunk to another offset must be detected.
        assert!(opener
            .open(3, 9, 0, b"file=3,chunk=8", &mut buf, &tag)
            .is_err());
    }

    #[test]
    fn wrong_chunk_index_fails() {
        let psk = random_key();
        let (a, b) = exchange(&Secrecy::Psk(psk), &Secrecy::Psk(psk)).unwrap();
        let mut sealer = a.sealer();
        let mut opener = b.opener();
        let mut buf = vec![7u8; 64];
        let tag = sealer.seal(1, 100, 0, b"h", &mut buf).unwrap();
        assert!(opener.open(1, 101, 0, b"h", &mut buf, &tag).is_err());
        assert!(opener.open(2, 100, 0, b"h", &mut buf, &tag).is_err());
    }

    #[test]
    fn nonces_are_unique_across_chunk_and_epoch() {
        let mut seen = std::collections::HashSet::new();
        for chunk in 0..1000u64 {
            for epoch in 0..4u32 {
                assert!(seen.insert(nonce_for(chunk, epoch)), "nonce reuse");
            }
        }
    }

    #[test]
    fn mode_mismatch_is_rejected() {
        let r = exchange(&Secrecy::Psk(random_key()), &Secrecy::TransportOnly);
        assert!(r.is_err(), "peer must not be able to downgrade us");
    }

    fn exchange_with(
        a_cipher: Cipher,
        b_cipher: Cipher,
        psk: [u8; 32],
    ) -> Result<(SessionCrypto, SessionCrypto)> {
        let a = Handshake::new(Role::Initiator, &Secrecy::Psk(psk), a_cipher);
        let b = Handshake::new(Role::Responder, &Secrecy::Psk(psk), b_cipher);
        let (am, bm) = (*a.message(), *b.message());
        Ok((a.finish(&bm)?, b.finish(&am)?))
    }

    /// Whatever the two sides prefer, they must end up on the *same* AEAD —
    /// otherwise every chunk fails to open.
    #[test]
    fn peers_with_different_cipher_preferences_still_interoperate() {
        let psk = random_key();
        for (a, b) in [
            (Cipher::Aes256Gcm, Cipher::Aes256Gcm),
            (Cipher::ChaCha20Poly1305, Cipher::ChaCha20Poly1305),
            (Cipher::Aes256Gcm, Cipher::ChaCha20Poly1305),
            (Cipher::ChaCha20Poly1305, Cipher::Aes256Gcm),
            (Cipher::Auto, Cipher::Aes256Gcm),
            (Cipher::Auto, Cipher::ChaCha20Poly1305),
            (Cipher::Auto, Cipher::Auto),
        ] {
            let (sa, sb) = exchange_with(a, b, psk).unwrap();
            let mut sealer = sa.sealer();
            let mut opener = sb.opener();
            let plain = b"a chunk of payload bytes".to_vec();
            let mut buf = plain.clone();
            let tag = sealer.seal(5, 11, 0, b"aad", &mut buf).unwrap();
            opener
                .open(5, 11, 0, b"aad", &mut buf, &tag)
                .unwrap_or_else(|e| panic!("{a:?} vs {b:?} failed to interoperate: {e}"));
            assert_eq!(buf, plain, "{a:?} vs {b:?}");

            // ...and in the other direction too.
            let mut sealer = sb.sealer();
            let mut opener = sa.opener();
            let mut buf = plain.clone();
            let tag = sealer.seal(5, 12, 0, b"aad", &mut buf).unwrap();
            opener.open(5, 12, 0, b"aad", &mut buf, &tag).unwrap();
            assert_eq!(buf, plain);
        }
    }

    /// Disagreement resolves to ChaCha20-Poly1305, which needs no hardware
    /// support, rather than to whichever side spoke first.
    #[test]
    fn mismatched_preferences_fall_back_to_chacha() {
        let psk = random_key();
        let (sa, _sb) = exchange_with(Cipher::Aes256Gcm, Cipher::ChaCha20Poly1305, psk).unwrap();
        assert_eq!(sa.cipher, Cipher::ChaCha20Poly1305);
        let (sa, _sb) = exchange_with(Cipher::Aes256Gcm, Cipher::Aes256Gcm, psk).unwrap();
        assert_eq!(sa.cipher, Cipher::Aes256Gcm);
    }

    #[test]
    fn measured_preference_is_stable_and_concrete() {
        let a = measured_preference();
        let b = measured_preference();
        assert_eq!(a, b, "calibration must be cached, not re-run");
        assert_ne!(a, Cipher::Auto, "must resolve to a concrete cipher");
    }

    #[test]
    fn transport_only_is_passthrough() {
        let (a, b) = exchange(&Secrecy::TransportOnly, &Secrecy::TransportOnly).unwrap();
        assert!(a.is_passthrough() && b.is_passthrough());
        assert_eq!(a.overhead(), 0);
        let mut sealer = a.sealer();
        let mut buf = b"plain".to_vec();
        let tag = sealer.seal(0, 0, 0, b"", &mut buf).unwrap();
        assert_eq!(buf, b"plain");
        b.opener().open(0, 0, 0, b"", &mut buf, &tag).unwrap();
    }
}