vector-core 0.13.0

Core library for Vector: the single source of truth for all Vector clients, SDKs and interfaces.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
//! Memory-hardened key storage: 32 arrays of random-looking words with decoy writes, and a
//! shielded key.
//!
//! The real 32-byte key is never stored. What is stored is the key XORed with
//! BLAKE3(prekey), XOR-split into 4 shares (16 `usize` values on 64-bit) and scattered
//! across 32 static arrays of 4,096 entries each. The prekey is 16 KiB of the arrays'
//! own random fill: the key's lane row in 8 arrays (16 on 32-bit), which nothing writes while
//! the key is live.
//!
//! Defense layers:
//! 1. **Shielding**: the vault opens only with every one of the prekey's 131,072 bits
//!    exact, so a noisy or partial capture of the vault (cold boot, Rowhammer/RAMBleed,
//!    speculative leaks, torn dumps) gives an unrelated key.
//! 2. **Secret splitting**: the shielded key is XOR-split into 4 shares
//! 3. **32 alike arrays**: same size, all randomly filled, all receiving the same number of
//!    decoys per set()/clear(). A single dump shows nothing that singles one out.
//! 4. **No heap allocations**: zero pointers, zero mlock
//! 5. **Scattered positions**: prekey rows, seed, multipliers and share data each sit at
//!    (array, slot) positions derived from the ASLR instance address. The slot
//!    dimension is partitioned into LANE_COUNT disjoint lanes; each live key owns one
//!    lane (chosen at set() to differ from every live key's, its own included), so two
//!    keys can never share a slot.
//! 6. **Decoy writes**: during set()/clear(), every array receives random writes, so the
//!    real ones hide among ~2,000 changed slots in a snapshot diff. Decoys keep off other
//!    live keys' slots and prekey rows, so those rows go untouched in a diff: two snapshots
//!    around a change show which lane and arrays another live key uses.
//! 7. **Retire by prekey**: a replaced or cleared key's shares are left in place and its
//!    prekey changed instead, and each set() draws a fresh seed, so no share slot is
//!    rewritten across two diffs. Only a lane's seed slot is, each time a key returns to it.
//! 8. **Zero writes on read**: a read only loads.
//! 9. **No fixed layout constants**: multipliers and round counts derive from ASLR
//!    addresses, and all modular arithmetic uses power-of-2 AND masks.
//! 10. **No stack residue**: `read`, `with_key` and `with_keys` rebuild the key into one
//!    buffer, run the caller's work on it, then zero the dead stack both used, so no copy
//!    outlives the call: not a moved-from local, a secp256k1 scalar or BLAKE3's output.
//!    `to_keys()` hands out an owned keypair, only where one must outlive the call.
//!
//! Security tiers:
//!   **Without source code** (info-stealers, forensic tools): nothing marks the vault or
//!   the key's place in it.
//!
//!   **Noisy or partial capture of the vault**: needs the full 16 KiB prekey bit-exact.
//!
//!   **Source code + snapshots of the vault alone, no load address**: the address is
//!   guessed. Every key's layout follows from it, so one guess that fits any key opens
//!   them all. A diff around any set() or clear() checks a guess without a hash or a curve
//!   operation; a single snapshot needs both per guess.
//!
//!   **Source code + a clean, complete dump**: recoverable, as any in-process secret is.
//!   A dump carries the image base, so the layout is one derivation away. The defence
//!   here is the anti-debug layer (PT_DENY_ATTACH, PR_SET_DUMPABLE, DACL), which stops
//!   the dump being taken.

use std::sync::atomic::{fence, AtomicUsize, Ordering};
use rand::RngCore;
use zeroize::Zeroize;

/// Entries per array — 4096 is common for crypto lookup tables (S-boxes, hash
/// constants), maximizing false positives during memory scanning.
const ARRAY_SIZE: usize = 4096;
/// Total arrays: 3 config (seed, mul1, mul2) + 4 shares scattered across random arrays + decoys.
/// Power-of-2: `% 32` compiles to `AND #0x1f` — hundreds of hits in any binary.
/// Non-power-of-2 would use a unique magic-multiply constant (trivially searchable).
const ARRAY_COUNT: usize = 32;
/// Decoy writes per array per set()/clear(). With 32 arrays this keeps the 2,048 changed
/// slots a snapshot diff must search the same as 128 arrays × 16 gave.
const DECOYS_PER_ARRAY: usize = 64;
/// Number of real XOR shares the key is split into.
const NUM_SHARES: usize = 4;
/// `usize` values per 32-byte share (4 on 64-bit, 8 on 32-bit).
const USIZES_PER_SHARE: usize = 32 / std::mem::size_of::<usize>();
/// Total entries used by one key's share data.
const SHARE_ENTRIES: usize = NUM_SHARES * USIZES_PER_SHARE;
/// Lane rows that make up one key's prekey: 16 KiB on 64-bit and on 32-bit alike.
const PREKEY_ROWS: usize = 16 * 1024 / (LANE_WIDTH * std::mem::size_of::<usize>());
// Retirement picks a prekey row with an AND mask, and the rows must leave arrays for shares.
const _: () = assert!(PREKEY_ROWS.is_power_of_two() && PREKEY_ROWS < ARRAY_COUNT);

/// Number of disjoint slot-lanes the slot dimension is partitioned into.
/// Each live key occupies exactly one lane, so two keys in distinct lanes can
/// never share an (array, slot) — eliminating cross-key write collisions without
/// any coordination at read time. Power-of-2: `& (LANE_COUNT-1)` compiles to a
/// plain AND mask (ubiquitous in any binary). 16 lanes ⇒ up to 16 concurrent keys
/// (production uses 2). `LANE_WIDTH` = 256 slots ≫ the 19 positions a key needs.
const LANE_COUNT: usize = 16;
/// Slots per lane. `ARRAY_SIZE / LANE_COUNT`, power-of-2.
const LANE_WIDTH: usize = ARRAY_SIZE / LANE_COUNT;

/// 32 vault arrays — all identical, all randomly initialized, all modified during set().
/// Memory: 32 × 4096 × size_of::<usize>() = 1 MiB on 64-bit, 512 KiB on 32-bit.
static VAULTS: [[AtomicUsize; ARRAY_SIZE]; ARRAY_COUNT] = {
    // Array-repeat seeds for this static only; each use is a fresh copy.
    #[allow(clippy::declare_interior_mutable_const)]
    const ZERO: AtomicUsize = AtomicUsize::new(0);
    #[allow(clippy::declare_interior_mutable_const, clippy::large_const_arrays)]
    const ROW: [AtomicUsize; ARRAY_SIZE] = [ZERO; ARRAY_SIZE];
    [ROW; ARRAY_COUNT]
};

/// Initialize all arrays with random values (once per process).
/// Every entry across all arrays is filled — real and decoy arrays are identical.
fn ensure_vaults() {
    if VAULTS[0][0].load(Ordering::Relaxed) == 0 {
        fill_random(&VAULTS);
    }
}

/// Fill every still-empty entry. Racing fillers keep whichever value lands first.
fn fill_random(rows: &[[AtomicUsize; ARRAY_SIZE]]) {
    let mut draws = Draws::new();
    for row in rows {
        for slot in row.iter() {
            let _ = slot.compare_exchange(0, draws.next(), Ordering::SeqCst, Ordering::Relaxed);
        }
    }
}

/// Non-zero random words from a ChaCha20 keystream seeded once from the OS. Decoys and fills
/// take thousands of words, and a syscall each dominated `set()`. Wiped on drop: whoever
/// recovers this state could tell decoy writes from real ones.
struct Draws {
    cipher: chacha20::ChaCha20,
    buf: [u64; 64],
    at: usize,
}

impl Draws {
    fn new() -> Self {
        use chacha20::cipher::KeyIvInit;
        let mut seed = [0u8; 44];
        rand::rngs::OsRng.fill_bytes(&mut seed);
        let cipher = chacha20::ChaCha20::new((&seed[..32]).into(), (&seed[32..]).into());
        seed.zeroize();
        Self { cipher, buf: [0; 64], at: 64 }
    }

    #[inline]
    fn next(&mut self) -> usize {
        use chacha20::cipher::StreamCipher;
        if self.at == self.buf.len() {
            self.buf = [0; 64];
            // SAFETY: a [u64; 64] is 512 initialised bytes, viewed as bytes for the keystream.
            let bytes = unsafe { std::slice::from_raw_parts_mut(self.buf.as_mut_ptr() as *mut u8, 512) };
            self.cipher.apply_keystream(bytes);
            self.at = 0;
        }
        let v = self.buf[self.at] as usize;
        self.at += 1;
        if v == 0 { 1 } else { v }
    }
}

impl Drop for Draws {
    fn drop(&mut self) {
        self.buf.zeroize();
    }
}

/// A position within the vault: (array index, slot index).
#[derive(Clone, Copy, PartialEq)]
#[cfg_attr(test, derive(Debug))]
struct VaultPos {
    array: usize,
    slot: usize,
}

/// Derive the mixing iteration count from ASLR addresses — ZERO constants in the binary.
/// Range: 16..31, changing every launch, so there is no fixed loop bound to search for. Not a
/// work factor: a dump carries the image base, so an attacker runs this derivation once.
#[inline]
fn mix_iterations(instance_addr: usize) -> usize {
    let base = VAULTS.as_ptr() as usize;
    let h = (instance_addr ^ base).wrapping_mul(instance_addr | 1);
    16 + ((h >> 7) & 15)
}

/// Hardened hash mixing — runtime-determined iterations of shift-multiply-XOR.
/// ZERO compile-time constants — both multipliers AND iteration count derived
/// from ASLR addresses. Compiles to a tight loop of generic MUL + EOR + LSR.
#[inline]
fn addr_mix(mut h: u64, m1: u64, m2: u64, iterations: usize) -> u64 {
    for _ in 0..iterations {
        h ^= h >> 33;
        h = h.wrapping_mul(m1);
        h ^= h >> 29;
        h = h.wrapping_mul(m2);
        h ^= h >> 31;
    }
    h
}

/// Map a raw hash to a slot inside `lane`'s disjoint slot-range.
/// `slot = lane*LANE_WIDTH + (raw % LANE_WIDTH)` — distinct lanes never overlap.
/// Both ops are AND masks (power-of-2), so this stays a generic AND/OR/SHIFT
/// sequence with no searchable constants.
#[inline]
fn lane_slot(raw: usize, lane: usize) -> usize {
    (lane << LANE_WIDTH.trailing_zeros()) | (raw & (LANE_WIDTH - 1))
}

/// Where one key lives in one lane: the arrays whose lane row is its prekey, and its 3
/// configuration positions (seed, mul1, mul2), which never sit in a prekey array.
struct Layout {
    prekey: [usize; PREKEY_ROWS],
    config: (VaultPos, VaultPos, VaultPos),
}

/// Derive a key's layout from the instance address. No dependency on stored values, which
/// breaks the chicken-and-egg. Uses instance address + VAULTS base address (both ASLR'd,
/// both change per launch); multipliers derive from the two, so no searchable constants.
/// `lane` confines every slot to one of LANE_COUNT disjoint ranges.
fn layout(instance_addr: usize, lane: usize) -> Layout {
    layout_with(instance_addr, lane, mix_iterations(instance_addr))
}

fn layout_with(instance_addr: usize, lane: usize, iters: usize) -> Layout {
    let base = VAULTS.as_ptr() as usize;
    // Derive multipliers from ASLR addresses — forced odd for mixing quality.
    let m1 = (instance_addr as u64) | 1;
    let m2 = (base as u64) | 1;
    let mut h = addr_mix((instance_addr as u64) ^ (base as u64).rotate_left(19), m1, m2, iters);

    let mut prekey = [0usize; PREKEY_ROWS];
    for i in 0..PREKEY_ROWS {
        loop {
            let candidate = ((h >> 32) as usize) & (ARRAY_COUNT - 1);
            h = addr_mix(h, m1, m2, iters);
            if !prekey[..i].contains(&candidate) {
                prekey[i] = candidate;
                break;
            }
        }
    }

    let mut positions = [VaultPos { array: 0, slot: 0 }; 3];
    for i in 0..3 {
        loop {
            let candidate = VaultPos {
                array: ((h >> 32) as usize) & (ARRAY_COUNT - 1),
                slot: lane_slot(h as usize, lane),
            };
            h = addr_mix(h, m1, m2, iters);
            if !positions[..i].contains(&candidate) && !prekey.contains(&candidate.array) {
                positions[i] = candidate;
                break;
            }
        }
    }

    Layout { prekey, config: (positions[0], positions[1], positions[2]) }
}

fn config_positions(instance_addr: usize, lane: usize) -> (VaultPos, VaultPos, VaultPos) {
    layout(instance_addr, lane).config
}

/// Derive share data positions. Uses the seed + multipliers read from the vault
/// (which are at config-derived positions) + instance address.
/// `lane` confines the slot dimension to the key's disjoint lane (same lane as its
/// config positions). Returns SHARE_ENTRIES (array, slot) pairs — each guaranteed
/// unique and non-overlapping with config positions (rehash on collision).
fn share_positions(instance_addr: usize, lane: usize) -> [VaultPos; SHARE_ENTRIES] {
    share_positions_from(instance_addr, lane, &layout(instance_addr, lane))
}

fn share_positions_from(instance_addr: usize, lane: usize, layout: &Layout) -> [VaultPos; SHARE_ENTRIES] {
    let (seed_pos, mul1_pos, mul2_pos) = layout.config;
    let seed = VAULTS[seed_pos.array][seed_pos.slot].load(Ordering::Relaxed) as u64;
    let mul1 = VAULTS[mul1_pos.array][mul1_pos.slot].load(Ordering::Relaxed) as u64;
    let mul2 = VAULTS[mul2_pos.array][mul2_pos.slot].load(Ordering::Relaxed) as u64;

    let mut h = seed ^ (instance_addr as u64).rotate_left(23);
    let mut positions = [VaultPos { array: 0, slot: 0 }; SHARE_ENTRIES];
    let config = [seed_pos, mul1_pos, mul2_pos];

    for i in 0..SHARE_ENTRIES {
        loop {
            h ^= h >> 17;
            h = h.wrapping_mul(mul1 | 1);
            h ^= h >> 13;
            h = h.wrapping_mul(mul2 | 1);
            h ^= h >> 16;
            let candidate = VaultPos {
                array: ((h >> 32) as usize) & (ARRAY_COUNT - 1),
                slot: lane_slot(h as usize, lane),
            };
            if !config.contains(&candidate)
                && !positions[..i].contains(&candidate)
                && !layout.prekey.contains(&candidate.array)
            {
                positions[i] = candidate;
                break;
            }
            // Collision: hash state already advanced, loop retries with new h
        }
    }

    positions
}

/// BLAKE3 of a key's prekey: its lane row in each of its prekey arrays, 16 KiB in all.
/// Copied out with atomic loads (a writer may be mid-decoy; the epoch check discards that
/// read) and wiped after.
fn shield(lane: usize, prekey: &[usize; PREKEY_ROWS]) -> [u8; 32] {
    let mut pad = [0u8; 32];
    shield_into(lane, prekey, &mut pad);
    pad
}

fn shield_into(lane: usize, prekey: &[usize; PREKEY_ROWS], out: &mut [u8; 32]) {
    let mut buf = [0usize; PREKEY_ROWS * LANE_WIDTH];
    for (row, &array) in buf.chunks_exact_mut(LANE_WIDTH).zip(prekey) {
        let slots = &VAULTS[array][lane * LANE_WIDTH..(lane + 1) * LANE_WIDTH];
        for (dst, slot) in row.iter_mut().zip(slots) {
            *dst = slot.load(Ordering::Relaxed);
        }
    }
    // SAFETY: an initialised local [usize] viewed as its bytes, for hashing only.
    let bytes = unsafe {
        std::slice::from_raw_parts(buf.as_ptr() as *const u8, std::mem::size_of_val(&buf))
    };
    *out = *blake3::hash(bytes).as_bytes();
    buf.zeroize();
}

/// How far below a read [`scrub_below`] zeroes: past the deepest hot path, the read's 16 KiB
/// prekey buffer and the closure together (`attack::stack_residue_by_path` measures them).
const SCRUB_BYTES: usize = 32 * 1024;

/// Zero the dead stack a read and its closure just used.
#[inline(never)]
fn scrub_below() {
    let mut stack = std::mem::MaybeUninit::<[u8; SCRUB_BYTES]>::uninit();
    // SAFETY: zeroes a local this frame owns; black_box keeps the writes from being elided.
    unsafe { std::ptr::write_bytes(stack.as_mut_ptr(), 0, 1) };
    std::hint::black_box(&mut stack);
}

/// Vault-wide seqlock: odd while a set() or clear() is rewriting, bumped past it after. A
/// read that overlaps one starts again, so it never mixes old and new shares or prekeys.
static EPOCH: AtomicUsize = AtomicUsize::new(0);

/// The vault's write count: it moves on every set() and clear(), and is odd while one runs.
/// Something derived from a key read under an even count is current while the count is unchanged.
pub fn write_count() -> usize {
    EPOCH.load(Ordering::Acquire)
}

/// Holds the epoch odd for one writer; even again on drop, panics included.
struct Rewriting(usize);

impl Rewriting {
    fn begin() -> Self {
        let epoch = EPOCH.load(Ordering::Relaxed);
        EPOCH.store(epoch.wrapping_add(1), Ordering::Relaxed);
        fence(Ordering::Release);
        Self(epoch)
    }
}

impl Drop for Rewriting {
    fn drop(&mut self) {
        EPOCH.store(self.0.wrapping_add(2), Ordering::Release);
    }
}

/// Write DECOYS_PER_ARRAY random entries to EVERY array (real + decoy), excluding protected positions
/// and the lane rows set in `rows` (bit `lane` of `rows[array]`). Both belong to other live keys.
fn write_decoys(protected: &[VaultPos], rows: &[u16; ARRAY_COUNT], draws: &mut Draws) {
    for (array_idx, row) in VAULTS.iter().enumerate() {
        for _ in 0..DECOYS_PER_ARRAY {
            let mut slot = draws.next() & (ARRAY_SIZE - 1);
            while rows[array_idx] >> (slot / LANE_WIDTH) & 1 == 1
                || protected.iter().any(|p| p.array == array_idx && p.slot == slot)
            {
                slot = draws.next() & (ARRAY_SIZE - 1);
            }
            row[slot].store(draws.next(), Ordering::Release);
        }
    }
}

/// A key being replaced or cleared. Its shares stay where they are: rewriting them would mark
/// them in a diff against the dump before. Changing one prekey word is enough to make them
/// useless, and the decoys all but always do that already.
struct Retiring {
    prekey: [usize; PREKEY_ROWS],
    lane: usize,
    pad: [u8; 32],
}

impl Retiring {
    fn begin(instance_addr: usize, lane: usize) -> Self {
        let prekey = layout(instance_addr, lane).prekey;
        Self { pad: shield(lane, &prekey), prekey, lane }
    }

    fn finish(self, draws: &mut Draws) {
        let mut now = shield(self.lane, &self.prekey);
        if now == self.pad {
            let slot = self.lane * LANE_WIDTH + (draws.next() & (LANE_WIDTH - 1));
            VAULTS[self.prekey[draws.next() & (PREKEY_ROWS - 1)]][slot].store(draws.next(), Ordering::Release);
        }
        now.zeroize();
    }
}

impl Drop for Retiring {
    fn drop(&mut self) {
        self.pad.zeroize();
    }
}

/// Serialises every set() and clear(). Each one reads its partners' lanes once, so two running
/// together could decoy over each other's fresh slots. Reads never take it.
static WRITER: std::sync::Mutex<()> = std::sync::Mutex::new(());

fn writer() -> std::sync::MutexGuard<'static, ()> {
    WRITER.lock().unwrap_or_else(|e| e.into_inner())
}

/// Memory-hardened key vault backed by 32 indistinguishable static arrays.
pub struct GuardedKey {
    /// Non-zero when a key is stored. Stores a random non-zero value (not 0/1)
    /// so it looks like any other random data in `__DATA`.
    active: AtomicUsize,
}

/// The process's standing vaults, always kept clear of whatever a caller passes, then the
/// caller's own, each once. A standing vault a call site forgets can't then share its lane.
fn partners<'a>(others: &'a [&'a GuardedKey]) -> impl Iterator<Item = &'a GuardedKey> {
    let standing: [&'static GuardedKey; 3] = [
        &crate::state::ENCRYPTION_KEY,
        &crate::state::MY_SECRET_KEY,
        &crate::state::PREVIOUS_AT_REST_KEY,
    ];
    let mut seen: Vec<usize> = Vec::with_capacity(standing.len() + others.len());
    standing.into_iter().chain(others.iter().copied()).filter(move |k| {
        let addr = *k as *const GuardedKey as usize;
        if seen.contains(&addr) {
            false
        } else {
            seen.push(addr);
            true
        }
    })
}

impl GuardedKey {
    pub const fn empty() -> Self {
        Self { active: AtomicUsize::new(0) }
    }

    #[inline]
    fn instance_addr(&self) -> usize {
        &self.active as *const _ as usize
    }

    /// The lane a marker maps to. Lanes partition the slot space; a key lives
    /// entirely within one lane so it can never share a slot with a key in a
    /// different lane. `& (LANE_COUNT-1)` is a plain AND mask.
    #[inline]
    fn lane_of(marker: usize) -> usize {
        marker & (LANE_COUNT - 1)
    }

    /// This instance's current lane, read from its active marker (0 if empty).
    #[inline]
    fn lane(&self) -> usize {
        Self::lane_of(self.active.load(Ordering::Acquire))
    }

    /// Pick a marker whose lane differs from every currently-live key's lane, this one's
    /// included, so this key's positions stay disjoint from theirs and from its own old ones. `rng` supplies the random
    /// marker; we reroll until its lane is free. With LANE_COUNT lanes and far fewer
    /// concurrent keys, this terminates in ~1 try. The marker itself remains a
    /// full-range random non-zero usize — the lane is an emergent low-bit property,
    /// not separately stored, so it adds no searchable fingerprint.
    fn pick_marker(&self, others: &[&GuardedKey], rng: &mut rand::rngs::OsRng) -> usize {
        let mut taken = [false; LANE_COUNT];
        if self.has_key() {
            taken[self.lane()] = true;
        }
        for key in partners(others) {
            if std::ptr::eq(key, self) || !key.has_key() { continue; }
            taken[key.lane()] = true;
        }
        loop {
            let mut marker = rng.next_u64() as usize;
            if marker == 0 { marker = 1; }
            if !taken[Self::lane_of(marker)] {
                return marker;
            }
        }
    }

    /// Collect protected vault positions from other active GuardedKey instances.
    /// Prevents write_decoys from corrupting another key's share/config data.
    ///
    /// `others` is a slice of references to other GuardedKey instances that share
    /// the same VAULTS arrays. The caller is responsible for passing all other
    /// active keys to ensure cross-key protection.
    ///
    /// Sized for up to LANE_COUNT live keys (the max that can coexist in distinct lanes).
    /// Decoys roam every lane, so this exclusion is what keeps them off a partner's slots.
    fn collect_other_protected(&self, others: &[&GuardedKey]) -> ([VaultPos; (3 + SHARE_ENTRIES) * LANE_COUNT], usize) {
        let mut buf = [VaultPos { array: 0, slot: 0 }; (3 + SHARE_ENTRIES) * LANE_COUNT];
        let mut n = 0;
        for key in partners(others) {
            if std::ptr::eq(key, self) || !key.has_key() { continue; }
            if n + 3 + SHARE_ENTRIES > buf.len() { break; }
            let addr = key.instance_addr();
            let lane = key.lane();
            let (s, m1, m2) = config_positions(addr, lane);
            buf[n] = s; n += 1;
            buf[n] = m1; n += 1;
            buf[n] = m2; n += 1;
            for &pos in share_positions(addr, lane).iter() {
                buf[n] = pos;
                n += 1;
            }
        }
        (buf, n)
    }

    /// Lane rows holding another live key's prekey, as a lane bitmask per array.
    fn other_prekey_rows(&self, others: &[&GuardedKey]) -> [u16; ARRAY_COUNT] {
        let mut rows = [0u16; ARRAY_COUNT];
        for key in partners(others) {
            if std::ptr::eq(key, self) || !key.has_key() { continue; }
            let lane = key.lane();
            for array in layout(key.instance_addr(), lane).prekey {
                rows[array] |= 1 << lane;
            }
        }
        rows
    }

    /// Extract the secret key from a `Keys` struct, store it in the vault,
    /// and zeroize the intermediate bytes. One-liner replacement for the
    /// repeated extract -> set -> zeroize pattern across login paths.
    ///
    /// `others` is a slice of references to other active GuardedKey instances
    /// for cross-key protection during decoy writes.
    #[inline]
    pub fn store_from_keys(&self, keys: &nostr_sdk::prelude::Keys, others: &[&GuardedKey]) {
        let mut sk_bytes = keys.secret_key().secret_bytes();
        self.set(sk_bytes, others);
        sk_bytes.zeroize();
    }

    /// Store a key: shielded under its new lane's prekey, XOR-split into 4 shares
    /// scattered across the arrays, with decoy writes to ALL arrays so real writes are
    /// indistinguishable.
    ///
    /// INVARIANT: pass EVERY other live key (the standing vaults are always included). Decoys
    /// keep off only the slots and prekey rows of the keys named here.
    pub fn set(&self, mut key: [u8; 32], others: &[&GuardedKey]) {
        let _writer = writer();
        let mut rng = rand::rngs::OsRng;
        let mut draws = Draws::new();
        ensure_vaults();

        // A fresh lane, free of every live key's including our own: new positions and a new
        // prekey, while readers of the old key keep a consistent copy until the epoch moves.
        let marker = self.pick_marker(others, &mut rng);
        let lane = Self::lane_of(marker);

        let old_marker = self.active.load(Ordering::Acquire);
        let (protected, pcount) = self.collect_other_protected(others);
        let rows = self.other_prekey_rows(others);
        // Drawn before the window: nothing inside it may fail, or the epoch would stay odd and
        // every read spin (a wasm panic aborts without running the guard's drop).
        let mut splits = zeroize::Zeroizing::new([[0u8; 32]; NUM_SHARES - 1]);
        for share in splits.iter_mut() {
            rng.fill_bytes(share);
        }
        let rewriting = Rewriting::begin();
        let retiring = (old_marker != 0).then(|| Retiring::begin(self.instance_addr(), Self::lane_of(old_marker)));

        // Decoys first, our new prekey rows included. Real writes below overwrite any decoy
        // that landed on OUR slots; every other key's slots and prekey rows are left alone.
        write_decoys(&protected[..pcount], &rows, &mut draws);

        // A fresh seed, so a lane this key held before never hands its shares the same slots:
        // a slot rewritten in two diffs stands out. One random word, like any decoy.
        let (seed_pos, _, _) = config_positions(self.instance_addr(), lane);
        VAULTS[seed_pos.array][seed_pos.slot].store(draws.next(), Ordering::Relaxed);

        Self::write_shielded(self.instance_addr(), lane, &mut key, &splits);

        // Commit the lane-bearing marker. get() re-derives the same lane from it.
        self.active.store(marker, Ordering::Release);

        if let Some(retiring) = retiring {
            retiring.finish(&mut draws);
        }

        drop(rewriting);
    }

    /// Shield `key` under `lane`'s prekey and write it as 4 shares, the first 3 being `splits`.
    /// Wipes `key`.
    fn write_shielded(instance_addr: usize, lane: usize, key: &mut [u8; 32], splits: &[[u8; 32]; NUM_SHARES - 1]) {
        let layout = layout(instance_addr, lane);
        let mut pad = shield(lane, &layout.prekey);
        let mut shares = zeroize::Zeroizing::new([[0u8; 32]; NUM_SHARES]);
        shares[..NUM_SHARES - 1].copy_from_slice(splits);
        for j in 0..32 {
            let mut last = key[j] ^ pad[j];
            for share in shares.iter().take(NUM_SHARES - 1) {
                last ^= share[j];
            }
            shares[NUM_SHARES - 1][j] = last;
        }
        key.zeroize();
        pad.zeroize();

        let positions = share_positions_from(instance_addr, lane, &layout);
        for (share_idx, share) in shares.iter().enumerate() {
            for u_idx in 0..USIZES_PER_SHARE {
                let byte_off = u_idx * std::mem::size_of::<usize>();
                let val = usize::from_ne_bytes(
                    share[byte_off..byte_off + std::mem::size_of::<usize>()]
                        .try_into().unwrap()
                );
                let pos = positions[share_idx * USIZES_PER_SHARE + u_idx];
                VAULTS[pos.array][pos.slot].store(val, Ordering::Release);
            }
        }
    }

    /// Run `f` on the key, or on `None` when the vault is empty. The key is rebuilt into one
    /// buffer `f` borrows, which is wiped when it returns, and then the stack both used is
    /// zeroed: only what `f` returns or stores outlives the call. Zero writes to the vault.
    pub fn read<R>(&self, f: impl FnOnce(Option<&[u8; 32]>) -> R) -> R {
        let out = self.read_then(f);
        scrub_below();
        out
    }

    /// Never inlined, so the read and `f` run in frames below the caller's, where
    /// [`scrub_below`] reaches the copies they leave: moved-from locals, secp256k1 scalars,
    /// BLAKE3's output.
    #[inline(never)]
    fn read_then<R>(&self, f: impl FnOnce(Option<&[u8; 32]>) -> R) -> R {
        let mut key = zeroize::Zeroizing::new([0u8; 32]);
        let held = self.read_into(&mut key);
        f(held.then_some(&*key))
    }

    /// [`Self::read`] for a vault expected to hold a key: `None` when it is empty.
    pub fn with_key<R>(&self, f: impl FnOnce(&[u8; 32]) -> R) -> Option<R> {
        self.read(|key| key.map(f))
    }

    /// [`Self::with_key`] as a keypair, dropped (and wiped) when `f` returns.
    pub fn with_keys<R>(&self, f: impl FnOnce(&nostr_sdk::prelude::Keys) -> R) -> Option<R> {
        use nostr_sdk::prelude::{Keys, SecretKey};
        self.with_key(|key| SecretKey::from_slice(key).ok().map(|sk| f(&Keys::new(sk))))?
    }

    /// A copy of the key, for tests to compare.
    #[cfg(any(test, feature = "bench"))]
    pub(crate) fn get(&self) -> Option<[u8; 32]> {
        self.with_key(|key| *key)
    }

    /// Rebuild the key into `out`; false when the vault is empty. A read that a set() or
    /// clear() overlapped sees the epoch (or this key's marker) move and starts again, so it
    /// never returns a mix of old and new shares or prekeys.
    fn read_into(&self, out: &mut [u8; 32]) -> bool {
        loop {
            let epoch = EPOCH.load(Ordering::Acquire);
            if epoch & 1 == 1 {
                std::hint::spin_loop();
                std::thread::yield_now();
                continue;
            }
            let marker = self.active.load(Ordering::Acquire);
            if marker == 0 {
                return false;
            }
            self.read_shielded(marker, out);
            fence(Ordering::Acquire);
            if EPOCH.load(Ordering::Relaxed) == epoch && self.active.load(Ordering::Relaxed) == marker {
                return true;
            }
            out.zeroize();
        }
    }

    fn read_shielded(&self, marker: usize, key: &mut [u8; 32]) {
        // Lane comes from the marker, so reads land on exactly the slots set() wrote.
        let lane = Self::lane_of(marker);
        let layout = layout(self.instance_addr(), lane);
        let positions = share_positions_from(self.instance_addr(), lane, &layout);
        shield_into(lane, &layout.prekey, key);

        for (i, pos) in positions.iter().enumerate() {
            let val = VAULTS[pos.array][pos.slot].load(Ordering::Acquire).to_ne_bytes();
            let byte_off = (i % USIZES_PER_SHARE) * std::mem::size_of::<usize>();
            for (a, b) in key[byte_off..byte_off + val.len()].iter_mut().zip(val) {
                *a ^= b;
            }
        }
    }

    /// Clear the key: retire its prekey and write decoys to all arrays, keeping off every other
    /// live key named in `others`.
    pub fn clear(&self, others: &[&GuardedKey]) {
        let _writer = writer();
        if self.active.load(Ordering::Acquire) == 0 {
            return;
        }
        let mut draws = Draws::new();
        let rows = self.other_prekey_rows(others);
        let (protected, pcount) = self.collect_other_protected(others);
        let rewriting = Rewriting::begin();

        let old_marker = self.active.swap(0, Ordering::SeqCst);
        let retiring = Retiring::begin(self.instance_addr(), Self::lane_of(old_marker));
        write_decoys(&protected[..pcount], &rows, &mut draws);
        retiring.finish(&mut draws);
        drop(rewriting);
    }

    pub fn has_key(&self) -> bool {
        self.active.load(Ordering::Acquire) != 0
    }

    /// An owned keypair, for an object that must keep one past the call (a NIP-46 client).
    /// Its moves leave copies nothing wipes, so shipping code marks each use `// owned-key:`
    /// (`vault_audit` enforces it); everything else uses [`Self::with_keys`].
    pub fn to_keys(&self) -> Option<nostr_sdk::prelude::Keys> {
        use nostr_sdk::prelude::{Keys, SecretKey};
        self.with_key(|key| SecretKey::from_slice(key).ok().map(Keys::new))?
    }
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(any(test, feature = "bench"))]
mod fixtures;
#[cfg(feature = "bench")]
#[doc(hidden)]
pub mod bench;
#[cfg(test)]
mod attack;

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

    // Test-local key statics (replaces crate::MY_SECRET_KEY / crate::ENCRYPTION_KEY)
    static TEST_KEY_A: GuardedKey = GuardedKey::empty();
    static TEST_KEY_B: GuardedKey = GuardedKey::empty();

    // SERIALIZE on the crate-wide `DB_TEST_GUARD` — NOT a vault-local lock. The `VAULTS` arrays are
    // ONE process-global shared by EVERY GuardedKey, including the production `MY_SECRET_KEY` /
    // `ENCRYPTION_KEY` that other tests write via `init_test_db` (which holds `DB_TEST_GUARD`). Those
    // writers pass only their partner in `others`, so their decoys/lane don't know about TEST_KEY_A/B and
    // would clobber them if run concurrently — the cause of the cross-key flake. Sharing the same guard
    // makes all vault-touching vector-core tests mutually exclusive. (Production is unaffected: its two
    // keys are always mutually `others`-aware, verified across every login/clear path. Poison-tolerant
    // via `into_inner` so one test panic doesn't cascade poison across the suite.)

    /// Fast reset: mark both test keys inactive without full clear overhead.
    fn reset() {
        TEST_KEY_A.active.store(0, Ordering::SeqCst);
        TEST_KEY_B.active.store(0, Ordering::SeqCst);
        ensure_vaults();
    }

    /// Helper: the "others" slice for TEST_KEY_A (protects TEST_KEY_B).
    fn others_for_a() -> [&'static GuardedKey; 1] {
        [&TEST_KEY_B]
    }

    /// Helper: the "others" slice for TEST_KEY_B (protects TEST_KEY_A).
    fn others_for_b() -> [&'static GuardedKey; 1] {
        [&TEST_KEY_A]
    }

    /// Generate a deterministic test key from a seed byte.
    fn test_key(seed: u8) -> [u8; 32] {
        let mut k = [0u8; 32];
        for (i, b) in k.iter_mut().enumerate() {
            *b = seed.wrapping_add(i as u8).wrapping_mul(37).wrapping_add(7);
        }
        k
    }

    // ================================================================
    // Basic operations
    // ================================================================

    #[test]
    fn set_get_roundtrip() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        reset();
        let key = test_key(42);
        TEST_KEY_A.set(key, &others_for_a());
        assert_eq!(TEST_KEY_A.get(), Some(key));
    }

    #[test]
    fn set_get_1000_iterations() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        for i in 0..1000u16 {
            reset();
            let key = test_key((i ^ (i >> 3)) as u8);
            TEST_KEY_A.set(key, &others_for_a());
            assert_eq!(
                TEST_KEY_A.get(), Some(key),
                "Roundtrip failed at iteration {i}"
            );
        }
    }

    #[test]
    fn empty_returns_none() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        reset();
        assert_eq!(TEST_KEY_A.get(), None);
        assert_eq!(TEST_KEY_B.get(), None);
    }

    #[test]
    fn has_key_lifecycle() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        reset();
        assert!(!TEST_KEY_A.has_key());
        TEST_KEY_A.set(test_key(1), &others_for_a());
        assert!(TEST_KEY_A.has_key());
        TEST_KEY_A.clear(&others_for_a());
        assert!(!TEST_KEY_A.has_key());
    }

    #[test]
    fn clear_returns_none() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        reset();
        TEST_KEY_A.set(test_key(99), &others_for_a());
        assert!(TEST_KEY_A.get().is_some());
        TEST_KEY_A.clear(&others_for_a());
        assert_eq!(TEST_KEY_A.get(), None);
    }

    #[test]
    fn set_overwrites_previous() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        reset();
        let a = test_key(10);
        let b = test_key(20);
        TEST_KEY_A.set(a, &others_for_a());
        assert_eq!(TEST_KEY_A.get(), Some(a));
        TEST_KEY_A.set(b, &others_for_a());
        assert_eq!(TEST_KEY_A.get(), Some(b));
    }

    #[test]
    fn clear_idempotent() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        reset();
        TEST_KEY_A.clear(&others_for_a());
        TEST_KEY_A.clear(&others_for_a());
        assert_eq!(TEST_KEY_A.get(), None);
        TEST_KEY_A.set(test_key(5), &others_for_a());
        TEST_KEY_A.clear(&others_for_a());
        TEST_KEY_A.clear(&others_for_a());
        assert_eq!(TEST_KEY_A.get(), None);
    }

    #[test]
    fn encryption_key_basic() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        reset();
        let key = test_key(0xEE);
        TEST_KEY_B.set(key, &others_for_b());
        assert_eq!(TEST_KEY_B.get(), Some(key));
        TEST_KEY_B.clear(&others_for_b());
        assert_eq!(TEST_KEY_B.get(), None);
    }

    // ================================================================
    // Cross-key protection — 500 iterations each.
    // Two keys live in disjoint lanes and decoys keep off each other's slots, so
    // neither key's writes (decoys, seed, shares) can ever land on the other's.
    // ================================================================

    #[test]
    fn cross_key_set_then_set_500() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        let key_a = test_key(0xAA);
        let key_b = test_key(0xBB);
        for i in 0..500 {
            reset();
            TEST_KEY_A.set(key_a, &others_for_a());
            TEST_KEY_B.set(key_b, &others_for_b());
            assert_eq!(
                TEST_KEY_A.get(), Some(key_a),
                "TEST_KEY_A corrupted at iteration {i}"
            );
            assert_eq!(
                TEST_KEY_B.get(), Some(key_b),
                "TEST_KEY_B corrupted at iteration {i}"
            );
        }
    }

    #[test]
    fn cross_key_reverse_order_500() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        let key_a = test_key(0xCC);
        let key_b = test_key(0xDD);
        for i in 0..500 {
            reset();
            TEST_KEY_B.set(key_b, &others_for_b());
            TEST_KEY_A.set(key_a, &others_for_a());
            assert_eq!(
                TEST_KEY_B.get(), Some(key_b),
                "TEST_KEY_B corrupted at iteration {i}"
            );
            assert_eq!(
                TEST_KEY_A.get(), Some(key_a),
                "TEST_KEY_A corrupted at iteration {i}"
            );
        }
    }

    #[test]
    fn cross_key_clear_preserves_other_500() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        let key_a = test_key(0x11);
        let key_b = test_key(0x22);
        for i in 0..500 {
            // Clear TEST_KEY_A, verify TEST_KEY_B survives
            reset();
            TEST_KEY_A.set(key_a, &others_for_a());
            TEST_KEY_B.set(key_b, &others_for_b());
            TEST_KEY_A.clear(&others_for_a());
            assert_eq!(
                TEST_KEY_B.get(), Some(key_b),
                "KEY_B corrupted after KEY_A.clear() at iteration {i}"
            );
            // Clear TEST_KEY_B, verify TEST_KEY_A survives
            reset();
            TEST_KEY_A.set(key_a, &others_for_a());
            TEST_KEY_B.set(key_b, &others_for_b());
            TEST_KEY_B.clear(&others_for_b());
            assert_eq!(
                TEST_KEY_A.get(), Some(key_a),
                "KEY_A corrupted after KEY_B.clear() at iteration {i}"
            );
        }
    }

    #[test]
    fn cross_key_alternating_500() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        for i in 0..500u16 {
            reset();
            let ka = test_key(i as u8);
            let kb = test_key(!(i as u8));
            TEST_KEY_A.set(ka, &others_for_a());
            TEST_KEY_B.set(kb, &others_for_b());
            assert_eq!(TEST_KEY_A.get(), Some(ka), "KEY_A wrong at iter {i}");
            assert_eq!(TEST_KEY_B.get(), Some(kb), "KEY_B wrong at iter {i}");
            TEST_KEY_A.clear(&others_for_a());
            assert_eq!(TEST_KEY_B.get(), Some(kb), "KEY_B wrong after KEY_A clear at iter {i}");
        }
    }

    /// Stress: alternating set order, different keys each round, 1000 iterations.
    /// Two keys occupy disjoint lanes, so a real write from one can never clobber the
    /// other's share slots regardless of decoy layout.
    #[test]
    fn stress_both_keys_1000() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        for i in 0..1000u32 {
            reset();
            let ka = test_key((i & 0xFF) as u8);
            let kb = test_key(!((i & 0xFF) as u8));
            if i % 2 == 0 {
                TEST_KEY_A.set(ka, &others_for_a());
                TEST_KEY_B.set(kb, &others_for_b());
            } else {
                TEST_KEY_B.set(kb, &others_for_b());
                TEST_KEY_A.set(ka, &others_for_a());
            }
            assert_eq!(TEST_KEY_A.get(), Some(ka), "KEY_A wrong at iter {i}");
            assert_eq!(TEST_KEY_B.get(), Some(kb), "KEY_B wrong at iter {i}");
        }
    }

    // ================================================================
    // Position derivation
    // ================================================================

    #[test]
    fn config_positions_all_unique() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        ensure_vaults();
        for lane in 0..LANE_COUNT {
            for addr in (0x1000..0x2000usize).step_by(8) {
                let (a, b, c) = config_positions(addr, lane);
                assert_ne!(a, b, "config collision a==b at addr {addr:#x} lane {lane}");
                assert_ne!(a, c, "config collision a==c at addr {addr:#x} lane {lane}");
                assert_ne!(b, c, "config collision b==c at addr {addr:#x} lane {lane}");
            }
        }
    }

    #[test]
    fn share_positions_all_unique() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        ensure_vaults();
        for lane in 0..LANE_COUNT {
            for addr in (0x2000..0x2100usize).step_by(8) {
                let positions = share_positions(addr, lane);
                for i in 0..SHARE_ENTRIES {
                    for j in (i + 1)..SHARE_ENTRIES {
                        assert_ne!(
                            positions[i], positions[j],
                            "share collision [{i}]==[{j}] at addr {addr:#x} lane {lane}"
                        );
                    }
                }
            }
        }
    }

    /// A standing vault keeps its lane even when a set or clear elsewhere doesn't name it.
    #[test]
    fn a_standing_vault_survives_sets_that_forget_it() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        let standing = &crate::state::PREVIOUS_AT_REST_KEY;
        standing.set([0xAB; 32], &[]);
        for i in 0..64u8 {
            let other = GuardedKey::empty();
            other.set([i; 32], &[]);
            assert_ne!(other.lane(), standing.lane());
            other.clear(&[]);
        }
        assert_eq!(standing.get(), Some([0xAB; 32]));
        standing.clear(&[]);
    }

    #[test]
    fn share_positions_no_config_overlap() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        ensure_vaults();
        for lane in 0..LANE_COUNT {
            for addr in (0x3000..0x3100usize).step_by(8) {
                let (s, m1, m2) = config_positions(addr, lane);
                let config = [s, m1, m2];
                let shares = share_positions(addr, lane);
                for (i, pos) in shares.iter().enumerate() {
                    assert!(
                        !config.contains(pos),
                        "share[{i}] collides with config at addr {addr:#x} lane {lane}"
                    );
                }
            }
        }
    }

    /// Distinct lanes are physically disjoint: no (array, slot) is shared between
    /// two different lanes for the same address. This is the property that makes
    /// cross-key writes collision-safe.
    #[test]
    fn distinct_lanes_are_disjoint() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        ensure_vaults();
        for addr in (0x5000..0x5100usize).step_by(8) {
            for la in 0..LANE_COUNT {
                for lb in 0..LANE_COUNT {
                    if la == lb { continue; }
                    let (sa, m1a, m2a) = config_positions(addr, la);
                    let a_all: Vec<VaultPos> = [sa, m1a, m2a]
                        .into_iter()
                        .chain(share_positions(addr, la))
                        .collect();
                    let (sb, m1b, m2b) = config_positions(addr, lb);
                    let b_all: Vec<VaultPos> = [sb, m1b, m2b]
                        .into_iter()
                        .chain(share_positions(addr, lb))
                        .collect();
                    for p in &a_all {
                        assert!(
                            !b_all.contains(p),
                            "lane {la} and lane {lb} share {p:?} at addr {addr:#x}"
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn positions_deterministic() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        ensure_vaults();
        let addr = TEST_KEY_A.instance_addr();
        let cfg1 = config_positions(addr, 3);
        let cfg2 = config_positions(addr, 3);
        assert_eq!(cfg1, cfg2);
        let sp1 = share_positions(addr, 3);
        let sp2 = share_positions(addr, 3);
        assert_eq!(sp1, sp2);
    }

    #[test]
    fn all_positions_in_bounds() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        ensure_vaults();
        for lane in 0..LANE_COUNT {
            for addr in (0x4000..0x4200usize).step_by(8) {
                let (a, b, c) = config_positions(addr, lane);
                for p in [a, b, c] {
                    assert!(p.array < ARRAY_COUNT);
                    assert!(p.slot < ARRAY_SIZE);
                }
                for p in share_positions(addr, lane) {
                    assert!(p.array < ARRAY_COUNT);
                    assert!(p.slot < ARRAY_SIZE);
                }
            }
        }
    }

    // ================================================================
    // Internals
    // ================================================================

    #[test]
    fn mix_iterations_in_range() {
        for addr in 0..10000usize {
            let n = mix_iterations(addr);
            assert!((16..=31).contains(&n), "mix_iterations({addr}) = {n}");
        }
    }

    #[test]
    fn addr_mix_zero_iterations_is_identity() {
        let h: u64 = 0xDEADBEEFCAFEBABE;
        assert_eq!(addr_mix(h, 123, 456, 0), h);
    }

    #[test]
    fn addr_mix_varies_output() {
        let a = addr_mix(1, 3, 5, 10);
        let b = addr_mix(2, 3, 5, 10);
        let c = addr_mix(1, 7, 5, 10);
        let d = addr_mix(1, 3, 11, 10);
        assert_ne!(a, b);
        assert_ne!(a, c);
        assert_ne!(a, d);
    }

    #[test]
    fn ensure_vaults_all_nonzero() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        ensure_vaults();
        for (r, row) in VAULTS.iter().enumerate() {
            for (s, slot) in row.iter().enumerate() {
                assert_ne!(
                    slot.load(Ordering::Relaxed), 0,
                    "VAULTS[{r}][{s}] is zero after ensure_vaults"
                );
            }
        }
    }

    #[test]
    fn ensure_vaults_idempotent() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        ensure_vaults();
        let samples: Vec<_> = (0..20)
            .map(|i| {
                let r = i * 13 % ARRAY_COUNT;
                let s = i * 397 % ARRAY_SIZE;
                (r, s, VAULTS[r][s].load(Ordering::Relaxed))
            })
            .collect();
        ensure_vaults();
        for (r, s, val) in &samples {
            assert_eq!(
                VAULTS[*r][*s].load(Ordering::Relaxed), *val,
                "ensure_vaults changed VAULTS[{r}][{s}]"
            );
        }
    }

    /// Run write_decoys 500 times with protected positions — verify they are NEVER overwritten.
    /// Without exclusion, P(at least one hit) per position ~ 99.96%, so a broken exclusion is
    /// caught with near-certainty.
    #[test]
    fn write_decoys_respects_exclusions_500() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        ensure_vaults();
        let protected = [
            VaultPos { array: 0, slot: 100 },
            VaultPos { array: 0, slot: 200 },
            VaultPos { array: 13, slot: 2000 },
            VaultPos { array: 13, slot: 3000 },
            VaultPos { array: 25, slot: 500 },
            VaultPos { array: 31, slot: 4095 },
        ];
        let before: Vec<usize> = protected.iter()
            .map(|p| VAULTS[p.array][p.slot].load(Ordering::Relaxed))
            .collect();
        for _ in 0..500 {
            write_decoys(&protected, &[0; ARRAY_COUNT], &mut Draws::new());
        }
        for (i, p) in protected.iter().enumerate() {
            assert_eq!(
                VAULTS[p.array][p.slot].load(Ordering::Relaxed),
                before[i],
                "Protected position ({}, {}) overwritten after 500 rounds",
                p.array, p.slot
            );
        }
    }

    #[test]
    fn write_decoys_empty_exclusion_works() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        ensure_vaults();
        write_decoys(&[], &[0; ARRAY_COUNT], &mut Draws::new());
    }

    // ================================================================
    // Edge cases
    // ================================================================

    #[test]
    fn zero_key_roundtrip() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        reset();
        let key = [0u8; 32];
        TEST_KEY_A.set(key, &others_for_a());
        assert_eq!(TEST_KEY_A.get(), Some(key));
    }

    #[test]
    fn max_key_roundtrip() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        reset();
        let key = [0xFFu8; 32];
        TEST_KEY_A.set(key, &others_for_a());
        assert_eq!(TEST_KEY_A.get(), Some(key));
    }

    #[test]
    fn to_keys_roundtrip() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        reset();
        let mut sk_bytes = [0u8; 32];
        sk_bytes[31] = 1; // scalar = 1, valid secp256k1 key
        TEST_KEY_A.set(sk_bytes, &others_for_a());
        let keys = TEST_KEY_A.to_keys();
        assert!(keys.is_some(), "to_keys returned None for valid key");
        assert_eq!(keys.unwrap().secret_key().secret_bytes(), sk_bytes);
    }

    #[test]
    fn to_keys_none_when_empty() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        reset();
        assert!(TEST_KEY_A.to_keys().is_none());
    }

    #[test]
    fn store_from_keys_roundtrip() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        reset();
        let keys = nostr_sdk::prelude::Keys::generate();
        let expected = keys.secret_key().secret_bytes();
        TEST_KEY_A.store_from_keys(&keys, &others_for_a());
        assert_eq!(TEST_KEY_A.get(), Some(expected));
    }

    // ================================================================
    // End-to-end encryption pipeline tests
    //
    // NOTE: These tests need crate::crypto integration (ChaCha20-Poly1305
    // encrypt/decrypt pipeline). They are not included in this standalone
    // module because they depend on:
    //   - crate::crypto::internal_encrypt / internal_decrypt
    //   - crate::crypto::maybe_encrypt / maybe_decrypt
    //   - crate::crypto::looks_encrypted
    //   - crate::state::set_encryption_enabled
    //
    // The original tests (e2e_encrypt_decrypt_10k, e2e_cross_key_stress_10k,
    // e2e_maybe_encrypt_decrypt_10k, e2e_batch_encrypt_then_decrypt,
    // e2e_key_isolation, e2e_edge_case_content, e2e_login_sequence_stress_5k)
    // should be placed in the integrating crate that provides both the
    // GuardedKey vault and the encryption pipeline.
    // ================================================================

    /// A read racing a stream of replacements only ever sees one of the keys, never a blend.
    #[test]
    fn reads_racing_a_replacement_see_a_whole_key() {
        use std::sync::atomic::{AtomicBool, AtomicU64};
        use std::sync::Arc;
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        reset();
        let (k1, k2) = (test_key(1), test_key(2));
        TEST_KEY_A.set(k1, &others_for_a());
        let stop = Arc::new(AtomicBool::new(false));
        let (reads, torn) = (Arc::new(AtomicU64::new(0)), Arc::new(AtomicU64::new(0)));
        let reader = {
            let (stop, reads, torn) = (stop.clone(), reads.clone(), torn.clone());
            std::thread::spawn(move || {
                while !stop.load(Ordering::SeqCst) {
                    let got = TEST_KEY_A.get();
                    reads.fetch_add(1, Ordering::SeqCst);
                    if got != Some(k1) && got != Some(k2) {
                        torn.fetch_add(1, Ordering::SeqCst);
                    }
                }
            })
        };
        for i in 0..200 {
            TEST_KEY_A.set(if i % 2 == 0 { k2 } else { k1 }, &others_for_a());
        }
        stop.store(true, Ordering::SeqCst);
        reader.join().unwrap();
        assert!(reads.load(Ordering::SeqCst) > 0);
        assert_eq!(torn.load(Ordering::SeqCst), 0);
        TEST_KEY_A.clear(&others_for_a());
    }

    /// Replacing a key always moves it to a fresh lane, so the old shares stay intact for readers.
    #[test]
    fn a_replacement_never_reuses_the_live_lane() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        reset();
        TEST_KEY_A.set(test_key(7), &others_for_a());
        for i in 0..64u8 {
            let before = TEST_KEY_A.lane();
            TEST_KEY_A.set(test_key(i), &others_for_a());
            assert_ne!(TEST_KEY_A.lane(), before);
            assert_eq!(TEST_KEY_A.get(), Some(test_key(i)));
        }
        TEST_KEY_A.clear(&others_for_a());
    }

    /// Draws never yields zero (an empty marker) and doesn't repeat across its buffer refills.
    #[test]
    fn draws_are_nonzero_and_distinct() {
        let mut d = Draws::new();
        let words: Vec<usize> = (0..4096).map(|_| d.next()).collect();
        assert!(words.iter().all(|&w| w != 0));
        let mut sorted = words.clone();
        sorted.sort_unstable();
        sorted.dedup();
        assert_eq!(sorted.len(), words.len());
        let mut other = Draws::new();
        assert_ne!(other.next(), words[0], "each Draws is seeded afresh");
    }

    /// Two keys changed at the same time from two threads both survive intact.
    #[test]
    fn concurrent_sets_of_two_keys_both_survive() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        reset();
        let mut corrupted = 0;
        for round in 0..40u8 {
            let a = std::thread::spawn(move || {
                for i in 0..8u8 { TEST_KEY_A.set(test_key(round ^ i), &others_for_a()); }
            });
            let b = std::thread::spawn(move || {
                for i in 0..8u8 { TEST_KEY_B.set(test_key(!(round ^ i)), &others_for_b()); }
            });
            a.join().unwrap();
            b.join().unwrap();
            corrupted += usize::from(TEST_KEY_A.get() != Some(test_key(round ^ 7)));
            corrupted += usize::from(TEST_KEY_B.get() != Some(test_key(!(round ^ 7))));
        }
        assert_eq!(corrupted, 0);
        TEST_KEY_A.clear(&others_for_a());
        TEST_KEY_B.clear(&others_for_b());
    }

    /// Prekey arrays are distinct, and neither config nor share data ever sits in one.
    #[test]
    fn prekey_rows_hold_nothing_else() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        ensure_vaults();
        for lane in 0..LANE_COUNT {
            for addr in (0x6000..0x6100usize).step_by(8) {
                let lay = layout(addr, lane);
                let mut arrays = lay.prekey.to_vec();
                arrays.sort_unstable();
                arrays.dedup();
                assert_eq!(arrays.len(), PREKEY_ROWS);
                let (s, m1, m2) = lay.config;
                for pos in [s, m1, m2].into_iter().chain(share_positions_from(addr, lane, &lay)) {
                    assert!(!lay.prekey.contains(&pos.array), "{pos:?} sits in a prekey array");
                }
            }
        }
    }

    /// The shares hold the shielded key, never the key, and one flipped prekey bit garbles it.
    #[test]
    fn the_key_is_stored_shielded_and_needs_every_prekey_bit() {
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        reset();
        let key = test_key(0x5c);
        TEST_KEY_A.set(key, &others_for_a());
        let (addr, lane) = (TEST_KEY_A.instance_addr(), TEST_KEY_A.lane());
        let lay = layout(addr, lane);
        let mut unshielded = [0u8; 32];
        for (i, pos) in share_positions_from(addr, lane, &lay).iter().enumerate() {
            let val = VAULTS[pos.array][pos.slot].load(Ordering::Relaxed).to_ne_bytes();
            let off = (i % USIZES_PER_SHARE) * std::mem::size_of::<usize>();
            for (a, b) in unshielded[off..off + val.len()].iter_mut().zip(val) { *a ^= b; }
        }
        assert_ne!(unshielded, key);

        let slot = &VAULTS[lay.prekey[3]][lane * LANE_WIDTH + 77];
        let original = slot.load(Ordering::Relaxed);
        slot.store(original ^ (1 << 13), Ordering::Relaxed);
        let garbled = TEST_KEY_A.get().unwrap();
        slot.store(original, Ordering::Relaxed);
        assert_ne!(garbled, key);
        assert_eq!(TEST_KEY_A.get(), Some(key));
        TEST_KEY_A.clear(&others_for_a());
    }

    /// Reads of one key stay whole while another key's set() and clear() run.
    #[test]
    fn reads_of_a_partner_survive_other_writes() {
        use std::sync::atomic::{AtomicBool, AtomicU64};
        use std::sync::Arc;
        let _l = crate::db::DB_TEST_GUARD.lock().unwrap_or_else(|e| e.into_inner());
        reset();
        let kb = test_key(0xB0);
        TEST_KEY_B.set(kb, &others_for_b());
        let stop = Arc::new(AtomicBool::new(false));
        let (reads, wrong) = (Arc::new(AtomicU64::new(0)), Arc::new(AtomicU64::new(0)));
        let reader = {
            let (stop, reads, wrong) = (stop.clone(), reads.clone(), wrong.clone());
            std::thread::spawn(move || {
                while !stop.load(Ordering::SeqCst) {
                    if TEST_KEY_B.get() != Some(kb) {
                        wrong.fetch_add(1, Ordering::SeqCst);
                    }
                    reads.fetch_add(1, Ordering::SeqCst);
                }
            })
        };
        for i in 0..300u16 {
            TEST_KEY_A.set(test_key(i as u8), &others_for_a());
            if i % 7 == 0 { TEST_KEY_A.clear(&others_for_a()); }
        }
        stop.store(true, Ordering::SeqCst);
        reader.join().unwrap();
        assert!(reads.load(Ordering::SeqCst) > 0);
        assert_eq!(wrong.load(Ordering::SeqCst), 0);
        TEST_KEY_A.clear(&others_for_a());
        TEST_KEY_B.clear(&others_for_b());
    }
}