Skip to main content

vector_core/crypto/
guarded_key.rs

1//! Memory-hardened key storage: 32 arrays of random-looking words with decoy writes, and a
2//! shielded key.
3//!
4//! The real 32-byte key is never stored. What is stored is the key XORed with
5//! BLAKE3(prekey), XOR-split into 4 shares (16 `usize` values on 64-bit) and scattered
6//! across 32 static arrays of 4,096 entries each. The prekey is 16 KiB of the arrays'
7//! own random fill: the key's lane row in 8 arrays (16 on 32-bit), which nothing writes while
8//! the key is live.
9//!
10//! Defense layers:
11//! 1. **Shielding**: the vault opens only with every one of the prekey's 131,072 bits
12//!    exact, so a noisy or partial capture of the vault (cold boot, Rowhammer/RAMBleed,
13//!    speculative leaks, torn dumps) gives an unrelated key.
14//! 2. **Secret splitting**: the shielded key is XOR-split into 4 shares
15//! 3. **32 alike arrays**: same size, all randomly filled, all receiving the same number of
16//!    decoys per set()/clear(). A single dump shows nothing that singles one out.
17//! 4. **No heap allocations**: zero pointers, zero mlock
18//! 5. **Scattered positions**: prekey rows, seed, multipliers and share data each sit at
19//!    (array, slot) positions derived from the ASLR instance address. The slot
20//!    dimension is partitioned into LANE_COUNT disjoint lanes; each live key owns one
21//!    lane (chosen at set() to differ from every live key's, its own included), so two
22//!    keys can never share a slot.
23//! 6. **Decoy writes**: during set()/clear(), every array receives random writes, so the
24//!    real ones hide among ~2,000 changed slots in a snapshot diff. Decoys keep off other
25//!    live keys' slots and prekey rows, so those rows go untouched in a diff: two snapshots
26//!    around a change show which lane and arrays another live key uses.
27//! 7. **Retire by prekey**: a replaced or cleared key's shares are left in place and its
28//!    prekey changed instead, and each set() draws a fresh seed, so no share slot is
29//!    rewritten across two diffs. Only a lane's seed slot is, each time a key returns to it.
30//! 8. **Zero writes on read**: a read only loads.
31//! 9. **No fixed layout constants**: multipliers and round counts derive from ASLR
32//!    addresses, and all modular arithmetic uses power-of-2 AND masks.
33//! 10. **No stack residue**: `read`, `with_key` and `with_keys` rebuild the key into one
34//!    buffer, run the caller's work on it, then zero the dead stack both used, so no copy
35//!    outlives the call: not a moved-from local, a secp256k1 scalar or BLAKE3's output.
36//!    `to_keys()` hands out an owned keypair, only where one must outlive the call.
37//!
38//! Security tiers:
39//!   **Without source code** (info-stealers, forensic tools): nothing marks the vault or
40//!   the key's place in it.
41//!
42//!   **Noisy or partial capture of the vault**: needs the full 16 KiB prekey bit-exact.
43//!
44//!   **Source code + snapshots of the vault alone, no load address**: the address is
45//!   guessed. Every key's layout follows from it, so one guess that fits any key opens
46//!   them all. A diff around any set() or clear() checks a guess without a hash or a curve
47//!   operation; a single snapshot needs both per guess.
48//!
49//!   **Source code + a clean, complete dump**: recoverable, as any in-process secret is.
50//!   A dump carries the image base, so the layout is one derivation away. The defence
51//!   here is the anti-debug layer (PT_DENY_ATTACH, PR_SET_DUMPABLE, DACL), which stops
52//!   the dump being taken.
53
54use std::sync::atomic::{fence, AtomicUsize, Ordering};
55use rand::RngCore;
56use zeroize::Zeroize;
57
58/// Entries per array — 4096 is common for crypto lookup tables (S-boxes, hash
59/// constants), maximizing false positives during memory scanning.
60const ARRAY_SIZE: usize = 4096;
61/// Total arrays: 3 config (seed, mul1, mul2) + 4 shares scattered across random arrays + decoys.
62/// Power-of-2: `% 32` compiles to `AND #0x1f` — hundreds of hits in any binary.
63/// Non-power-of-2 would use a unique magic-multiply constant (trivially searchable).
64const ARRAY_COUNT: usize = 32;
65/// Decoy writes per array per set()/clear(). With 32 arrays this keeps the 2,048 changed
66/// slots a snapshot diff must search the same as 128 arrays × 16 gave.
67const DECOYS_PER_ARRAY: usize = 64;
68/// Number of real XOR shares the key is split into.
69const NUM_SHARES: usize = 4;
70/// `usize` values per 32-byte share (4 on 64-bit, 8 on 32-bit).
71const USIZES_PER_SHARE: usize = 32 / std::mem::size_of::<usize>();
72/// Total entries used by one key's share data.
73const SHARE_ENTRIES: usize = NUM_SHARES * USIZES_PER_SHARE;
74/// Lane rows that make up one key's prekey: 16 KiB on 64-bit and on 32-bit alike.
75const PREKEY_ROWS: usize = 16 * 1024 / (LANE_WIDTH * std::mem::size_of::<usize>());
76// Retirement picks a prekey row with an AND mask, and the rows must leave arrays for shares.
77const _: () = assert!(PREKEY_ROWS.is_power_of_two() && PREKEY_ROWS < ARRAY_COUNT);
78
79/// Number of disjoint slot-lanes the slot dimension is partitioned into.
80/// Each live key occupies exactly one lane, so two keys in distinct lanes can
81/// never share an (array, slot) — eliminating cross-key write collisions without
82/// any coordination at read time. Power-of-2: `& (LANE_COUNT-1)` compiles to a
83/// plain AND mask (ubiquitous in any binary). 16 lanes ⇒ up to 16 concurrent keys
84/// (production uses 2). `LANE_WIDTH` = 256 slots ≫ the 19 positions a key needs.
85const LANE_COUNT: usize = 16;
86/// Slots per lane. `ARRAY_SIZE / LANE_COUNT`, power-of-2.
87const LANE_WIDTH: usize = ARRAY_SIZE / LANE_COUNT;
88
89/// 32 vault arrays — all identical, all randomly initialized, all modified during set().
90/// Memory: 32 × 4096 × size_of::<usize>() = 1 MiB on 64-bit, 512 KiB on 32-bit.
91static VAULTS: [[AtomicUsize; ARRAY_SIZE]; ARRAY_COUNT] = {
92    // Array-repeat seeds for this static only; each use is a fresh copy.
93    #[allow(clippy::declare_interior_mutable_const)]
94    const ZERO: AtomicUsize = AtomicUsize::new(0);
95    #[allow(clippy::declare_interior_mutable_const, clippy::large_const_arrays)]
96    const ROW: [AtomicUsize; ARRAY_SIZE] = [ZERO; ARRAY_SIZE];
97    [ROW; ARRAY_COUNT]
98};
99
100/// Initialize all arrays with random values (once per process).
101/// Every entry across all arrays is filled — real and decoy arrays are identical.
102fn ensure_vaults() {
103    if VAULTS[0][0].load(Ordering::Relaxed) == 0 {
104        fill_random(&VAULTS);
105    }
106}
107
108/// Fill every still-empty entry. Racing fillers keep whichever value lands first.
109fn fill_random(rows: &[[AtomicUsize; ARRAY_SIZE]]) {
110    let mut draws = Draws::new();
111    for row in rows {
112        for slot in row.iter() {
113            let _ = slot.compare_exchange(0, draws.next(), Ordering::SeqCst, Ordering::Relaxed);
114        }
115    }
116}
117
118/// Non-zero random words from a ChaCha20 keystream seeded once from the OS. Decoys and fills
119/// take thousands of words, and a syscall each dominated `set()`. Wiped on drop: whoever
120/// recovers this state could tell decoy writes from real ones.
121struct Draws {
122    cipher: chacha20::ChaCha20,
123    buf: [u64; 64],
124    at: usize,
125}
126
127impl Draws {
128    fn new() -> Self {
129        use chacha20::cipher::KeyIvInit;
130        let mut seed = [0u8; 44];
131        rand::rngs::OsRng.fill_bytes(&mut seed);
132        let cipher = chacha20::ChaCha20::new((&seed[..32]).into(), (&seed[32..]).into());
133        seed.zeroize();
134        Self { cipher, buf: [0; 64], at: 64 }
135    }
136
137    #[inline]
138    fn next(&mut self) -> usize {
139        use chacha20::cipher::StreamCipher;
140        if self.at == self.buf.len() {
141            self.buf = [0; 64];
142            // SAFETY: a [u64; 64] is 512 initialised bytes, viewed as bytes for the keystream.
143            let bytes = unsafe { std::slice::from_raw_parts_mut(self.buf.as_mut_ptr() as *mut u8, 512) };
144            self.cipher.apply_keystream(bytes);
145            self.at = 0;
146        }
147        let v = self.buf[self.at] as usize;
148        self.at += 1;
149        if v == 0 { 1 } else { v }
150    }
151}
152
153impl Drop for Draws {
154    fn drop(&mut self) {
155        self.buf.zeroize();
156    }
157}
158
159/// A position within the vault: (array index, slot index).
160#[derive(Clone, Copy, PartialEq)]
161#[cfg_attr(test, derive(Debug))]
162struct VaultPos {
163    array: usize,
164    slot: usize,
165}
166
167/// Derive the mixing iteration count from ASLR addresses — ZERO constants in the binary.
168/// Range: 16..31, changing every launch, so there is no fixed loop bound to search for. Not a
169/// work factor: a dump carries the image base, so an attacker runs this derivation once.
170#[inline]
171fn mix_iterations(instance_addr: usize) -> usize {
172    let base = VAULTS.as_ptr() as usize;
173    let h = (instance_addr ^ base).wrapping_mul(instance_addr | 1);
174    16 + ((h >> 7) & 15)
175}
176
177/// Hardened hash mixing — runtime-determined iterations of shift-multiply-XOR.
178/// ZERO compile-time constants — both multipliers AND iteration count derived
179/// from ASLR addresses. Compiles to a tight loop of generic MUL + EOR + LSR.
180#[inline]
181fn addr_mix(mut h: u64, m1: u64, m2: u64, iterations: usize) -> u64 {
182    for _ in 0..iterations {
183        h ^= h >> 33;
184        h = h.wrapping_mul(m1);
185        h ^= h >> 29;
186        h = h.wrapping_mul(m2);
187        h ^= h >> 31;
188    }
189    h
190}
191
192/// Map a raw hash to a slot inside `lane`'s disjoint slot-range.
193/// `slot = lane*LANE_WIDTH + (raw % LANE_WIDTH)` — distinct lanes never overlap.
194/// Both ops are AND masks (power-of-2), so this stays a generic AND/OR/SHIFT
195/// sequence with no searchable constants.
196#[inline]
197fn lane_slot(raw: usize, lane: usize) -> usize {
198    (lane << LANE_WIDTH.trailing_zeros()) | (raw & (LANE_WIDTH - 1))
199}
200
201/// Where one key lives in one lane: the arrays whose lane row is its prekey, and its 3
202/// configuration positions (seed, mul1, mul2), which never sit in a prekey array.
203struct Layout {
204    prekey: [usize; PREKEY_ROWS],
205    config: (VaultPos, VaultPos, VaultPos),
206}
207
208/// Derive a key's layout from the instance address. No dependency on stored values, which
209/// breaks the chicken-and-egg. Uses instance address + VAULTS base address (both ASLR'd,
210/// both change per launch); multipliers derive from the two, so no searchable constants.
211/// `lane` confines every slot to one of LANE_COUNT disjoint ranges.
212fn layout(instance_addr: usize, lane: usize) -> Layout {
213    layout_with(instance_addr, lane, mix_iterations(instance_addr))
214}
215
216fn layout_with(instance_addr: usize, lane: usize, iters: usize) -> Layout {
217    let base = VAULTS.as_ptr() as usize;
218    // Derive multipliers from ASLR addresses — forced odd for mixing quality.
219    let m1 = (instance_addr as u64) | 1;
220    let m2 = (base as u64) | 1;
221    let mut h = addr_mix((instance_addr as u64) ^ (base as u64).rotate_left(19), m1, m2, iters);
222
223    let mut prekey = [0usize; PREKEY_ROWS];
224    for i in 0..PREKEY_ROWS {
225        loop {
226            let candidate = ((h >> 32) as usize) & (ARRAY_COUNT - 1);
227            h = addr_mix(h, m1, m2, iters);
228            if !prekey[..i].contains(&candidate) {
229                prekey[i] = candidate;
230                break;
231            }
232        }
233    }
234
235    let mut positions = [VaultPos { array: 0, slot: 0 }; 3];
236    for i in 0..3 {
237        loop {
238            let candidate = VaultPos {
239                array: ((h >> 32) as usize) & (ARRAY_COUNT - 1),
240                slot: lane_slot(h as usize, lane),
241            };
242            h = addr_mix(h, m1, m2, iters);
243            if !positions[..i].contains(&candidate) && !prekey.contains(&candidate.array) {
244                positions[i] = candidate;
245                break;
246            }
247        }
248    }
249
250    Layout { prekey, config: (positions[0], positions[1], positions[2]) }
251}
252
253fn config_positions(instance_addr: usize, lane: usize) -> (VaultPos, VaultPos, VaultPos) {
254    layout(instance_addr, lane).config
255}
256
257/// Derive share data positions. Uses the seed + multipliers read from the vault
258/// (which are at config-derived positions) + instance address.
259/// `lane` confines the slot dimension to the key's disjoint lane (same lane as its
260/// config positions). Returns SHARE_ENTRIES (array, slot) pairs — each guaranteed
261/// unique and non-overlapping with config positions (rehash on collision).
262fn share_positions(instance_addr: usize, lane: usize) -> [VaultPos; SHARE_ENTRIES] {
263    share_positions_from(instance_addr, lane, &layout(instance_addr, lane))
264}
265
266fn share_positions_from(instance_addr: usize, lane: usize, layout: &Layout) -> [VaultPos; SHARE_ENTRIES] {
267    let (seed_pos, mul1_pos, mul2_pos) = layout.config;
268    let seed = VAULTS[seed_pos.array][seed_pos.slot].load(Ordering::Relaxed) as u64;
269    let mul1 = VAULTS[mul1_pos.array][mul1_pos.slot].load(Ordering::Relaxed) as u64;
270    let mul2 = VAULTS[mul2_pos.array][mul2_pos.slot].load(Ordering::Relaxed) as u64;
271
272    let mut h = seed ^ (instance_addr as u64).rotate_left(23);
273    let mut positions = [VaultPos { array: 0, slot: 0 }; SHARE_ENTRIES];
274    let config = [seed_pos, mul1_pos, mul2_pos];
275
276    for i in 0..SHARE_ENTRIES {
277        loop {
278            h ^= h >> 17;
279            h = h.wrapping_mul(mul1 | 1);
280            h ^= h >> 13;
281            h = h.wrapping_mul(mul2 | 1);
282            h ^= h >> 16;
283            let candidate = VaultPos {
284                array: ((h >> 32) as usize) & (ARRAY_COUNT - 1),
285                slot: lane_slot(h as usize, lane),
286            };
287            if !config.contains(&candidate)
288                && !positions[..i].contains(&candidate)
289                && !layout.prekey.contains(&candidate.array)
290            {
291                positions[i] = candidate;
292                break;
293            }
294            // Collision: hash state already advanced, loop retries with new h
295        }
296    }
297
298    positions
299}
300
301/// BLAKE3 of a key's prekey: its lane row in each of its prekey arrays, 16 KiB in all.
302/// Copied out with atomic loads (a writer may be mid-decoy; the epoch check discards that
303/// read) and wiped after.
304fn shield(lane: usize, prekey: &[usize; PREKEY_ROWS]) -> [u8; 32] {
305    let mut pad = [0u8; 32];
306    shield_into(lane, prekey, &mut pad);
307    pad
308}
309
310fn shield_into(lane: usize, prekey: &[usize; PREKEY_ROWS], out: &mut [u8; 32]) {
311    let mut buf = [0usize; PREKEY_ROWS * LANE_WIDTH];
312    for (row, &array) in buf.chunks_exact_mut(LANE_WIDTH).zip(prekey) {
313        let slots = &VAULTS[array][lane * LANE_WIDTH..(lane + 1) * LANE_WIDTH];
314        for (dst, slot) in row.iter_mut().zip(slots) {
315            *dst = slot.load(Ordering::Relaxed);
316        }
317    }
318    // SAFETY: an initialised local [usize] viewed as its bytes, for hashing only.
319    let bytes = unsafe {
320        std::slice::from_raw_parts(buf.as_ptr() as *const u8, std::mem::size_of_val(&buf))
321    };
322    *out = *blake3::hash(bytes).as_bytes();
323    buf.zeroize();
324}
325
326/// How far below a read [`scrub_below`] zeroes: past the deepest hot path, the read's 16 KiB
327/// prekey buffer and the closure together (`attack::stack_residue_by_path` measures them).
328const SCRUB_BYTES: usize = 32 * 1024;
329
330/// Zero the dead stack a read and its closure just used.
331#[inline(never)]
332fn scrub_below() {
333    let mut stack = std::mem::MaybeUninit::<[u8; SCRUB_BYTES]>::uninit();
334    // SAFETY: zeroes a local this frame owns; black_box keeps the writes from being elided.
335    unsafe { std::ptr::write_bytes(stack.as_mut_ptr(), 0, 1) };
336    std::hint::black_box(&mut stack);
337}
338
339/// Vault-wide seqlock: odd while a set() or clear() is rewriting, bumped past it after. A
340/// read that overlaps one starts again, so it never mixes old and new shares or prekeys.
341static EPOCH: AtomicUsize = AtomicUsize::new(0);
342
343/// The vault's write count: it moves on every set() and clear(), and is odd while one runs.
344/// Something derived from a key read under an even count is current while the count is unchanged.
345pub fn write_count() -> usize {
346    EPOCH.load(Ordering::Acquire)
347}
348
349/// Holds the epoch odd for one writer; even again on drop, panics included.
350struct Rewriting(usize);
351
352impl Rewriting {
353    fn begin() -> Self {
354        let epoch = EPOCH.load(Ordering::Relaxed);
355        EPOCH.store(epoch.wrapping_add(1), Ordering::Relaxed);
356        fence(Ordering::Release);
357        Self(epoch)
358    }
359}
360
361impl Drop for Rewriting {
362    fn drop(&mut self) {
363        EPOCH.store(self.0.wrapping_add(2), Ordering::Release);
364    }
365}
366
367/// Write DECOYS_PER_ARRAY random entries to EVERY array (real + decoy), excluding protected positions
368/// and the lane rows set in `rows` (bit `lane` of `rows[array]`). Both belong to other live keys.
369fn write_decoys(protected: &[VaultPos], rows: &[u16; ARRAY_COUNT], draws: &mut Draws) {
370    for (array_idx, row) in VAULTS.iter().enumerate() {
371        for _ in 0..DECOYS_PER_ARRAY {
372            let mut slot = draws.next() & (ARRAY_SIZE - 1);
373            while rows[array_idx] >> (slot / LANE_WIDTH) & 1 == 1
374                || protected.iter().any(|p| p.array == array_idx && p.slot == slot)
375            {
376                slot = draws.next() & (ARRAY_SIZE - 1);
377            }
378            row[slot].store(draws.next(), Ordering::Release);
379        }
380    }
381}
382
383/// A key being replaced or cleared. Its shares stay where they are: rewriting them would mark
384/// them in a diff against the dump before. Changing one prekey word is enough to make them
385/// useless, and the decoys all but always do that already.
386struct Retiring {
387    prekey: [usize; PREKEY_ROWS],
388    lane: usize,
389    pad: [u8; 32],
390}
391
392impl Retiring {
393    fn begin(instance_addr: usize, lane: usize) -> Self {
394        let prekey = layout(instance_addr, lane).prekey;
395        Self { pad: shield(lane, &prekey), prekey, lane }
396    }
397
398    fn finish(self, draws: &mut Draws) {
399        let mut now = shield(self.lane, &self.prekey);
400        if now == self.pad {
401            let slot = self.lane * LANE_WIDTH + (draws.next() & (LANE_WIDTH - 1));
402            VAULTS[self.prekey[draws.next() & (PREKEY_ROWS - 1)]][slot].store(draws.next(), Ordering::Release);
403        }
404        now.zeroize();
405    }
406}
407
408impl Drop for Retiring {
409    fn drop(&mut self) {
410        self.pad.zeroize();
411    }
412}
413
414/// Serialises every set() and clear(). Each one reads its partners' lanes once, so two running
415/// together could decoy over each other's fresh slots. Reads never take it.
416static WRITER: std::sync::Mutex<()> = std::sync::Mutex::new(());
417
418fn writer() -> std::sync::MutexGuard<'static, ()> {
419    WRITER.lock().unwrap_or_else(|e| e.into_inner())
420}
421
422/// Memory-hardened key vault backed by 32 indistinguishable static arrays.
423pub struct GuardedKey {
424    /// Non-zero when a key is stored. Stores a random non-zero value (not 0/1)
425    /// so it looks like any other random data in `__DATA`.
426    active: AtomicUsize,
427}
428
429/// The process's standing vaults, always kept clear of whatever a caller passes, then the
430/// caller's own, each once. A standing vault a call site forgets can't then share its lane.
431fn partners<'a>(others: &'a [&'a GuardedKey]) -> impl Iterator<Item = &'a GuardedKey> {
432    let standing: [&'static GuardedKey; 3] = [
433        &crate::state::ENCRYPTION_KEY,
434        &crate::state::MY_SECRET_KEY,
435        &crate::state::PREVIOUS_AT_REST_KEY,
436    ];
437    let mut seen: Vec<usize> = Vec::with_capacity(standing.len() + others.len());
438    standing.into_iter().chain(others.iter().copied()).filter(move |k| {
439        let addr = *k as *const GuardedKey as usize;
440        if seen.contains(&addr) {
441            false
442        } else {
443            seen.push(addr);
444            true
445        }
446    })
447}
448
449impl GuardedKey {
450    pub const fn empty() -> Self {
451        Self { active: AtomicUsize::new(0) }
452    }
453
454    #[inline]
455    fn instance_addr(&self) -> usize {
456        &self.active as *const _ as usize
457    }
458
459    /// The lane a marker maps to. Lanes partition the slot space; a key lives
460    /// entirely within one lane so it can never share a slot with a key in a
461    /// different lane. `& (LANE_COUNT-1)` is a plain AND mask.
462    #[inline]
463    fn lane_of(marker: usize) -> usize {
464        marker & (LANE_COUNT - 1)
465    }
466
467    /// This instance's current lane, read from its active marker (0 if empty).
468    #[inline]
469    fn lane(&self) -> usize {
470        Self::lane_of(self.active.load(Ordering::Acquire))
471    }
472
473    /// Pick a marker whose lane differs from every currently-live key's lane, this one's
474    /// included, so this key's positions stay disjoint from theirs and from its own old ones. `rng` supplies the random
475    /// marker; we reroll until its lane is free. With LANE_COUNT lanes and far fewer
476    /// concurrent keys, this terminates in ~1 try. The marker itself remains a
477    /// full-range random non-zero usize — the lane is an emergent low-bit property,
478    /// not separately stored, so it adds no searchable fingerprint.
479    fn pick_marker(&self, others: &[&GuardedKey], rng: &mut rand::rngs::OsRng) -> usize {
480        let mut taken = [false; LANE_COUNT];
481        if self.has_key() {
482            taken[self.lane()] = true;
483        }
484        for key in partners(others) {
485            if std::ptr::eq(key, self) || !key.has_key() { continue; }
486            taken[key.lane()] = true;
487        }
488        loop {
489            let mut marker = rng.next_u64() as usize;
490            if marker == 0 { marker = 1; }
491            if !taken[Self::lane_of(marker)] {
492                return marker;
493            }
494        }
495    }
496
497    /// Collect protected vault positions from other active GuardedKey instances.
498    /// Prevents write_decoys from corrupting another key's share/config data.
499    ///
500    /// `others` is a slice of references to other GuardedKey instances that share
501    /// the same VAULTS arrays. The caller is responsible for passing all other
502    /// active keys to ensure cross-key protection.
503    ///
504    /// Sized for up to LANE_COUNT live keys (the max that can coexist in distinct lanes).
505    /// Decoys roam every lane, so this exclusion is what keeps them off a partner's slots.
506    fn collect_other_protected(&self, others: &[&GuardedKey]) -> ([VaultPos; (3 + SHARE_ENTRIES) * LANE_COUNT], usize) {
507        let mut buf = [VaultPos { array: 0, slot: 0 }; (3 + SHARE_ENTRIES) * LANE_COUNT];
508        let mut n = 0;
509        for key in partners(others) {
510            if std::ptr::eq(key, self) || !key.has_key() { continue; }
511            if n + 3 + SHARE_ENTRIES > buf.len() { break; }
512            let addr = key.instance_addr();
513            let lane = key.lane();
514            let (s, m1, m2) = config_positions(addr, lane);
515            buf[n] = s; n += 1;
516            buf[n] = m1; n += 1;
517            buf[n] = m2; n += 1;
518            for &pos in share_positions(addr, lane).iter() {
519                buf[n] = pos;
520                n += 1;
521            }
522        }
523        (buf, n)
524    }
525
526    /// Lane rows holding another live key's prekey, as a lane bitmask per array.
527    fn other_prekey_rows(&self, others: &[&GuardedKey]) -> [u16; ARRAY_COUNT] {
528        let mut rows = [0u16; ARRAY_COUNT];
529        for key in partners(others) {
530            if std::ptr::eq(key, self) || !key.has_key() { continue; }
531            let lane = key.lane();
532            for array in layout(key.instance_addr(), lane).prekey {
533                rows[array] |= 1 << lane;
534            }
535        }
536        rows
537    }
538
539    /// Extract the secret key from a `Keys` struct, store it in the vault,
540    /// and zeroize the intermediate bytes. One-liner replacement for the
541    /// repeated extract -> set -> zeroize pattern across login paths.
542    ///
543    /// `others` is a slice of references to other active GuardedKey instances
544    /// for cross-key protection during decoy writes.
545    #[inline]
546    pub fn store_from_keys(&self, keys: &nostr_sdk::prelude::Keys, others: &[&GuardedKey]) {
547        let mut sk_bytes = keys.secret_key().secret_bytes();
548        self.set(sk_bytes, others);
549        sk_bytes.zeroize();
550    }
551
552    /// Store a key: shielded under its new lane's prekey, XOR-split into 4 shares
553    /// scattered across the arrays, with decoy writes to ALL arrays so real writes are
554    /// indistinguishable.
555    ///
556    /// INVARIANT: pass EVERY other live key (the standing vaults are always included). Decoys
557    /// keep off only the slots and prekey rows of the keys named here.
558    pub fn set(&self, mut key: [u8; 32], others: &[&GuardedKey]) {
559        let _writer = writer();
560        let mut rng = rand::rngs::OsRng;
561        let mut draws = Draws::new();
562        ensure_vaults();
563
564        // A fresh lane, free of every live key's including our own: new positions and a new
565        // prekey, while readers of the old key keep a consistent copy until the epoch moves.
566        let marker = self.pick_marker(others, &mut rng);
567        let lane = Self::lane_of(marker);
568
569        let old_marker = self.active.load(Ordering::Acquire);
570        let (protected, pcount) = self.collect_other_protected(others);
571        let rows = self.other_prekey_rows(others);
572        // Drawn before the window: nothing inside it may fail, or the epoch would stay odd and
573        // every read spin (a wasm panic aborts without running the guard's drop).
574        let mut splits = zeroize::Zeroizing::new([[0u8; 32]; NUM_SHARES - 1]);
575        for share in splits.iter_mut() {
576            rng.fill_bytes(share);
577        }
578        let rewriting = Rewriting::begin();
579        let retiring = (old_marker != 0).then(|| Retiring::begin(self.instance_addr(), Self::lane_of(old_marker)));
580
581        // Decoys first, our new prekey rows included. Real writes below overwrite any decoy
582        // that landed on OUR slots; every other key's slots and prekey rows are left alone.
583        write_decoys(&protected[..pcount], &rows, &mut draws);
584
585        // A fresh seed, so a lane this key held before never hands its shares the same slots:
586        // a slot rewritten in two diffs stands out. One random word, like any decoy.
587        let (seed_pos, _, _) = config_positions(self.instance_addr(), lane);
588        VAULTS[seed_pos.array][seed_pos.slot].store(draws.next(), Ordering::Relaxed);
589
590        Self::write_shielded(self.instance_addr(), lane, &mut key, &splits);
591
592        // Commit the lane-bearing marker. get() re-derives the same lane from it.
593        self.active.store(marker, Ordering::Release);
594
595        if let Some(retiring) = retiring {
596            retiring.finish(&mut draws);
597        }
598
599        drop(rewriting);
600    }
601
602    /// Shield `key` under `lane`'s prekey and write it as 4 shares, the first 3 being `splits`.
603    /// Wipes `key`.
604    fn write_shielded(instance_addr: usize, lane: usize, key: &mut [u8; 32], splits: &[[u8; 32]; NUM_SHARES - 1]) {
605        let layout = layout(instance_addr, lane);
606        let mut pad = shield(lane, &layout.prekey);
607        let mut shares = zeroize::Zeroizing::new([[0u8; 32]; NUM_SHARES]);
608        shares[..NUM_SHARES - 1].copy_from_slice(splits);
609        for j in 0..32 {
610            let mut last = key[j] ^ pad[j];
611            for share in shares.iter().take(NUM_SHARES - 1) {
612                last ^= share[j];
613            }
614            shares[NUM_SHARES - 1][j] = last;
615        }
616        key.zeroize();
617        pad.zeroize();
618
619        let positions = share_positions_from(instance_addr, lane, &layout);
620        for (share_idx, share) in shares.iter().enumerate() {
621            for u_idx in 0..USIZES_PER_SHARE {
622                let byte_off = u_idx * std::mem::size_of::<usize>();
623                let val = usize::from_ne_bytes(
624                    share[byte_off..byte_off + std::mem::size_of::<usize>()]
625                        .try_into().unwrap()
626                );
627                let pos = positions[share_idx * USIZES_PER_SHARE + u_idx];
628                VAULTS[pos.array][pos.slot].store(val, Ordering::Release);
629            }
630        }
631    }
632
633    /// Run `f` on the key, or on `None` when the vault is empty. The key is rebuilt into one
634    /// buffer `f` borrows, which is wiped when it returns, and then the stack both used is
635    /// zeroed: only what `f` returns or stores outlives the call. Zero writes to the vault.
636    pub fn read<R>(&self, f: impl FnOnce(Option<&[u8; 32]>) -> R) -> R {
637        let out = self.read_then(f);
638        scrub_below();
639        out
640    }
641
642    /// Never inlined, so the read and `f` run in frames below the caller's, where
643    /// [`scrub_below`] reaches the copies they leave: moved-from locals, secp256k1 scalars,
644    /// BLAKE3's output.
645    #[inline(never)]
646    fn read_then<R>(&self, f: impl FnOnce(Option<&[u8; 32]>) -> R) -> R {
647        let mut key = zeroize::Zeroizing::new([0u8; 32]);
648        let held = self.read_into(&mut key);
649        f(held.then_some(&*key))
650    }
651
652    /// [`Self::read`] for a vault expected to hold a key: `None` when it is empty.
653    pub fn with_key<R>(&self, f: impl FnOnce(&[u8; 32]) -> R) -> Option<R> {
654        self.read(|key| key.map(f))
655    }
656
657    /// [`Self::with_key`] as a keypair, dropped (and wiped) when `f` returns.
658    pub fn with_keys<R>(&self, f: impl FnOnce(&nostr_sdk::prelude::Keys) -> R) -> Option<R> {
659        use nostr_sdk::prelude::{Keys, SecretKey};
660        self.with_key(|key| SecretKey::from_slice(key).ok().map(|sk| f(&Keys::new(sk))))?
661    }
662
663    /// A copy of the key, for tests to compare.
664    #[cfg(any(test, feature = "bench"))]
665    pub(crate) fn get(&self) -> Option<[u8; 32]> {
666        self.with_key(|key| *key)
667    }
668
669    /// Rebuild the key into `out`; false when the vault is empty. A read that a set() or
670    /// clear() overlapped sees the epoch (or this key's marker) move and starts again, so it
671    /// never returns a mix of old and new shares or prekeys.
672    fn read_into(&self, out: &mut [u8; 32]) -> bool {
673        loop {
674            let epoch = EPOCH.load(Ordering::Acquire);
675            if epoch & 1 == 1 {
676                std::hint::spin_loop();
677                std::thread::yield_now();
678                continue;
679            }
680            let marker = self.active.load(Ordering::Acquire);
681            if marker == 0 {
682                return false;
683            }
684            self.read_shielded(marker, out);
685            fence(Ordering::Acquire);
686            if EPOCH.load(Ordering::Relaxed) == epoch && self.active.load(Ordering::Relaxed) == marker {
687                return true;
688            }
689            out.zeroize();
690        }
691    }
692
693    fn read_shielded(&self, marker: usize, key: &mut [u8; 32]) {
694        // Lane comes from the marker, so reads land on exactly the slots set() wrote.
695        let lane = Self::lane_of(marker);
696        let layout = layout(self.instance_addr(), lane);
697        let positions = share_positions_from(self.instance_addr(), lane, &layout);
698        shield_into(lane, &layout.prekey, key);
699
700        for (i, pos) in positions.iter().enumerate() {
701            let val = VAULTS[pos.array][pos.slot].load(Ordering::Acquire).to_ne_bytes();
702            let byte_off = (i % USIZES_PER_SHARE) * std::mem::size_of::<usize>();
703            for (a, b) in key[byte_off..byte_off + val.len()].iter_mut().zip(val) {
704                *a ^= b;
705            }
706        }
707    }
708
709    /// Clear the key: retire its prekey and write decoys to all arrays, keeping off every other
710    /// live key named in `others`.
711    pub fn clear(&self, others: &[&GuardedKey]) {
712        let _writer = writer();
713        if self.active.load(Ordering::Acquire) == 0 {
714            return;
715        }
716        let mut draws = Draws::new();
717        let rows = self.other_prekey_rows(others);
718        let (protected, pcount) = self.collect_other_protected(others);
719        let rewriting = Rewriting::begin();
720
721        let old_marker = self.active.swap(0, Ordering::SeqCst);
722        let retiring = Retiring::begin(self.instance_addr(), Self::lane_of(old_marker));
723        write_decoys(&protected[..pcount], &rows, &mut draws);
724        retiring.finish(&mut draws);
725        drop(rewriting);
726    }
727
728    pub fn has_key(&self) -> bool {
729        self.active.load(Ordering::Acquire) != 0
730    }
731
732    /// An owned keypair, for an object that must keep one past the call (a NIP-46 client).
733    /// Its moves leave copies nothing wipes, so shipping code marks each use `// owned-key:`
734    /// (`vault_audit` enforces it); everything else uses [`Self::with_keys`].
735    pub fn to_keys(&self) -> Option<nostr_sdk::prelude::Keys> {
736        use nostr_sdk::prelude::{Keys, SecretKey};
737        self.with_key(|key| SecretKey::from_slice(key).ok().map(Keys::new))?
738    }
739}
740
741// ============================================================================
742// Tests
743// ============================================================================
744
745#[cfg(any(test, feature = "bench"))]
746mod fixtures;
747#[cfg(feature = "bench")]
748#[doc(hidden)]
749pub mod bench;
750#[cfg(test)]
751mod attack;
752
753#[cfg(test)]
754mod tests {
755    use super::*;
756
757    // Test-local key statics (replaces crate::MY_SECRET_KEY / crate::ENCRYPTION_KEY)
758    static TEST_KEY_A: GuardedKey = GuardedKey::empty();
759    static TEST_KEY_B: GuardedKey = GuardedKey::empty();
760
761    // SERIALIZE on the crate-wide `DB_TEST_GUARD` — NOT a vault-local lock. The `VAULTS` arrays are
762    // ONE process-global shared by EVERY GuardedKey, including the production `MY_SECRET_KEY` /
763    // `ENCRYPTION_KEY` that other tests write via `init_test_db` (which holds `DB_TEST_GUARD`). Those
764    // writers pass only their partner in `others`, so their decoys/lane don't know about TEST_KEY_A/B and
765    // would clobber them if run concurrently — the cause of the cross-key flake. Sharing the same guard
766    // makes all vault-touching vector-core tests mutually exclusive. (Production is unaffected: its two
767    // keys are always mutually `others`-aware, verified across every login/clear path. Poison-tolerant
768    // via `into_inner` so one test panic doesn't cascade poison across the suite.)
769
770    /// Fast reset: mark both test keys inactive without full clear overhead.
771    fn reset() {
772        TEST_KEY_A.active.store(0, Ordering::SeqCst);
773        TEST_KEY_B.active.store(0, Ordering::SeqCst);
774        ensure_vaults();
775    }
776
777    /// Helper: the "others" slice for TEST_KEY_A (protects TEST_KEY_B).
778    fn others_for_a() -> [&'static GuardedKey; 1] {
779        [&TEST_KEY_B]
780    }
781
782    /// Helper: the "others" slice for TEST_KEY_B (protects TEST_KEY_A).
783    fn others_for_b() -> [&'static GuardedKey; 1] {
784        [&TEST_KEY_A]
785    }
786
787    /// Generate a deterministic test key from a seed byte.
788    fn test_key(seed: u8) -> [u8; 32] {
789        let mut k = [0u8; 32];
790        for (i, b) in k.iter_mut().enumerate() {
791            *b = seed.wrapping_add(i as u8).wrapping_mul(37).wrapping_add(7);
792        }
793        k
794    }
795
796    // ================================================================
797    // Basic operations
798    // ================================================================
799
800    #[test]
801    fn set_get_roundtrip() {
802        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
803        reset();
804        let key = test_key(42);
805        TEST_KEY_A.set(key, &others_for_a());
806        assert_eq!(TEST_KEY_A.get(), Some(key));
807    }
808
809    #[test]
810    fn set_get_1000_iterations() {
811        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
812        for i in 0..1000u16 {
813            reset();
814            let key = test_key((i ^ (i >> 3)) as u8);
815            TEST_KEY_A.set(key, &others_for_a());
816            assert_eq!(
817                TEST_KEY_A.get(), Some(key),
818                "Roundtrip failed at iteration {i}"
819            );
820        }
821    }
822
823    #[test]
824    fn empty_returns_none() {
825        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
826        reset();
827        assert_eq!(TEST_KEY_A.get(), None);
828        assert_eq!(TEST_KEY_B.get(), None);
829    }
830
831    #[test]
832    fn has_key_lifecycle() {
833        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
834        reset();
835        assert!(!TEST_KEY_A.has_key());
836        TEST_KEY_A.set(test_key(1), &others_for_a());
837        assert!(TEST_KEY_A.has_key());
838        TEST_KEY_A.clear(&others_for_a());
839        assert!(!TEST_KEY_A.has_key());
840    }
841
842    #[test]
843    fn clear_returns_none() {
844        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
845        reset();
846        TEST_KEY_A.set(test_key(99), &others_for_a());
847        assert!(TEST_KEY_A.get().is_some());
848        TEST_KEY_A.clear(&others_for_a());
849        assert_eq!(TEST_KEY_A.get(), None);
850    }
851
852    #[test]
853    fn set_overwrites_previous() {
854        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
855        reset();
856        let a = test_key(10);
857        let b = test_key(20);
858        TEST_KEY_A.set(a, &others_for_a());
859        assert_eq!(TEST_KEY_A.get(), Some(a));
860        TEST_KEY_A.set(b, &others_for_a());
861        assert_eq!(TEST_KEY_A.get(), Some(b));
862    }
863
864    #[test]
865    fn clear_idempotent() {
866        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
867        reset();
868        TEST_KEY_A.clear(&others_for_a());
869        TEST_KEY_A.clear(&others_for_a());
870        assert_eq!(TEST_KEY_A.get(), None);
871        TEST_KEY_A.set(test_key(5), &others_for_a());
872        TEST_KEY_A.clear(&others_for_a());
873        TEST_KEY_A.clear(&others_for_a());
874        assert_eq!(TEST_KEY_A.get(), None);
875    }
876
877    #[test]
878    fn encryption_key_basic() {
879        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
880        reset();
881        let key = test_key(0xEE);
882        TEST_KEY_B.set(key, &others_for_b());
883        assert_eq!(TEST_KEY_B.get(), Some(key));
884        TEST_KEY_B.clear(&others_for_b());
885        assert_eq!(TEST_KEY_B.get(), None);
886    }
887
888    // ================================================================
889    // Cross-key protection — 500 iterations each.
890    // Two keys live in disjoint lanes and decoys keep off each other's slots, so
891    // neither key's writes (decoys, seed, shares) can ever land on the other's.
892    // ================================================================
893
894    #[test]
895    fn cross_key_set_then_set_500() {
896        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
897        let key_a = test_key(0xAA);
898        let key_b = test_key(0xBB);
899        for i in 0..500 {
900            reset();
901            TEST_KEY_A.set(key_a, &others_for_a());
902            TEST_KEY_B.set(key_b, &others_for_b());
903            assert_eq!(
904                TEST_KEY_A.get(), Some(key_a),
905                "TEST_KEY_A corrupted at iteration {i}"
906            );
907            assert_eq!(
908                TEST_KEY_B.get(), Some(key_b),
909                "TEST_KEY_B corrupted at iteration {i}"
910            );
911        }
912    }
913
914    #[test]
915    fn cross_key_reverse_order_500() {
916        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
917        let key_a = test_key(0xCC);
918        let key_b = test_key(0xDD);
919        for i in 0..500 {
920            reset();
921            TEST_KEY_B.set(key_b, &others_for_b());
922            TEST_KEY_A.set(key_a, &others_for_a());
923            assert_eq!(
924                TEST_KEY_B.get(), Some(key_b),
925                "TEST_KEY_B corrupted at iteration {i}"
926            );
927            assert_eq!(
928                TEST_KEY_A.get(), Some(key_a),
929                "TEST_KEY_A corrupted at iteration {i}"
930            );
931        }
932    }
933
934    #[test]
935    fn cross_key_clear_preserves_other_500() {
936        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
937        let key_a = test_key(0x11);
938        let key_b = test_key(0x22);
939        for i in 0..500 {
940            // Clear TEST_KEY_A, verify TEST_KEY_B survives
941            reset();
942            TEST_KEY_A.set(key_a, &others_for_a());
943            TEST_KEY_B.set(key_b, &others_for_b());
944            TEST_KEY_A.clear(&others_for_a());
945            assert_eq!(
946                TEST_KEY_B.get(), Some(key_b),
947                "KEY_B corrupted after KEY_A.clear() at iteration {i}"
948            );
949            // Clear TEST_KEY_B, verify TEST_KEY_A survives
950            reset();
951            TEST_KEY_A.set(key_a, &others_for_a());
952            TEST_KEY_B.set(key_b, &others_for_b());
953            TEST_KEY_B.clear(&others_for_b());
954            assert_eq!(
955                TEST_KEY_A.get(), Some(key_a),
956                "KEY_A corrupted after KEY_B.clear() at iteration {i}"
957            );
958        }
959    }
960
961    #[test]
962    fn cross_key_alternating_500() {
963        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
964        for i in 0..500u16 {
965            reset();
966            let ka = test_key(i as u8);
967            let kb = test_key(!(i as u8));
968            TEST_KEY_A.set(ka, &others_for_a());
969            TEST_KEY_B.set(kb, &others_for_b());
970            assert_eq!(TEST_KEY_A.get(), Some(ka), "KEY_A wrong at iter {i}");
971            assert_eq!(TEST_KEY_B.get(), Some(kb), "KEY_B wrong at iter {i}");
972            TEST_KEY_A.clear(&others_for_a());
973            assert_eq!(TEST_KEY_B.get(), Some(kb), "KEY_B wrong after KEY_A clear at iter {i}");
974        }
975    }
976
977    /// Stress: alternating set order, different keys each round, 1000 iterations.
978    /// Two keys occupy disjoint lanes, so a real write from one can never clobber the
979    /// other's share slots regardless of decoy layout.
980    #[test]
981    fn stress_both_keys_1000() {
982        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
983        for i in 0..1000u32 {
984            reset();
985            let ka = test_key((i & 0xFF) as u8);
986            let kb = test_key(!((i & 0xFF) as u8));
987            if i % 2 == 0 {
988                TEST_KEY_A.set(ka, &others_for_a());
989                TEST_KEY_B.set(kb, &others_for_b());
990            } else {
991                TEST_KEY_B.set(kb, &others_for_b());
992                TEST_KEY_A.set(ka, &others_for_a());
993            }
994            assert_eq!(TEST_KEY_A.get(), Some(ka), "KEY_A wrong at iter {i}");
995            assert_eq!(TEST_KEY_B.get(), Some(kb), "KEY_B wrong at iter {i}");
996        }
997    }
998
999    // ================================================================
1000    // Position derivation
1001    // ================================================================
1002
1003    #[test]
1004    fn config_positions_all_unique() {
1005        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1006        ensure_vaults();
1007        for lane in 0..LANE_COUNT {
1008            for addr in (0x1000..0x2000usize).step_by(8) {
1009                let (a, b, c) = config_positions(addr, lane);
1010                assert_ne!(a, b, "config collision a==b at addr {addr:#x} lane {lane}");
1011                assert_ne!(a, c, "config collision a==c at addr {addr:#x} lane {lane}");
1012                assert_ne!(b, c, "config collision b==c at addr {addr:#x} lane {lane}");
1013            }
1014        }
1015    }
1016
1017    #[test]
1018    fn share_positions_all_unique() {
1019        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1020        ensure_vaults();
1021        for lane in 0..LANE_COUNT {
1022            for addr in (0x2000..0x2100usize).step_by(8) {
1023                let positions = share_positions(addr, lane);
1024                for i in 0..SHARE_ENTRIES {
1025                    for j in (i + 1)..SHARE_ENTRIES {
1026                        assert_ne!(
1027                            positions[i], positions[j],
1028                            "share collision [{i}]==[{j}] at addr {addr:#x} lane {lane}"
1029                        );
1030                    }
1031                }
1032            }
1033        }
1034    }
1035
1036    /// A standing vault keeps its lane even when a set or clear elsewhere doesn't name it.
1037    #[test]
1038    fn a_standing_vault_survives_sets_that_forget_it() {
1039        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1040        let standing = &crate::state::PREVIOUS_AT_REST_KEY;
1041        standing.set([0xAB; 32], &[]);
1042        for i in 0..64u8 {
1043            let other = GuardedKey::empty();
1044            other.set([i; 32], &[]);
1045            assert_ne!(other.lane(), standing.lane());
1046            other.clear(&[]);
1047        }
1048        assert_eq!(standing.get(), Some([0xAB; 32]));
1049        standing.clear(&[]);
1050    }
1051
1052    #[test]
1053    fn share_positions_no_config_overlap() {
1054        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1055        ensure_vaults();
1056        for lane in 0..LANE_COUNT {
1057            for addr in (0x3000..0x3100usize).step_by(8) {
1058                let (s, m1, m2) = config_positions(addr, lane);
1059                let config = [s, m1, m2];
1060                let shares = share_positions(addr, lane);
1061                for (i, pos) in shares.iter().enumerate() {
1062                    assert!(
1063                        !config.contains(pos),
1064                        "share[{i}] collides with config at addr {addr:#x} lane {lane}"
1065                    );
1066                }
1067            }
1068        }
1069    }
1070
1071    /// Distinct lanes are physically disjoint: no (array, slot) is shared between
1072    /// two different lanes for the same address. This is the property that makes
1073    /// cross-key writes collision-safe.
1074    #[test]
1075    fn distinct_lanes_are_disjoint() {
1076        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1077        ensure_vaults();
1078        for addr in (0x5000..0x5100usize).step_by(8) {
1079            for la in 0..LANE_COUNT {
1080                for lb in 0..LANE_COUNT {
1081                    if la == lb { continue; }
1082                    let (sa, m1a, m2a) = config_positions(addr, la);
1083                    let a_all: Vec<VaultPos> = [sa, m1a, m2a]
1084                        .into_iter()
1085                        .chain(share_positions(addr, la))
1086                        .collect();
1087                    let (sb, m1b, m2b) = config_positions(addr, lb);
1088                    let b_all: Vec<VaultPos> = [sb, m1b, m2b]
1089                        .into_iter()
1090                        .chain(share_positions(addr, lb))
1091                        .collect();
1092                    for p in &a_all {
1093                        assert!(
1094                            !b_all.contains(p),
1095                            "lane {la} and lane {lb} share {p:?} at addr {addr:#x}"
1096                        );
1097                    }
1098                }
1099            }
1100        }
1101    }
1102
1103    #[test]
1104    fn positions_deterministic() {
1105        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1106        ensure_vaults();
1107        let addr = TEST_KEY_A.instance_addr();
1108        let cfg1 = config_positions(addr, 3);
1109        let cfg2 = config_positions(addr, 3);
1110        assert_eq!(cfg1, cfg2);
1111        let sp1 = share_positions(addr, 3);
1112        let sp2 = share_positions(addr, 3);
1113        assert_eq!(sp1, sp2);
1114    }
1115
1116    #[test]
1117    fn all_positions_in_bounds() {
1118        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1119        ensure_vaults();
1120        for lane in 0..LANE_COUNT {
1121            for addr in (0x4000..0x4200usize).step_by(8) {
1122                let (a, b, c) = config_positions(addr, lane);
1123                for p in [a, b, c] {
1124                    assert!(p.array < ARRAY_COUNT);
1125                    assert!(p.slot < ARRAY_SIZE);
1126                }
1127                for p in share_positions(addr, lane) {
1128                    assert!(p.array < ARRAY_COUNT);
1129                    assert!(p.slot < ARRAY_SIZE);
1130                }
1131            }
1132        }
1133    }
1134
1135    // ================================================================
1136    // Internals
1137    // ================================================================
1138
1139    #[test]
1140    fn mix_iterations_in_range() {
1141        for addr in 0..10000usize {
1142            let n = mix_iterations(addr);
1143            assert!((16..=31).contains(&n), "mix_iterations({addr}) = {n}");
1144        }
1145    }
1146
1147    #[test]
1148    fn addr_mix_zero_iterations_is_identity() {
1149        let h: u64 = 0xDEADBEEFCAFEBABE;
1150        assert_eq!(addr_mix(h, 123, 456, 0), h);
1151    }
1152
1153    #[test]
1154    fn addr_mix_varies_output() {
1155        let a = addr_mix(1, 3, 5, 10);
1156        let b = addr_mix(2, 3, 5, 10);
1157        let c = addr_mix(1, 7, 5, 10);
1158        let d = addr_mix(1, 3, 11, 10);
1159        assert_ne!(a, b);
1160        assert_ne!(a, c);
1161        assert_ne!(a, d);
1162    }
1163
1164    #[test]
1165    fn ensure_vaults_all_nonzero() {
1166        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1167        ensure_vaults();
1168        for (r, row) in VAULTS.iter().enumerate() {
1169            for (s, slot) in row.iter().enumerate() {
1170                assert_ne!(
1171                    slot.load(Ordering::Relaxed), 0,
1172                    "VAULTS[{r}][{s}] is zero after ensure_vaults"
1173                );
1174            }
1175        }
1176    }
1177
1178    #[test]
1179    fn ensure_vaults_idempotent() {
1180        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1181        ensure_vaults();
1182        let samples: Vec<_> = (0..20)
1183            .map(|i| {
1184                let r = i * 13 % ARRAY_COUNT;
1185                let s = i * 397 % ARRAY_SIZE;
1186                (r, s, VAULTS[r][s].load(Ordering::Relaxed))
1187            })
1188            .collect();
1189        ensure_vaults();
1190        for (r, s, val) in &samples {
1191            assert_eq!(
1192                VAULTS[*r][*s].load(Ordering::Relaxed), *val,
1193                "ensure_vaults changed VAULTS[{r}][{s}]"
1194            );
1195        }
1196    }
1197
1198    /// Run write_decoys 500 times with protected positions — verify they are NEVER overwritten.
1199    /// Without exclusion, P(at least one hit) per position ~ 99.96%, so a broken exclusion is
1200    /// caught with near-certainty.
1201    #[test]
1202    fn write_decoys_respects_exclusions_500() {
1203        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1204        ensure_vaults();
1205        let protected = [
1206            VaultPos { array: 0, slot: 100 },
1207            VaultPos { array: 0, slot: 200 },
1208            VaultPos { array: 13, slot: 2000 },
1209            VaultPos { array: 13, slot: 3000 },
1210            VaultPos { array: 25, slot: 500 },
1211            VaultPos { array: 31, slot: 4095 },
1212        ];
1213        let before: Vec<usize> = protected.iter()
1214            .map(|p| VAULTS[p.array][p.slot].load(Ordering::Relaxed))
1215            .collect();
1216        for _ in 0..500 {
1217            write_decoys(&protected, &[0; ARRAY_COUNT], &mut Draws::new());
1218        }
1219        for (i, p) in protected.iter().enumerate() {
1220            assert_eq!(
1221                VAULTS[p.array][p.slot].load(Ordering::Relaxed),
1222                before[i],
1223                "Protected position ({}, {}) overwritten after 500 rounds",
1224                p.array, p.slot
1225            );
1226        }
1227    }
1228
1229    #[test]
1230    fn write_decoys_empty_exclusion_works() {
1231        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1232        ensure_vaults();
1233        write_decoys(&[], &[0; ARRAY_COUNT], &mut Draws::new());
1234    }
1235
1236    // ================================================================
1237    // Edge cases
1238    // ================================================================
1239
1240    #[test]
1241    fn zero_key_roundtrip() {
1242        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1243        reset();
1244        let key = [0u8; 32];
1245        TEST_KEY_A.set(key, &others_for_a());
1246        assert_eq!(TEST_KEY_A.get(), Some(key));
1247    }
1248
1249    #[test]
1250    fn max_key_roundtrip() {
1251        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1252        reset();
1253        let key = [0xFFu8; 32];
1254        TEST_KEY_A.set(key, &others_for_a());
1255        assert_eq!(TEST_KEY_A.get(), Some(key));
1256    }
1257
1258    #[test]
1259    fn to_keys_roundtrip() {
1260        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1261        reset();
1262        let mut sk_bytes = [0u8; 32];
1263        sk_bytes[31] = 1; // scalar = 1, valid secp256k1 key
1264        TEST_KEY_A.set(sk_bytes, &others_for_a());
1265        let keys = TEST_KEY_A.to_keys();
1266        assert!(keys.is_some(), "to_keys returned None for valid key");
1267        assert_eq!(keys.unwrap().secret_key().secret_bytes(), sk_bytes);
1268    }
1269
1270    #[test]
1271    fn to_keys_none_when_empty() {
1272        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1273        reset();
1274        assert!(TEST_KEY_A.to_keys().is_none());
1275    }
1276
1277    #[test]
1278    fn store_from_keys_roundtrip() {
1279        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1280        reset();
1281        let keys = nostr_sdk::prelude::Keys::generate();
1282        let expected = keys.secret_key().secret_bytes();
1283        TEST_KEY_A.store_from_keys(&keys, &others_for_a());
1284        assert_eq!(TEST_KEY_A.get(), Some(expected));
1285    }
1286
1287    // ================================================================
1288    // End-to-end encryption pipeline tests
1289    //
1290    // NOTE: These tests need crate::crypto integration (ChaCha20-Poly1305
1291    // encrypt/decrypt pipeline). They are not included in this standalone
1292    // module because they depend on:
1293    //   - crate::crypto::internal_encrypt / internal_decrypt
1294    //   - crate::crypto::maybe_encrypt / maybe_decrypt
1295    //   - crate::crypto::looks_encrypted
1296    //   - crate::state::set_encryption_enabled
1297    //
1298    // The original tests (e2e_encrypt_decrypt_10k, e2e_cross_key_stress_10k,
1299    // e2e_maybe_encrypt_decrypt_10k, e2e_batch_encrypt_then_decrypt,
1300    // e2e_key_isolation, e2e_edge_case_content, e2e_login_sequence_stress_5k)
1301    // should be placed in the integrating crate that provides both the
1302    // GuardedKey vault and the encryption pipeline.
1303    // ================================================================
1304
1305    /// A read racing a stream of replacements only ever sees one of the keys, never a blend.
1306    #[test]
1307    fn reads_racing_a_replacement_see_a_whole_key() {
1308        use std::sync::atomic::{AtomicBool, AtomicU64};
1309        use std::sync::Arc;
1310        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1311        reset();
1312        let (k1, k2) = (test_key(1), test_key(2));
1313        TEST_KEY_A.set(k1, &others_for_a());
1314        let stop = Arc::new(AtomicBool::new(false));
1315        let (reads, torn) = (Arc::new(AtomicU64::new(0)), Arc::new(AtomicU64::new(0)));
1316        let reader = {
1317            let (stop, reads, torn) = (stop.clone(), reads.clone(), torn.clone());
1318            std::thread::spawn(move || {
1319                while !stop.load(Ordering::SeqCst) {
1320                    let got = TEST_KEY_A.get();
1321                    reads.fetch_add(1, Ordering::SeqCst);
1322                    if got != Some(k1) && got != Some(k2) {
1323                        torn.fetch_add(1, Ordering::SeqCst);
1324                    }
1325                }
1326            })
1327        };
1328        for i in 0..200 {
1329            TEST_KEY_A.set(if i % 2 == 0 { k2 } else { k1 }, &others_for_a());
1330        }
1331        stop.store(true, Ordering::SeqCst);
1332        reader.join().unwrap();
1333        assert!(reads.load(Ordering::SeqCst) > 0);
1334        assert_eq!(torn.load(Ordering::SeqCst), 0);
1335        TEST_KEY_A.clear(&others_for_a());
1336    }
1337
1338    /// Replacing a key always moves it to a fresh lane, so the old shares stay intact for readers.
1339    #[test]
1340    fn a_replacement_never_reuses_the_live_lane() {
1341        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1342        reset();
1343        TEST_KEY_A.set(test_key(7), &others_for_a());
1344        for i in 0..64u8 {
1345            let before = TEST_KEY_A.lane();
1346            TEST_KEY_A.set(test_key(i), &others_for_a());
1347            assert_ne!(TEST_KEY_A.lane(), before);
1348            assert_eq!(TEST_KEY_A.get(), Some(test_key(i)));
1349        }
1350        TEST_KEY_A.clear(&others_for_a());
1351    }
1352
1353    /// Draws never yields zero (an empty marker) and doesn't repeat across its buffer refills.
1354    #[test]
1355    fn draws_are_nonzero_and_distinct() {
1356        let mut d = Draws::new();
1357        let words: Vec<usize> = (0..4096).map(|_| d.next()).collect();
1358        assert!(words.iter().all(|&w| w != 0));
1359        let mut sorted = words.clone();
1360        sorted.sort_unstable();
1361        sorted.dedup();
1362        assert_eq!(sorted.len(), words.len());
1363        let mut other = Draws::new();
1364        assert_ne!(other.next(), words[0], "each Draws is seeded afresh");
1365    }
1366
1367    /// Two keys changed at the same time from two threads both survive intact.
1368    #[test]
1369    fn concurrent_sets_of_two_keys_both_survive() {
1370        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1371        reset();
1372        let mut corrupted = 0;
1373        for round in 0..40u8 {
1374            let a = std::thread::spawn(move || {
1375                for i in 0..8u8 { TEST_KEY_A.set(test_key(round ^ i), &others_for_a()); }
1376            });
1377            let b = std::thread::spawn(move || {
1378                for i in 0..8u8 { TEST_KEY_B.set(test_key(!(round ^ i)), &others_for_b()); }
1379            });
1380            a.join().unwrap();
1381            b.join().unwrap();
1382            corrupted += usize::from(TEST_KEY_A.get() != Some(test_key(round ^ 7)));
1383            corrupted += usize::from(TEST_KEY_B.get() != Some(test_key(!(round ^ 7))));
1384        }
1385        assert_eq!(corrupted, 0);
1386        TEST_KEY_A.clear(&others_for_a());
1387        TEST_KEY_B.clear(&others_for_b());
1388    }
1389
1390    /// Prekey arrays are distinct, and neither config nor share data ever sits in one.
1391    #[test]
1392    fn prekey_rows_hold_nothing_else() {
1393        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1394        ensure_vaults();
1395        for lane in 0..LANE_COUNT {
1396            for addr in (0x6000..0x6100usize).step_by(8) {
1397                let lay = layout(addr, lane);
1398                let mut arrays = lay.prekey.to_vec();
1399                arrays.sort_unstable();
1400                arrays.dedup();
1401                assert_eq!(arrays.len(), PREKEY_ROWS);
1402                let (s, m1, m2) = lay.config;
1403                for pos in [s, m1, m2].into_iter().chain(share_positions_from(addr, lane, &lay)) {
1404                    assert!(!lay.prekey.contains(&pos.array), "{pos:?} sits in a prekey array");
1405                }
1406            }
1407        }
1408    }
1409
1410    /// The shares hold the shielded key, never the key, and one flipped prekey bit garbles it.
1411    #[test]
1412    fn the_key_is_stored_shielded_and_needs_every_prekey_bit() {
1413        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1414        reset();
1415        let key = test_key(0x5c);
1416        TEST_KEY_A.set(key, &others_for_a());
1417        let (addr, lane) = (TEST_KEY_A.instance_addr(), TEST_KEY_A.lane());
1418        let lay = layout(addr, lane);
1419        let mut unshielded = [0u8; 32];
1420        for (i, pos) in share_positions_from(addr, lane, &lay).iter().enumerate() {
1421            let val = VAULTS[pos.array][pos.slot].load(Ordering::Relaxed).to_ne_bytes();
1422            let off = (i % USIZES_PER_SHARE) * std::mem::size_of::<usize>();
1423            for (a, b) in unshielded[off..off + val.len()].iter_mut().zip(val) { *a ^= b; }
1424        }
1425        assert_ne!(unshielded, key);
1426
1427        let slot = &VAULTS[lay.prekey[3]][lane * LANE_WIDTH + 77];
1428        let original = slot.load(Ordering::Relaxed);
1429        slot.store(original ^ (1 << 13), Ordering::Relaxed);
1430        let garbled = TEST_KEY_A.get().unwrap();
1431        slot.store(original, Ordering::Relaxed);
1432        assert_ne!(garbled, key);
1433        assert_eq!(TEST_KEY_A.get(), Some(key));
1434        TEST_KEY_A.clear(&others_for_a());
1435    }
1436
1437    /// Reads of one key stay whole while another key's set() and clear() run.
1438    #[test]
1439    fn reads_of_a_partner_survive_other_writes() {
1440        use std::sync::atomic::{AtomicBool, AtomicU64};
1441        use std::sync::Arc;
1442        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
1443        reset();
1444        let kb = test_key(0xB0);
1445        TEST_KEY_B.set(kb, &others_for_b());
1446        let stop = Arc::new(AtomicBool::new(false));
1447        let (reads, wrong) = (Arc::new(AtomicU64::new(0)), Arc::new(AtomicU64::new(0)));
1448        let reader = {
1449            let (stop, reads, wrong) = (stop.clone(), reads.clone(), wrong.clone());
1450            std::thread::spawn(move || {
1451                while !stop.load(Ordering::SeqCst) {
1452                    if TEST_KEY_B.get() != Some(kb) {
1453                        wrong.fetch_add(1, Ordering::SeqCst);
1454                    }
1455                    reads.fetch_add(1, Ordering::SeqCst);
1456                }
1457            })
1458        };
1459        for i in 0..300u16 {
1460            TEST_KEY_A.set(test_key(i as u8), &others_for_a());
1461            if i % 7 == 0 { TEST_KEY_A.clear(&others_for_a()); }
1462        }
1463        stop.store(true, Ordering::SeqCst);
1464        reader.join().unwrap();
1465        assert!(reads.load(Ordering::SeqCst) > 0);
1466        assert_eq!(wrong.load(Ordering::SeqCst), 0);
1467        TEST_KEY_A.clear(&others_for_a());
1468        TEST_KEY_B.clear(&others_for_b());
1469    }
1470}