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
//! Wallet signing service for server-side transaction signing
//!
//! This service handles the cryptographic operations for v2 wallet signing:
//! - Decrypting Share A using user credentials
//! - Combining shares using Shamir's Secret Sharing
//! - Signing Solana transactions
//! - Secure memory wiping
//!
//! ## Security Model
//!
//! - Share A is encrypted with user's password/PIN (Argon2id KDF) or passkey PRF (HKDF)
//! - Share B is stored as plaintext (SSS math protects it)
//! - Seed is reconstructed JIT, used for signing, then immediately wiped
//! - Server never stores seed or private key at rest
use aes_gcm::{
aead::{Aead, KeyInit},
Aes256Gcm, Nonce,
};
use argon2::{Algorithm, Argon2, Params, Version};
use ed25519_dalek::{Signer, SigningKey};
use hkdf::Hkdf;
use sha2::Sha256;
use tokio::task;
use zeroize::{Zeroize, Zeroizing};
use rand::rngs::OsRng;
use rand::RngCore;
use crate::errors::AppError;
use crate::repositories::{KdfParams, ShareAAuthMethod, WalletMaterialEntity};
/// Generate a random salt for Argon2id KDF (16 bytes)
///
/// SRV-04: Uses OsRng (kernel entropy) rather than thread_rng (ChaCha PRNG)
/// for cryptographic salt generation, per best-practice for Argon2 salts.
fn generate_salt() -> [u8; 16] {
let mut salt = [0u8; 16];
OsRng.fill_bytes(&mut salt);
salt
}
/// Wallet signing service
#[derive(Clone, Default)]
pub struct WalletSigningService;
/// Credential for unlocking Share A
pub enum UnlockCredential {
/// Password (email users) - derives key with Argon2id
Password(String),
/// PIN (OAuth users) - derives key with Argon2id
Pin(String),
/// PRF output from passkey - derives key with HKDF
PrfOutput(Vec<u8>),
/// Raw API key - derives key with Argon2id
ApiKey(String),
}
/// Result of re-encrypting Share A with a new password
///
/// Contains the new ciphertext, nonce, and salt needed to update wallet material.
pub struct ReencryptedShareA {
/// New AES-GCM ciphertext
pub ciphertext: Vec<u8>,
/// New 12-byte nonce
pub nonce: Vec<u8>,
/// New 16-byte Argon2id salt
pub salt: Vec<u8>,
}
impl WalletSigningService {
/// Create a new wallet signing service
pub fn new() -> Self {
Self
}
/// Sign a transaction using the wallet material and credential
///
/// # Security
///
/// - Decrypts Share A using the credential
/// - Combines Share A + Share B to reconstruct the seed
/// - Signs the transaction
/// - Wipes seed and intermediate values from memory
///
/// # Thread Safety (C-02)
///
/// The `material` reference must remain immutable for the duration of this call.
/// Share B is read from `material` after Share A is decrypted. If `material`
/// were mutated between these operations (e.g., during a concurrent rotation),
/// the shares would be mismatched and reconstruction would fail or produce
/// an incorrect seed.
///
/// **Caller guarantee:** Do not mutate `WalletMaterialEntity` while signing
/// operations are in flight. The repository layer ensures this by providing
/// immutable snapshots per request.
pub async fn sign_transaction(
&self,
material: &WalletMaterialEntity,
credential: &UnlockCredential,
transaction: &[u8],
) -> Result<Vec<u8>, AppError> {
// Decrypt Share A
let mut share_a = self.decrypt_share_a(material, credential).await?;
// Combine shares to reconstruct seed
let mut seed = self.combine_shares(&share_a, &material.share_b)?;
// Wipe Share A immediately after use
share_a.zeroize();
// Sign the transaction
let signature = self.sign_with_seed(&seed, transaction)?;
// Wipe seed immediately after signing
seed.zeroize();
Ok(signature)
}
/// Reconstruct the private key (seed) as a base58-encoded string
///
/// Used for Privacy Cash deposits where the sidecar needs the private key.
/// Returns the 64-byte Ed25519 keypair as base58 (Solana keypair format).
///
/// # Security
///
/// - Uses cached key to decrypt Share A
/// - Combines Share A + Share B to reconstruct the seed
/// - Returns the keypair as base58 (caller must handle securely)
/// - Wipes intermediate values from memory
///
/// # Thread Safety (C-02)
///
/// See [`sign_transaction`] for thread safety requirements.
/// SRV-05: Returns `Zeroizing<String>` so the base58-encoded private key
/// is zeroed from heap memory on drop.
pub fn reconstruct_private_key(
&self,
material: &WalletMaterialEntity,
cached_key: &[u8; 32],
) -> Result<Zeroizing<String>, AppError> {
// Decrypt Share A using cached key
let mut share_a = self.decrypt_aes_gcm(
cached_key,
&material.share_a_nonce,
&material.share_a_ciphertext,
)?;
// Combine shares to reconstruct seed
let mut seed = self.combine_shares(&share_a, &material.share_b)?;
// Wipe Share A immediately after use
share_a.zeroize();
if seed.len() != 32 {
seed.zeroize();
return Err(AppError::Internal(anyhow::anyhow!(
"Invalid seed length: expected 32, got {}",
seed.len()
)));
}
// Create the Ed25519 signing key
let seed_array: [u8; 32] = seed[..32].try_into().map_err(|_| {
seed.zeroize();
AppError::Internal(anyhow::anyhow!("Seed conversion failed"))
})?;
let signing_key = SigningKey::from_bytes(&seed_array);
let verifying_key = signing_key.verifying_key();
// Solana keypair format: 32-byte secret key + 32-byte public key
let mut keypair_bytes = [0u8; 64];
keypair_bytes[..32].copy_from_slice(&seed_array);
keypair_bytes[32..].copy_from_slice(verifying_key.as_bytes());
// Wipe seed
seed.zeroize();
// Encode as base58, wrapped in Zeroizing so it's wiped on drop
let result = Zeroizing::new(bs58::encode(&keypair_bytes).into_string());
// Zeroize keypair bytes
keypair_bytes.zeroize();
Ok(result)
}
/// Sign a transaction using a cached encryption key
///
/// Used when wallet is already unlocked for the session.
/// The cached_key is the derived encryption key, NOT the Share A or seed.
///
/// # Security
///
/// - Uses cached key to decrypt Share A
/// - Combines Share A + Share B to reconstruct the seed
/// - Signs the transaction
/// - Wipes seed and intermediate values from memory
///
/// # Thread Safety (C-02)
///
/// See [`sign_transaction`] for thread safety requirements. The same
/// immutability guarantee applies to `material` during this call.
pub fn sign_transaction_with_cached_key(
&self,
material: &WalletMaterialEntity,
cached_key: &[u8; 32],
transaction: &[u8],
) -> Result<Vec<u8>, AppError> {
// Decrypt Share A using cached key
let mut share_a = self.decrypt_aes_gcm(
cached_key,
&material.share_a_nonce,
&material.share_a_ciphertext,
)?;
// Combine shares to reconstruct seed
let mut seed = self.combine_shares(&share_a, &material.share_b)?;
// Wipe Share A immediately after use
share_a.zeroize();
// Sign the transaction
let signature = self.sign_with_seed(&seed, transaction)?;
// Wipe seed immediately after signing
seed.zeroize();
Ok(signature)
}
/// Sign a transaction using a cached key and a derived wallet index
///
/// For index 0 (default wallet), uses master seed directly.
/// For index > 0, derives a child seed via HKDF-SHA256.
pub fn sign_transaction_with_derived_index(
&self,
material: &WalletMaterialEntity,
cached_key: &[u8; 32],
transaction: &[u8],
derivation_index: i32,
) -> Result<Vec<u8>, AppError> {
// Decrypt Share A using cached key
let mut share_a = self.decrypt_aes_gcm(
cached_key,
&material.share_a_nonce,
&material.share_a_ciphertext,
)?;
// Combine shares to reconstruct master seed
let mut master_seed = self.combine_shares(&share_a, &material.share_b)?;
share_a.zeroize();
let signature = if derivation_index > 0 {
let mut child = derive_child_seed_from_bytes(&master_seed, derivation_index as u32)?;
master_seed.zeroize();
let sig = self.sign_with_seed(&child, transaction)?;
child.zeroize();
sig
} else {
let sig = self.sign_with_seed(&master_seed, transaction)?;
master_seed.zeroize();
sig
};
Ok(signature)
}
/// Sign a transaction with credential and derived wallet index
pub async fn sign_transaction_with_derived(
&self,
material: &WalletMaterialEntity,
credential: &UnlockCredential,
transaction: &[u8],
derivation_index: i32,
) -> Result<Vec<u8>, AppError> {
let mut share_a = self.decrypt_share_a(material, credential).await?;
let mut master_seed = self.combine_shares(&share_a, &material.share_b)?;
share_a.zeroize();
let signature = if derivation_index > 0 {
let mut child = derive_child_seed_from_bytes(&master_seed, derivation_index as u32)?;
master_seed.zeroize();
let sig = self.sign_with_seed(&child, transaction)?;
child.zeroize();
sig
} else {
let sig = self.sign_with_seed(&master_seed, transaction)?;
master_seed.zeroize();
sig
};
Ok(signature)
}
/// Derive a child pubkey from the master wallet at a given derivation index.
///
/// Requires the cached encryption key (wallet must be unlocked).
/// Reconstructs master seed from shares, derives child seed, returns pubkey.
pub fn derive_pubkey_for_index(
&self,
material: &WalletMaterialEntity,
cached_key: &[u8; 32],
index: u32,
) -> Result<String, AppError> {
let mut share_a = self.decrypt_aes_gcm(
cached_key,
&material.share_a_nonce,
&material.share_a_ciphertext,
)?;
let mut master_seed = self.combine_shares(&share_a, &material.share_b)?;
share_a.zeroize();
let pubkey = derive_pubkey_at_index(&master_seed, index)?;
master_seed.zeroize();
Ok(pubkey)
}
/// Derive the encryption key from a credential
///
/// Returns the derived key that can be cached for session-based signing.
/// Caller is responsible for securely storing and eventually zeroizing the key.
pub async fn derive_key(
&self,
material: &WalletMaterialEntity,
credential: &UnlockCredential,
) -> Result<[u8; 32], AppError> {
match (&material.share_a_auth_method, credential) {
(ShareAAuthMethod::Password, UnlockCredential::Password(password)) => {
self.derive_key_argon2(
password.as_bytes().to_vec(),
material
.share_a_kdf_salt
.as_ref()
.ok_or_else(|| {
AppError::Internal(anyhow::anyhow!(
"Missing KDF salt for password method"
))
})?
.clone(),
material
.share_a_kdf_params
.as_ref()
.ok_or_else(|| {
AppError::Internal(anyhow::anyhow!(
"Missing KDF params for password method"
))
})?
.clone(),
)
.await
}
(ShareAAuthMethod::Pin, UnlockCredential::Pin(pin)) => {
self.derive_key_argon2(
pin.as_bytes().to_vec(),
material
.share_a_kdf_salt
.as_ref()
.ok_or_else(|| {
AppError::Internal(anyhow::anyhow!("Missing KDF salt for PIN method"))
})?
.clone(),
material
.share_a_kdf_params
.as_ref()
.ok_or_else(|| {
AppError::Internal(anyhow::anyhow!("Missing KDF params for PIN method"))
})?
.clone(),
)
.await
}
(ShareAAuthMethod::Passkey, UnlockCredential::PrfOutput(prf_output)) => self
.derive_key_hkdf(
prf_output,
material.prf_salt.as_ref().ok_or_else(|| {
AppError::Internal(anyhow::anyhow!("Missing PRF salt for passkey method"))
})?,
),
(ShareAAuthMethod::ApiKey, UnlockCredential::ApiKey(raw_key)) => {
self.derive_key_argon2(
raw_key.as_bytes().to_vec(),
material
.share_a_kdf_salt
.as_ref()
.ok_or_else(|| {
AppError::Internal(anyhow::anyhow!(
"Missing KDF salt for api_key method"
))
})?
.clone(),
material
.share_a_kdf_params
.as_ref()
.ok_or_else(|| {
AppError::Internal(anyhow::anyhow!(
"Missing KDF params for api_key method"
))
})?
.clone(),
)
.await
}
_ => Err(AppError::Validation(
"Credential type doesn't match wallet auth method".into(),
)),
}
}
/// Verify a credential by attempting to decrypt Share A
///
/// Returns the derived key if successful, which can be cached.
pub async fn verify_and_derive_key(
&self,
material: &WalletMaterialEntity,
credential: &UnlockCredential,
) -> Result<[u8; 32], AppError> {
let key = self.derive_key(material, credential).await?;
// Verify by attempting decryption (will fail with InvalidCredentials if wrong)
self.decrypt_aes_gcm(&key, &material.share_a_nonce, &material.share_a_ciphertext)?;
Ok(key)
}
/// Decrypt Share A using the credential
async fn decrypt_share_a(
&self,
material: &WalletMaterialEntity,
credential: &UnlockCredential,
) -> Result<Vec<u8>, AppError> {
// Derive the encryption key based on auth method
let mut key = match (&material.share_a_auth_method, credential) {
(ShareAAuthMethod::Password, UnlockCredential::Password(password)) => {
self.derive_key_argon2(
password.as_bytes().to_vec(),
material
.share_a_kdf_salt
.as_ref()
.ok_or_else(|| {
AppError::Internal(anyhow::anyhow!(
"Missing KDF salt for password method"
))
})?
.clone(),
material
.share_a_kdf_params
.as_ref()
.ok_or_else(|| {
AppError::Internal(anyhow::anyhow!(
"Missing KDF params for password method"
))
})?
.clone(),
)
.await?
}
(ShareAAuthMethod::Pin, UnlockCredential::Pin(pin)) => {
self.derive_key_argon2(
pin.as_bytes().to_vec(),
material
.share_a_kdf_salt
.as_ref()
.ok_or_else(|| {
AppError::Internal(anyhow::anyhow!("Missing KDF salt for PIN method"))
})?
.clone(),
material
.share_a_kdf_params
.as_ref()
.ok_or_else(|| {
AppError::Internal(anyhow::anyhow!("Missing KDF params for PIN method"))
})?
.clone(),
)
.await?
}
(ShareAAuthMethod::Passkey, UnlockCredential::PrfOutput(prf_output)) => self
.derive_key_hkdf(
prf_output,
material.prf_salt.as_ref().ok_or_else(|| {
AppError::Internal(anyhow::anyhow!("Missing PRF salt for passkey method"))
})?,
)?,
(ShareAAuthMethod::ApiKey, UnlockCredential::ApiKey(raw_key)) => {
self.derive_key_argon2(
raw_key.as_bytes().to_vec(),
material
.share_a_kdf_salt
.as_ref()
.ok_or_else(|| {
AppError::Internal(anyhow::anyhow!(
"Missing KDF salt for api_key method"
))
})?
.clone(),
material
.share_a_kdf_params
.as_ref()
.ok_or_else(|| {
AppError::Internal(anyhow::anyhow!(
"Missing KDF params for api_key method"
))
})?
.clone(),
)
.await?
}
_ => {
return Err(AppError::Validation(
"Credential type doesn't match wallet auth method".into(),
))
}
};
// Decrypt Share A
let result =
self.decrypt_aes_gcm(&key, &material.share_a_nonce, &material.share_a_ciphertext);
// Wipe key immediately
key.zeroize();
result
}
/// Derive encryption key using Argon2id
///
/// PERF-001: Runs in spawn_blocking to avoid blocking the async runtime.
/// Argon2 key derivation is CPU-intensive (~50-100ms) and would otherwise
/// saturate the tokio thread pool under load.
pub(crate) async fn derive_key_argon2(
&self,
password: Vec<u8>,
salt: Vec<u8>,
params: KdfParams,
) -> Result<[u8; 32], AppError> {
task::spawn_blocking(move || {
let argon2_params = Params::new(params.m_cost, params.t_cost, params.p_cost, Some(32))
.map_err(|e| AppError::Internal(anyhow::anyhow!("Invalid Argon2 params: {}", e)))?;
let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, argon2_params);
let mut key = [0u8; 32];
argon2
.hash_password_into(&password, &salt, &mut key)
.map_err(|e| {
AppError::Internal(anyhow::anyhow!("Argon2 key derivation failed: {}", e))
})?;
Ok(key)
})
.await
.map_err(|e| AppError::Internal(anyhow::anyhow!("Argon2 task failed: {}", e)))?
}
/// Derive encryption key using HKDF-SHA256 (for passkey PRF)
fn derive_key_hkdf(&self, prf_output: &[u8], salt: &[u8]) -> Result<[u8; 32], AppError> {
use hmac::{Hmac, Mac};
type HmacSha256 = Hmac<Sha256>;
// HKDF Extract
let mut extract_hmac: HmacSha256 = Mac::new_from_slice(salt)
.map_err(|e| AppError::Internal(anyhow::anyhow!("HMAC init failed: {}", e)))?;
extract_hmac.update(prf_output);
let prk = extract_hmac.finalize().into_bytes();
// HKDF Expand (single iteration for 32 bytes)
let info = b"wallet-share-a-encryption";
let mut expand_hmac: HmacSha256 = Mac::new_from_slice(&prk)
.map_err(|e| AppError::Internal(anyhow::anyhow!("HMAC init failed: {}", e)))?;
expand_hmac.update(info);
expand_hmac.update(&[1u8]); // Counter byte
let result = expand_hmac.finalize().into_bytes();
let mut key = [0u8; 32];
key.copy_from_slice(&result);
Ok(key)
}
/// Decrypt ciphertext using AES-256-GCM
fn decrypt_aes_gcm(
&self,
key: &[u8; 32],
nonce: &[u8],
ciphertext: &[u8],
) -> Result<Vec<u8>, AppError> {
let cipher = Aes256Gcm::new_from_slice(key)
.map_err(|e| AppError::Internal(anyhow::anyhow!("AES cipher init failed: {}", e)))?;
#[allow(deprecated)]
let nonce = Nonce::from_slice(nonce);
cipher
.decrypt(nonce, ciphertext)
.map_err(|_| AppError::InvalidCredentials)
}
/// Combine two Shamir shares to reconstruct the seed
///
/// Compatible with secrets.js-grempe format (GF(2^8) arithmetic)
fn combine_shares(&self, share_a: &[u8], share_b: &[u8]) -> Result<Vec<u8>, AppError> {
// SRV-04: Reject oversized shares to prevent unbounded allocation
const MAX_SHARE_LEN: usize = 128;
if share_a.len() > MAX_SHARE_LEN || share_b.len() > MAX_SHARE_LEN {
return Err(AppError::Validation(format!(
"Share exceeds maximum length of {} bytes",
MAX_SHARE_LEN
)));
}
// Parse shares in secrets.js format
let (id_a, data_a) = parse_share(share_a)?;
let (id_b, data_b) = parse_share(share_b)?;
if id_a == id_b {
return Err(AppError::Internal(anyhow::anyhow!(
"Cannot combine shares with same ID"
)));
}
if data_a.len() != data_b.len() {
return Err(AppError::Internal(anyhow::anyhow!(
"Share data length mismatch"
)));
}
// Lagrange interpolation at x=0 in GF(2^8)
// For 2 shares: secret = y1 * L1(0) + y2 * L2(0)
// L1(0) = (0 - x2) / (x1 - x2) = x2 / (x1 XOR x2)
// L2(0) = (0 - x1) / (x2 - x1) = x1 / (x1 XOR x2)
let x1 = id_a;
let x2 = id_b;
let denom = gf256_add(x1, x2); // x1 XOR x2
// C-01: gf256_div now returns Result, but denom can never be 0 here
// since x1 != x2 (checked above) implies x1 XOR x2 != 0.
// We still propagate the error for defensive correctness.
let l1 = gf256_div(x2, denom)?; // x2 / (x1 XOR x2)
let l2 = gf256_div(x1, denom)?; // x1 / (x1 XOR x2)
// Reconstruct each byte of the secret
let mut secret = vec![0u8; data_a.len()];
for i in 0..secret.len() {
let term1 = gf256_mul(data_a[i], l1);
let term2 = gf256_mul(data_b[i], l2);
secret[i] = gf256_add(term1, term2);
}
Ok(secret)
}
/// Verify Share C ownership for Share C recovery mode
///
/// Combines Share B (from stored material) + Share C (from user) to reconstruct
/// the seed, then derives the pubkey and verifies it matches the stored pubkey.
///
/// # Security
///
/// - Only returns Share B if ownership is verified
/// - Seed is reconstructed temporarily and wiped immediately
///
/// Returns: true if Share C is valid (pubkey matches)
pub fn verify_share_c(
&self,
material: &WalletMaterialEntity,
share_c: &[u8],
) -> Result<bool, AppError> {
// Share C comes as raw 32-byte entropy from mnemonic
// We need to convert it to secrets.js format for combining
// Share C has ID 3 in our 2-of-3 scheme
let share_c_formatted = format_share(3, share_c);
// Combine Share B + Share C to reconstruct seed
let mut seed = self.combine_shares(&material.share_b, &share_c_formatted)?;
// Derive pubkey from seed
let pubkey = derive_pubkey_from_seed(&seed)?;
// Wipe seed immediately
seed.zeroize();
// Verify pubkey matches stored pubkey
Ok(pubkey == material.solana_pubkey)
}
/// Re-encrypt Share A with a new password
///
/// Used when user changes their login password - transparently re-encrypts Share A
/// without requiring the user to do anything special.
///
/// # Security
///
/// - Decrypts Share A using old password
/// - Re-encrypts with new password
/// - Wipes plaintext Share A and keys from memory
pub async fn reencrypt_share_a(
&self,
material: &WalletMaterialEntity,
old_password: &str,
new_password: &str,
) -> Result<ReencryptedShareA, AppError> {
// Verify auth method is password
if material.share_a_auth_method != ShareAAuthMethod::Password {
return Err(AppError::Validation(
"Wallet is not using password authentication".into(),
));
}
// Get existing KDF params and salt
let kdf_params = material.share_a_kdf_params.as_ref().ok_or_else(|| {
AppError::Internal(anyhow::anyhow!("Missing KDF params for password method"))
})?;
let old_salt = material.share_a_kdf_salt.as_ref().ok_or_else(|| {
AppError::Internal(anyhow::anyhow!("Missing KDF salt for password method"))
})?;
// Derive old key and decrypt Share A
let mut old_key = self
.derive_key_argon2(
old_password.as_bytes().to_vec(),
old_salt.clone(),
kdf_params.clone(),
)
.await?;
let mut share_a = self.decrypt_aes_gcm(
&old_key,
&material.share_a_nonce,
&material.share_a_ciphertext,
)?;
old_key.zeroize();
// Generate new salt and derive new key
let new_salt = generate_salt();
let mut new_key = self
.derive_key_argon2(
new_password.as_bytes().to_vec(),
new_salt.to_vec(),
kdf_params.clone(),
)
.await?;
// Encrypt Share A with new key
let (ciphertext, nonce) = self.encrypt_aes_gcm(&new_key, &share_a)?;
// Wipe sensitive data
new_key.zeroize();
share_a.zeroize();
Ok(ReencryptedShareA {
ciphertext,
nonce: nonce.to_vec(),
salt: new_salt.to_vec(),
})
}
/// Encrypt data using AES-256-GCM
pub(crate) fn encrypt_aes_gcm(
&self,
key: &[u8; 32],
plaintext: &[u8],
) -> Result<(Vec<u8>, [u8; 12]), AppError> {
use aes_gcm::aead::OsRng;
use aes_gcm::AeadCore;
let cipher = Aes256Gcm::new_from_slice(key)
.map_err(|e| AppError::Internal(anyhow::anyhow!("AES cipher init failed: {}", e)))?;
let nonce = Aes256Gcm::generate_nonce(&mut OsRng);
let ciphertext = cipher
.encrypt(&nonce, plaintext)
.map_err(|e| AppError::Internal(anyhow::anyhow!("AES encryption failed: {}", e)))?;
let mut nonce_bytes = [0u8; 12];
nonce_bytes.copy_from_slice(&nonce);
Ok((ciphertext, nonce_bytes))
}
/// Split a secret into 3 Shamir shares (threshold 2) using GF(2^8)
///
/// Generates a random degree-1 polynomial `f(x) = secret + a1*x` for each byte,
/// then evaluates at x=1,2,3. Any 2 shares can reconstruct the secret via
/// Lagrange interpolation (see `combine_shares`).
///
/// Returns `(share_a, share_b, share_c)` in secrets.js binary format
/// (0x80 prefix + id + data).
pub fn split_secret(&self, secret: &[u8]) -> Result<(Vec<u8>, Vec<u8>, Vec<u8>), AppError> {
if secret.is_empty() || secret.len() > 64 {
return Err(AppError::Validation(format!(
"Secret length must be 1-64 bytes, got {}",
secret.len()
)));
}
let mut coeffs = vec![0u8; secret.len()];
OsRng.fill_bytes(&mut coeffs);
let mut data_1 = vec![0u8; secret.len()];
let mut data_2 = vec![0u8; secret.len()];
let mut data_3 = vec![0u8; secret.len()];
for i in 0..secret.len() {
// f(x) = secret[i] + coeffs[i]*x in GF(2^8)
data_1[i] = gf256_add(secret[i], gf256_mul(coeffs[i], 1));
data_2[i] = gf256_add(secret[i], gf256_mul(coeffs[i], 2));
data_3[i] = gf256_add(secret[i], gf256_mul(coeffs[i], 3));
}
coeffs.zeroize();
Ok((
format_share(1, &data_1),
format_share(2, &data_2),
format_share(3, &data_3),
))
}
/// Sign data using Ed25519
fn sign_with_seed(&self, seed: &[u8], message: &[u8]) -> Result<Vec<u8>, AppError> {
if seed.len() != 32 {
return Err(AppError::Internal(anyhow::anyhow!(
"Invalid seed length: expected 32, got {}",
seed.len()
)));
}
let seed_array: [u8; 32] = seed
.try_into()
.map_err(|_| AppError::Internal(anyhow::anyhow!("Seed conversion failed")))?;
let signing_key = SigningKey::from_bytes(&seed_array);
let signature = signing_key.sign(message);
Ok(signature.to_bytes().to_vec())
}
}
// --- secrets.js-grempe compatible share parsing ---
/// Parse a secrets.js share format
///
/// Format: first 2 hex chars = config (bits + flags), next 2 hex chars = share ID, rest = data
/// In binary: byte[0] = 0x80 | flags, byte[1] = share_id, byte[2..] = share_data
fn parse_share(share: &[u8]) -> Result<(u8, Vec<u8>), AppError> {
if share.len() < 3 {
return Err(AppError::Internal(anyhow::anyhow!(
"Share too short: {} bytes",
share.len()
)));
}
// First byte indicates bit mode (0x80 = 8-bit mode)
let config = share[0];
if config & 0xF0 != 0x80 {
// Check for alternate format (may have extra nibble)
// secrets.js can produce odd-length hex strings, which get padded with 0
// If first byte is 0x08, the share was padded
if config == 0x08 {
// Padded format: 0x08, 0x0N (where N is share ID), data...
if share.len() < 3 {
return Err(AppError::Internal(anyhow::anyhow!(
"Padded share too short"
)));
}
let id = share[1] & 0x0F; // Extract share ID from low nibble
return Ok((id, share[2..].to_vec()));
}
return Err(AppError::Internal(anyhow::anyhow!(
"Invalid share format: expected 8-bit mode (0x8_), got 0x{:02X}",
config
)));
}
// Second byte is share ID (1-255)
let id = share[1];
if id == 0 {
return Err(AppError::Internal(anyhow::anyhow!("Invalid share ID: 0")));
}
// Rest is share data
let data = share[2..].to_vec();
Ok((id, data))
}
// --- GF(2^8) arithmetic ---
/// GF(2^8) addition (XOR)
#[inline]
fn gf256_add(a: u8, b: u8) -> u8 {
a ^ b
}
/// GF(2^8) multiplication using AES polynomial (0x11B)
fn gf256_mul(a: u8, b: u8) -> u8 {
let mut result = 0u8;
let mut a = a;
let mut b = b;
while b != 0 {
if b & 1 != 0 {
result ^= a;
}
let high_bit = a & 0x80;
a <<= 1;
if high_bit != 0 {
a ^= 0x1B; // AES irreducible polynomial: x^8 + x^4 + x^3 + x + 1
}
b >>= 1;
}
result
}
/// GF(2^8) multiplicative inverse using extended Euclidean algorithm
///
/// # Errors
///
/// Returns an error if `a` is 0, since 0 has no multiplicative inverse.
fn gf256_inv(a: u8) -> Result<u8, AppError> {
if a == 0 {
// C-01: Return explicit error instead of silently returning 0
return Err(AppError::Internal(anyhow::anyhow!(
"GF(2^8) inverse undefined for zero"
)));
}
// Use exponentiation: a^254 = a^(-1) in GF(2^8)
// 254 = 128 + 64 + 32 + 16 + 8 + 4 + 2 = 11111110 in binary
let mut result = 1u8;
let mut base = a;
let mut exp = 254u8;
while exp > 0 {
if exp & 1 != 0 {
result = gf256_mul(result, base);
}
base = gf256_mul(base, base);
exp >>= 1;
}
Ok(result)
}
/// GF(2^8) division
///
/// # Errors
///
/// Returns an error if `b` is 0 (division by zero).
#[inline]
fn gf256_div(a: u8, b: u8) -> Result<u8, AppError> {
Ok(gf256_mul(a, gf256_inv(b)?))
}
/// Format raw 32-byte data as a secrets.js share
///
/// secrets.js format: byte[0] = 0x80 (8-bit mode), byte[1] = share_id, byte[2..] = data
pub(crate) fn format_share(id: u8, data: &[u8]) -> Vec<u8> {
let mut share = Vec::with_capacity(2 + data.len());
share.push(0x80); // 8-bit mode marker
share.push(id);
share.extend_from_slice(data);
share
}
/// Derive a child seed from a master seed using HKDF-SHA256
///
/// Index 0 = master seed directly (backward compatible).
/// Index > 0 = HKDF-SHA256(ikm=master_seed, salt="cedros-derived-wallet", info=u32_be(index)).
///
/// Uses a custom derivation (NOT BIP-44) to keep wallets app-locked.
pub fn derive_child_seed_from_bytes(master_seed: &[u8], index: u32) -> Result<Vec<u8>, AppError> {
if master_seed.len() != 32 {
return Err(AppError::Internal(anyhow::anyhow!(
"Invalid master seed length: expected 32, got {}",
master_seed.len()
)));
}
if index == 0 {
return Ok(master_seed.to_vec());
}
let hk = Hkdf::<Sha256>::new(Some(b"cedros-derived-wallet"), master_seed);
let mut child = vec![0u8; 32];
hk.expand(&index.to_be_bytes(), &mut child)
.map_err(|e| AppError::Internal(anyhow::anyhow!("HKDF expand failed: {}", e)))?;
Ok(child)
}
/// Derive the Solana pubkey (base58) for a given derivation index from a master seed
pub fn derive_pubkey_at_index(master_seed: &[u8], index: u32) -> Result<String, AppError> {
let mut child = derive_child_seed_from_bytes(master_seed, index)?;
let pubkey = derive_pubkey_from_seed(&child)?;
child.zeroize();
Ok(pubkey)
}
/// Derive Solana public key (base58) from 32-byte seed
pub(crate) fn derive_pubkey_from_seed(seed: &[u8]) -> Result<String, AppError> {
if seed.len() != 32 {
return Err(AppError::Internal(anyhow::anyhow!(
"Invalid seed length: expected 32, got {}",
seed.len()
)));
}
let seed_array: [u8; 32] = seed
.try_into()
.map_err(|_| AppError::Internal(anyhow::anyhow!("Seed conversion failed")))?;
let signing_key = SigningKey::from_bytes(&seed_array);
let verifying_key = signing_key.verifying_key();
let pubkey_bytes = verifying_key.as_bytes();
// Encode as base58
Ok(bs58::encode(pubkey_bytes).into_string())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_gf256_add() {
assert_eq!(gf256_add(0, 0), 0);
assert_eq!(gf256_add(0xFF, 0xFF), 0);
assert_eq!(gf256_add(0x53, 0xCA), 0x99);
}
#[test]
fn test_gf256_mul() {
assert_eq!(gf256_mul(0, 0x53), 0);
assert_eq!(gf256_mul(1, 0x53), 0x53);
assert_eq!(gf256_mul(0x53, 0xCA), 0x01); // These are multiplicative inverses
}
#[test]
fn test_gf256_inv() {
// Test some known inverses
assert_eq!(gf256_mul(0x53, gf256_inv(0x53).unwrap()), 1);
assert_eq!(gf256_mul(0xCA, gf256_inv(0xCA).unwrap()), 1);
assert_eq!(gf256_mul(0x02, gf256_inv(0x02).unwrap()), 1);
assert_eq!(gf256_mul(0xFF, gf256_inv(0xFF).unwrap()), 1);
}
#[test]
fn test_gf256_inv_zero_returns_error() {
// C-01: Verify that gf256_inv(0) returns an error instead of silently returning 0
let result = gf256_inv(0);
assert!(result.is_err(), "gf256_inv(0) should return an error");
}
#[test]
fn test_gf256_div() {
// a / a = 1
assert_eq!(gf256_div(0x53, 0x53).unwrap(), 1);
// a / 1 = a
assert_eq!(gf256_div(0x53, 1).unwrap(), 0x53);
}
#[test]
fn test_gf256_div_by_zero_returns_error() {
// C-01: Verify that gf256_div(a, 0) returns an error
let result = gf256_div(0x53, 0);
assert!(result.is_err());
}
#[test]
fn test_parse_share_valid() {
// 0x80 = 8-bit mode, 0x01 = share ID 1, followed by data
let share = vec![0x80, 0x01, 0xAB, 0xCD, 0xEF];
let (id, data) = parse_share(&share).unwrap();
assert_eq!(id, 1);
assert_eq!(data, vec![0xAB, 0xCD, 0xEF]);
}
#[test]
fn test_parse_share_padded_format() {
// Padded format: 0x08, 0x01, data...
let share = vec![0x08, 0x01, 0xAB, 0xCD];
let (id, data) = parse_share(&share).unwrap();
assert_eq!(id, 1);
assert_eq!(data, vec![0xAB, 0xCD]);
}
#[test]
fn test_parse_share_invalid_mode() {
let share = vec![0x40, 0x01, 0xAB]; // Wrong bit mode
assert!(parse_share(&share).is_err());
}
#[test]
fn test_parse_share_too_short() {
let share = vec![0x80, 0x01];
assert!(parse_share(&share).is_err());
}
#[test]
fn test_combine_shares_simple() {
// Create two simple shares with known values
// Share 1: ID=1, data=[0x01]
// Share 2: ID=2, data=[0x02]
let share1 = vec![0x80, 0x01, 0x01];
let share2 = vec![0x80, 0x02, 0x02];
let service = WalletSigningService::new();
let result = service.combine_shares(&share1, &share2);
assert!(result.is_ok());
}
#[tokio::test]
async fn test_derive_key_argon2() {
let service = WalletSigningService::new();
let params = KdfParams {
m_cost: 19456,
t_cost: 2,
p_cost: 1,
};
let salt = vec![0u8; 16];
let password = b"test-password".to_vec();
let key = service
.derive_key_argon2(password.clone(), salt.clone(), params.clone())
.await
.unwrap();
assert_eq!(key.len(), 32);
// Same inputs should produce same key
let key2 = service
.derive_key_argon2(password.clone(), salt.clone(), params.clone())
.await
.unwrap();
assert_eq!(key, key2);
// Different password should produce different key
let key3 = service
.derive_key_argon2(b"different".to_vec(), salt, params)
.await
.unwrap();
assert_ne!(key, key3);
}
#[test]
fn test_derive_key_hkdf() {
let service = WalletSigningService::new();
let prf_output = [0u8; 32];
let salt = [0u8; 32];
let key = service.derive_key_hkdf(&prf_output, &salt).unwrap();
assert_eq!(key.len(), 32);
// Same inputs should produce same key
let key2 = service.derive_key_hkdf(&prf_output, &salt).unwrap();
assert_eq!(key, key2);
}
#[test]
fn test_sign_with_seed() {
let service = WalletSigningService::new();
let seed = [0u8; 32];
let message = b"test message";
let signature = service.sign_with_seed(&seed, message).unwrap();
assert_eq!(signature.len(), 64); // Ed25519 signatures are 64 bytes
// Same inputs should produce same signature
let signature2 = service.sign_with_seed(&seed, message).unwrap();
assert_eq!(signature, signature2);
}
#[test]
fn test_sign_with_seed_invalid_length() {
let service = WalletSigningService::new();
let seed = [0u8; 16]; // Wrong length
let result = service.sign_with_seed(&seed, b"test");
assert!(result.is_err());
}
#[test]
fn test_encrypt_decrypt_roundtrip() {
let service = WalletSigningService::new();
let key = [0x42u8; 32];
let plaintext = b"secret data to encrypt";
// Encrypt
let (ciphertext, nonce) = service.encrypt_aes_gcm(&key, plaintext).unwrap();
assert_ne!(ciphertext.as_slice(), plaintext.as_slice());
// Decrypt
let decrypted = service.decrypt_aes_gcm(&key, &nonce, &ciphertext).unwrap();
assert_eq!(decrypted, plaintext);
}
#[tokio::test]
async fn test_reencrypt_share_a() {
use chrono::Utc;
use uuid::Uuid;
let service = WalletSigningService::new();
// Create test material
let old_password = "old-password-123";
let new_password = "new-password-456";
let kdf_params = KdfParams {
m_cost: 19456,
t_cost: 2,
p_cost: 1,
};
let old_salt = generate_salt();
// Derive old key and encrypt test data
let old_key = service
.derive_key_argon2(
old_password.as_bytes().to_vec(),
old_salt.to_vec(),
kdf_params.clone(),
)
.await
.unwrap();
let test_share_a = b"test share a data here!";
let (ciphertext, nonce) = service.encrypt_aes_gcm(&old_key, test_share_a).unwrap();
// Create wallet material
let material = WalletMaterialEntity {
id: Uuid::new_v4(),
user_id: Uuid::new_v4(),
solana_pubkey: "test-pubkey".to_string(),
scheme_version: 2,
share_a_auth_method: ShareAAuthMethod::Password,
share_a_ciphertext: ciphertext,
share_a_nonce: nonce.to_vec(),
share_a_kdf_salt: Some(old_salt.to_vec()),
share_a_kdf_params: Some(kdf_params.clone()),
prf_salt: None,
share_a_pin_hash: None,
share_b: vec![],
api_key_id: None,
created_at: Utc::now(),
updated_at: Utc::now(),
};
// Re-encrypt with new password
let reencrypted = service
.reencrypt_share_a(&material, old_password, new_password)
.await
.unwrap();
// Verify we can decrypt with new password
let new_key = service
.derive_key_argon2(
new_password.as_bytes().to_vec(),
reencrypted.salt.clone(),
kdf_params.clone(),
)
.await
.unwrap();
let decrypted = service
.decrypt_aes_gcm(&new_key, &reencrypted.nonce, &reencrypted.ciphertext)
.unwrap();
assert_eq!(decrypted, test_share_a);
// Verify old password no longer works
let old_key_attempt = service
.derive_key_argon2(
old_password.as_bytes().to_vec(),
reencrypted.salt.clone(),
kdf_params,
)
.await
.unwrap();
let decrypt_result = service.decrypt_aes_gcm(
&old_key_attempt,
&reencrypted.nonce,
&reencrypted.ciphertext,
);
assert!(decrypt_result.is_err());
}
#[test]
fn test_derive_child_seed_index_0_returns_master() {
let master = [0x42u8; 32];
let child = derive_child_seed_from_bytes(&master, 0).unwrap();
assert_eq!(child, master.to_vec());
}
#[test]
fn test_derive_child_seed_deterministic() {
let master = [0x42u8; 32];
let c1 = derive_child_seed_from_bytes(&master, 1).unwrap();
let c2 = derive_child_seed_from_bytes(&master, 1).unwrap();
assert_eq!(c1, c2);
assert_eq!(c1.len(), 32);
}
#[test]
fn test_derive_child_seed_distinct_per_index() {
let master = [0x42u8; 32];
let c1 = derive_child_seed_from_bytes(&master, 1).unwrap();
let c2 = derive_child_seed_from_bytes(&master, 2).unwrap();
assert_ne!(c1, c2);
// Neither should equal master
assert_ne!(c1, master.to_vec());
assert_ne!(c2, master.to_vec());
}
#[test]
fn test_derive_child_seed_invalid_length() {
let short = [0u8; 16];
assert!(derive_child_seed_from_bytes(&short, 1).is_err());
}
#[test]
fn test_derive_pubkey_at_index_backward_compat() {
let master = [0xABu8; 32];
// Index 0 pubkey should match derive_pubkey_from_seed(master)
let pk0 = derive_pubkey_at_index(&master, 0).unwrap();
let pk_direct = derive_pubkey_from_seed(&master).unwrap();
assert_eq!(pk0, pk_direct);
}
#[test]
fn test_derive_pubkey_at_index_distinct() {
let master = [0xABu8; 32];
let pk0 = derive_pubkey_at_index(&master, 0).unwrap();
let pk1 = derive_pubkey_at_index(&master, 1).unwrap();
assert_ne!(pk0, pk1);
}
#[tokio::test]
async fn test_reencrypt_share_a_wrong_auth_method() {
use chrono::Utc;
use uuid::Uuid;
let service = WalletSigningService::new();
// Create wallet material with passkey method (not password)
let material = WalletMaterialEntity {
id: Uuid::new_v4(),
user_id: Uuid::new_v4(),
solana_pubkey: "test-pubkey".to_string(),
scheme_version: 2,
share_a_auth_method: ShareAAuthMethod::Passkey,
share_a_ciphertext: vec![],
share_a_nonce: vec![],
share_a_kdf_salt: None,
share_a_kdf_params: None,
prf_salt: Some(vec![0u8; 32]),
share_a_pin_hash: None,
share_b: vec![],
api_key_id: None,
created_at: Utc::now(),
updated_at: Utc::now(),
};
// Should fail because wallet uses passkey, not password
let result = service.reencrypt_share_a(&material, "old", "new").await;
assert!(result.is_err());
}
#[test]
fn test_split_secret_roundtrip() {
let service = WalletSigningService::new();
let secret = [0x42u8; 32];
let (share_a, share_b, share_c) = service.split_secret(&secret).unwrap();
// Any 2 of 3 shares should reconstruct the original secret
let recovered_ab = service.combine_shares(&share_a, &share_b).unwrap();
assert_eq!(recovered_ab, secret.to_vec());
let recovered_ac = service.combine_shares(&share_a, &share_c).unwrap();
assert_eq!(recovered_ac, secret.to_vec());
let recovered_bc = service.combine_shares(&share_b, &share_c).unwrap();
assert_eq!(recovered_bc, secret.to_vec());
}
#[test]
fn test_split_secret_random_roundtrip() {
let service = WalletSigningService::new();
let mut secret = [0u8; 32];
OsRng.fill_bytes(&mut secret);
let (share_a, share_b, _) = service.split_secret(&secret).unwrap();
let recovered = service.combine_shares(&share_a, &share_b).unwrap();
assert_eq!(recovered, secret.to_vec());
}
#[test]
fn test_split_secret_rejects_empty() {
let service = WalletSigningService::new();
assert!(service.split_secret(&[]).is_err());
}
}