Skip to main content

quai_keystore/
lib.rs

1//! Bounded legacy Web3 v3 / x-quais keystore interchange.
2//!
3//! Native authenticated full-wallet backups belong to `quai-wallet`. This format
4//! only protects the private-key ciphertext with its legacy MAC. Optional mnemonic
5//! metadata is accepted only when its derived key matches the decrypted key.
6//! KDFs are synchronous CPU work: use a bounded worker, never an async executor/UI thread.
7use aes::cipher::{KeyIvInit, StreamCipher};
8use quai_crypto::{SecretKey, keccak256};
9use quai_primitives::Address;
10use quai_wallet::{ExtendedPrivateKey, Language, Mnemonic};
11use serde_json::Value;
12use std::fmt;
13use subtle::ConstantTimeEq;
14use unicode_normalization::UnicodeNormalization;
15use zeroize::Zeroizing;
16/// Standalone guarded key derivation, independent of encrypted document parsing.
17pub mod derive;
18mod json;
19
20/// Sanitized failures never include passwords, keys or mnemonic metadata.
21///
22/// Non-exhaustive: `WeakParameters` is new in 0.1.0-alpha.4, and marking the
23/// enum makes later variants additive.
24#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
25#[non_exhaustive]
26pub enum KeystoreError {
27    /// Unsupported or ambiguous document/cipher/KDF/extension.
28    #[error("invalid or unsupported legacy keystore")]
29    Format,
30    /// Resource policy exceeded before expensive work.
31    #[error("legacy keystore exceeds resource limits")]
32    Limit,
33    /// MAC, key/address or mnemonic derivation does not match.
34    #[error("legacy keystore authentication or ownership check failed")]
35    Authentication,
36    /// OS or Web Crypto entropy failed.
37    #[error("secure randomness unavailable")]
38    Randomness,
39    /// The document's KDF parameters are below the accepted work or salt floor.
40    ///
41    /// Distinct from [`KeystoreError::Limit`], which reports a ceiling, so a
42    /// caller can deliberately accept a weak document by lowering the floor
43    /// rather than by disabling the bound in both directions.
44    #[error("legacy keystore key derivation is weaker than the accepted minimum")]
45    WeakParameters,
46}
47/// Explicit text normalization versus exact password bytes, matching quais.js.
48pub enum Password<'a> {
49    /// UTF-8 after NFKC normalization (not BIP39's NFKD convention).
50    Text(&'a str),
51    /// Exact bytes without Unicode normalization.
52    Bytes(&'a [u8]),
53}
54impl fmt::Debug for Password<'_> {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        f.write_str("Password([REDACTED])")
57    }
58}
59impl Password<'_> {
60    fn guarded(&self) -> Result<Zeroizing<Vec<u8>>, KeystoreError> {
61        let bytes = match self {
62            Self::Text(s) if s.len() <= 1024 => {
63                // Allocate the final bounded guard before copying any normalized
64                // secret; incremental growth must not leave prior heap copies.
65                let mut normalized = Zeroizing::new(Vec::with_capacity(4096));
66                let mut utf8 = Zeroizing::new([0u8; 4]);
67                for character in s.nfkc() {
68                    let encoded = character.encode_utf8(&mut utf8[..]).as_bytes();
69                    if normalized.len() + encoded.len() > 4096 {
70                        return Err(KeystoreError::Limit);
71                    }
72                    normalized.extend_from_slice(encoded);
73                }
74                normalized
75            }
76            Self::Bytes(b) if b.len() <= 1024 => Zeroizing::new(b.to_vec()),
77            _ => return Err(KeystoreError::Limit),
78        };
79        if bytes.len() > 4096 {
80            return Err(KeystoreError::Limit);
81        }
82        Ok(bytes)
83    }
84}
85/// Fixed hostile-input KDF limits; all checked before deriving or allocating work memory.
86///
87/// Construct with [`KdfLimits::default`] and adjust through the `with_*` methods.
88/// The type is `#[non_exhaustive]` deliberately: the floors below were added
89/// after the first alpha, and adding a public field to a struct that consumers
90/// construct by literal is a breaking change. Marking it now means later policy
91/// knobs are additive, and it forces callers onto a path where a new bound is
92/// inherited from `default()` rather than silently skipped.
93#[derive(Clone, Copy, Debug)]
94#[non_exhaustive]
95pub struct KdfLimits {
96    /// Maximum scrypt V/B/T memory even with parallel feature unification;
97    /// default 256 MiB plus 64 KiB.
98    ///
99    /// The slack is deliberate: the widely used N=2^18, r=8, p=1 documents
100    /// (geth's and MetaMask's standard) need 256 MiB of V plus 2 KiB of B and T
101    /// workspace, so a flat 256 MiB refused them by 2 KiB.
102    pub max_memory_bytes: u64,
103    /// Maximum N*r*p work units; default 2^24.
104    pub max_scrypt_work: u64,
105    /// Maximum PBKDF2 rounds; default 2,000,000.
106    pub max_pbkdf2_rounds: u32,
107    /// Minimum N*r*p work units; default 2^20.
108    ///
109    /// Ceilings alone bound only what the document can cost *us*. A floor bounds
110    /// what it costs an attacker: nothing stops a hostile file declaring
111    /// `n=2, r=1, p=1`, which decrypts correctly and turns an import flow into
112    /// an offline oracle against the password the user just typed, at roughly
113    /// one hash per guess. Set to zero to accept any work factor deliberately.
114    pub min_scrypt_work: u64,
115    /// Minimum PBKDF2 rounds; default 100,000. Zero accepts any count.
116    pub min_pbkdf2_rounds: u32,
117    /// Minimum salt length in bytes; default 16.
118    ///
119    /// A short salt makes precomputation across victims viable; the format
120    /// otherwise permits a single byte.
121    pub min_salt_bytes: usize,
122}
123impl Default for KdfLimits {
124    fn default() -> Self {
125        Self {
126            max_memory_bytes: 256 * 1024 * 1024 + 64 * 1024,
127            max_scrypt_work: 1 << 24,
128            max_pbkdf2_rounds: 2_000_000,
129            min_scrypt_work: 1 << 20,
130            min_pbkdf2_rounds: 100_000,
131            min_salt_bytes: 16,
132        }
133    }
134}
135impl KdfLimits {
136    /// Set the maximum scrypt working memory in bytes.
137    #[must_use]
138    pub fn with_max_memory_bytes(mut self, bytes: u64) -> Self {
139        self.max_memory_bytes = bytes;
140        self
141    }
142    /// Set the maximum scrypt `N*r*p` work.
143    #[must_use]
144    pub fn with_max_scrypt_work(mut self, work: u64) -> Self {
145        self.max_scrypt_work = work;
146        self
147    }
148    /// Set the maximum PBKDF2 round count.
149    #[must_use]
150    pub fn with_max_pbkdf2_rounds(mut self, rounds: u32) -> Self {
151        self.max_pbkdf2_rounds = rounds;
152        self
153    }
154    /// Set the minimum scrypt `N*r*p` work. Zero accepts any work factor.
155    #[must_use]
156    pub fn with_min_scrypt_work(mut self, work: u64) -> Self {
157        self.min_scrypt_work = work;
158        self
159    }
160    /// Set the minimum PBKDF2 round count. Zero accepts any count.
161    #[must_use]
162    pub fn with_min_pbkdf2_rounds(mut self, rounds: u32) -> Self {
163        self.min_pbkdf2_rounds = rounds;
164        self
165    }
166    /// Set the minimum salt length in bytes. Zero accepts any salt.
167    #[must_use]
168    pub fn with_min_salt_bytes(mut self, bytes: usize) -> Self {
169        self.min_salt_bytes = bytes;
170        self
171    }
172    /// Restore the default password-strength floors, keeping other settings.
173    ///
174    /// The counterpart to [`Self::without_strength_floors`], for a caller that
175    /// derives from a human-chosen password and wants the document policy.
176    #[must_use]
177    pub fn with_strength_floors(self) -> Self {
178        let defaults = Self::default();
179        self.with_min_scrypt_work(defaults.min_scrypt_work)
180            .with_min_pbkdf2_rounds(defaults.min_pbkdf2_rounds)
181            .with_min_salt_bytes(defaults.min_salt_bytes)
182    }
183    /// Remove the password-strength floors, keeping every resource ceiling.
184    ///
185    /// This tracks floors added in later releases: a floor introduced after this
186    /// call site was written is also removed by it. That is the intent for a
187    /// caller whose parameters are its own, and the reason a document importer
188    /// should never use it.
189    ///
190    /// The floors defend against an attacker-authored document. Removing them is
191    /// the right call when the parameters are the caller's own, or the salt is
192    /// fixed by a surrounding protocol, or the input is not a human-chosen
193    /// password. It is the wrong call for importing a document someone sent you.
194    #[must_use]
195    pub fn without_strength_floors(self) -> Self {
196        self.with_min_scrypt_work(0)
197            .with_min_pbkdf2_rounds(0)
198            .with_min_salt_bytes(0)
199    }
200}
201#[derive(Clone, Copy)]
202enum Kdf {
203    Scrypt { log_n: u8, r: u32, p: u32 },
204    Pbkdf2 { rounds: u32, sha512: bool },
205}
206impl Kdf {
207    fn validate(self, limits: KdfLimits) -> Result<(), KeystoreError> {
208        // Hard ceilings also bound callers who accidentally pass unbounded policies.
209        if limits.max_memory_bytes > 1024 * 1024 * 1024
210            || limits.max_scrypt_work > 1 << 28
211            || limits.max_pbkdf2_rounds > 10_000_000
212        {
213            return Err(KeystoreError::Limit);
214        }
215        // A floor above its own ceiling admits nothing. Report it as a policy
216        // error rather than letting every document fail as WeakParameters with
217        // no indication that the limits themselves are unsatisfiable.
218        if limits.min_scrypt_work > limits.max_scrypt_work
219            || limits.min_pbkdf2_rounds > limits.max_pbkdf2_rounds
220        {
221            return Err(KeystoreError::Limit);
222        }
223        match self {
224            Self::Scrypt { log_n, r, p } => {
225                let n = 1u64.checked_shl(log_n.into()).ok_or(KeystoreError::Limit)?;
226                // Cargo features unify: another dependency can enable scrypt/parallel.
227                // Bound B plus a V/T workspace for every lane, not just one worker.
228                let memory = n
229                    .checked_add(2)
230                    .and_then(|x| x.checked_mul(u64::from(p)))
231                    .and_then(|x| x.checked_mul(u64::from(r)))
232                    .and_then(|x| x.checked_mul(128))
233                    .ok_or(KeystoreError::Limit)?;
234                let work = n
235                    .checked_mul(u64::from(r))
236                    .and_then(|x| x.checked_mul(u64::from(p)))
237                    .ok_or(KeystoreError::Limit)?;
238                if memory > limits.max_memory_bytes || work > limits.max_scrypt_work {
239                    return Err(KeystoreError::Limit);
240                }
241                if work < limits.min_scrypt_work {
242                    return Err(KeystoreError::WeakParameters);
243                }
244                // RFC 7914's N < 2^(16r). quais.js enforces it and scrypt 0.12
245                // no longer does, so without it we would open what quais.js refuses.
246                if u32::from(log_n) >= r.saturating_mul(16) {
247                    return Err(KeystoreError::Format);
248                }
249                scrypt::Params::new(log_n, r, p).map_err(|_| KeystoreError::Format)?;
250            }
251            Self::Pbkdf2 { rounds, .. } => {
252                if rounds == 0 || rounds > limits.max_pbkdf2_rounds {
253                    return Err(KeystoreError::Limit);
254                }
255                if rounds < limits.min_pbkdf2_rounds {
256                    return Err(KeystoreError::WeakParameters);
257                }
258            }
259        }
260        Ok(())
261    }
262    fn derive(
263        self,
264        password: &[u8],
265        salt: &[u8],
266        limits: KdfLimits,
267    ) -> Result<Zeroizing<[u8; 64]>, KeystoreError> {
268        self.validate(limits)?;
269        // Checked here rather than at parse time so the floor applies wherever a
270        // derivation actually happens, including the mnemonic section.
271        if salt.len() < limits.min_salt_bytes {
272            return Err(KeystoreError::WeakParameters);
273        }
274        let mut key = Zeroizing::new([0; 64]);
275        match self {
276            Self::Scrypt { log_n, r, p } => scrypt::scrypt(
277                password,
278                salt,
279                &scrypt::Params::new(log_n, r, p).map_err(|_| KeystoreError::Format)?,
280                key.as_mut(),
281            )
282            .map_err(|_| KeystoreError::Format)?,
283            Self::Pbkdf2 {
284                rounds,
285                sha512: false,
286            } => {
287                pbkdf2::pbkdf2_hmac::<pbkdf2::sha2::Sha256>(password, salt, rounds, &mut key[..32])
288            }
289            Self::Pbkdf2 {
290                rounds,
291                sha512: true,
292            } => {
293                pbkdf2::pbkdf2_hmac::<pbkdf2::sha2::Sha512>(password, salt, rounds, &mut key[..32])
294            }
295        }
296        Ok(key)
297    }
298}
299struct MnemonicData {
300    ciphertext: Vec<u8>,
301    iv: [u8; 16],
302    language: Language,
303    path: String,
304}
305/// Validated, encrypted document. Parsing does no KDF or entropy work.
306pub struct Keystore {
307    address: Address,
308    iv: [u8; 16],
309    ciphertext: [u8; 32],
310    mac: [u8; 32],
311    salt: Vec<u8>,
312    kdf: Kdf,
313    mnemonic: Option<MnemonicData>,
314}
315impl fmt::Debug for Keystore {
316    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317        f.write_str("Keystore([ENCRYPTED])")
318    }
319}
320/// Decrypted key and optional mnemonic whose derivation was checked against it.
321pub struct KeystoreAccount {
322    key: SecretKey,
323    mnemonic: Option<VerifiedMnemonic>,
324}
325impl fmt::Debug for KeystoreAccount {
326    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327        f.write_str("KeystoreAccount([REDACTED])")
328    }
329}
330impl KeystoreAccount {
331    /// Public account derived from the actual key.
332    pub fn address(&self) -> Address {
333        self.key.public_key().address()
334    }
335    /// Borrow the guarded signing key explicitly.
336    pub fn secret_key(&self) -> &SecretKey {
337        &self.key
338    }
339    /// Mnemonic present only after empty-passphrase derivation ownership verification.
340    pub fn mnemonic(&self) -> Option<&VerifiedMnemonic> {
341        self.mnemonic.as_ref()
342    }
343    /// Transfer key ownership; any mnemonic held in this object is dropped and zeroized.
344    pub fn into_secret_key(self) -> SecretKey {
345        self.key
346    }
347}
348/// Derivation-verified mnemonic. Legacy format cannot represent a BIP39 passphrase.
349pub struct VerifiedMnemonic {
350    mnemonic: Mnemonic,
351    path: String,
352}
353impl fmt::Debug for VerifiedMnemonic {
354    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355        f.write_str("VerifiedMnemonic([REDACTED])")
356    }
357}
358impl VerifiedMnemonic {
359    /// Explicit secret mnemonic access.
360    pub fn mnemonic(&self) -> &Mnemonic {
361        &self.mnemonic
362    }
363    /// Exact absolute derivation path validated against the private key.
364    pub fn path(&self) -> &str {
365        &self.path
366    }
367}
368fn string(v: &Value) -> Result<&str, KeystoreError> {
369    v.as_str().ok_or(KeystoreError::Format)
370}
371fn uint(v: &Value) -> Result<u64, KeystoreError> {
372    v.as_u64().ok_or(KeystoreError::Format)
373}
374fn bytes(v: &Value, min: usize, max: usize) -> Result<Vec<u8>, KeystoreError> {
375    let text = string(v)?;
376    let text = text.strip_prefix("0x").unwrap_or(text);
377    if text.len() % 2 != 0
378        || text.len() / 2 < min
379        || text.len() / 2 > max
380        || !text.bytes().all(|b| b.is_ascii_hexdigit())
381    {
382        return Err(KeystoreError::Format);
383    }
384    text.as_bytes()
385        .chunks_exact(2)
386        .map(|pair| {
387            u8::from_str_radix(
388                std::str::from_utf8(pair).map_err(|_| KeystoreError::Format)?,
389                16,
390            )
391            .map_err(|_| KeystoreError::Format)
392        })
393        .collect()
394}
395fn fixed<const N: usize>(v: &Value) -> Result<[u8; N], KeystoreError> {
396    bytes(v, N, N)?
397        .try_into()
398        .map_err(|_| KeystoreError::Format)
399}
400fn allowed(v: &Value, keys: &[&str]) -> Result<(), KeystoreError> {
401    let map = v.as_object().ok_or(KeystoreError::Format)?;
402    if map.keys().any(|k| !keys.contains(&k.as_str())) {
403        return Err(KeystoreError::Format);
404    }
405    Ok(())
406}
407fn language(locale: &str) -> Result<Language, KeystoreError> {
408    match locale {
409        "en" => Ok(Language::English),
410        "es" => Ok(Language::Spanish),
411        "fr" => Ok(Language::French),
412        "it" => Ok(Language::Italian),
413        "ja" => Ok(Language::Japanese),
414        "ko" => Ok(Language::Korean),
415        "zh_cn" => Ok(Language::SimplifiedChinese),
416        "zh_tw" => Ok(Language::TraditionalChinese),
417        "cz" => Ok(Language::Czech),
418        "pt" => Ok(Language::Portuguese),
419        _ => Err(KeystoreError::Format),
420    }
421}
422impl Keystore {
423    /// Parse strict v3 AES-128-CTR with scrypt or PBKDF2-HMAC-SHA256/SHA512.
424    /// Case-insensitive field aliases are accepted only if unique. Unknown extensions
425    /// fail explicitly. An address is mandatory to detect un-MACed IV tampering.
426    pub fn from_json(document: &[u8], limits: KdfLimits) -> Result<Self, KeystoreError> {
427        let v = json::parse(document)?;
428        allowed(&v, &["address", "id", "version", "crypto", "x-quais"])?;
429        if uint(&v["version"])? != 3 {
430            return Err(KeystoreError::Format);
431        }
432        let address = Address::from_bytes(fixed::<20>(&v["address"])?);
433        let c = &v["crypto"];
434        allowed(
435            c,
436            &[
437                "cipher",
438                "cipherparams",
439                "ciphertext",
440                "kdf",
441                "kdfparams",
442                "mac",
443            ],
444        )?;
445        allowed(&c["cipherparams"], &["iv"])?;
446        if string(&c["cipher"])? != "aes-128-ctr" {
447            return Err(KeystoreError::Format);
448        }
449        let p = &c["kdfparams"];
450        if uint(&p["dklen"])? != 32 {
451            return Err(KeystoreError::Format);
452        }
453        let kdf = match string(&c["kdf"])? {
454            "scrypt" => {
455                allowed(p, &["salt", "n", "r", "p", "dklen"])?;
456                let n = uint(&p["n"])?;
457                if !n.is_power_of_two() || n < 2 {
458                    return Err(KeystoreError::Format);
459                }
460                Kdf::Scrypt {
461                    log_n: n.trailing_zeros() as u8,
462                    r: uint(&p["r"])?
463                        .try_into()
464                        .map_err(|_| KeystoreError::Limit)?,
465                    p: uint(&p["p"])?
466                        .try_into()
467                        .map_err(|_| KeystoreError::Limit)?,
468                }
469            }
470            "pbkdf2" => {
471                allowed(p, &["salt", "c", "prf", "dklen"])?;
472                let sha512 = match string(&p["prf"])? {
473                    "hmac-sha256" => false,
474                    "hmac-sha512" => true,
475                    _ => return Err(KeystoreError::Format),
476                };
477                Kdf::Pbkdf2 {
478                    rounds: uint(&p["c"])?
479                        .try_into()
480                        .map_err(|_| KeystoreError::Limit)?,
481                    sha512,
482                }
483            }
484            _ => return Err(KeystoreError::Format),
485        };
486        kdf.validate(limits)?;
487        let mnemonic = if let Some(m) = v.get("x-quais") {
488            allowed(
489                m,
490                &[
491                    "version",
492                    "mnemonicciphertext",
493                    "mnemoniccounter",
494                    "path",
495                    "locale",
496                    "client",
497                    "gethfilename",
498                ],
499            )?;
500            if !matches!(kdf, Kdf::Scrypt { .. }) || string(&m["version"])? != "0.1" {
501                return Err(KeystoreError::Format);
502            }
503            let ciphertext = bytes(&m["mnemonicciphertext"], 16, 32)?;
504            if ciphertext.len() % 4 != 0 {
505                return Err(KeystoreError::Format);
506            }
507            let path = m
508                .get("path")
509                .map(string)
510                .transpose()?
511                .unwrap_or("m/44'/994'/0'/0/0");
512            if path.is_empty() || path.len() > 1024 {
513                return Err(KeystoreError::Limit);
514            }
515            Some(MnemonicData {
516                ciphertext,
517                iv: fixed(&m["mnemoniccounter"])?,
518                path: path.to_owned(),
519                language: language(m.get("locale").map(string).transpose()?.unwrap_or("en"))?,
520            })
521        } else {
522            None
523        };
524        Ok(Self {
525            address,
526            iv: fixed(&c["cipherparams"]["iv"])?,
527            ciphertext: fixed(&c["ciphertext"])?,
528            mac: fixed(&c["mac"])?,
529            salt: bytes(&p["salt"], 1, 64)?,
530            kdf,
531            mnemonic,
532        })
533    }
534    /// Synchronously derive, verify MAC, decrypt and validate all available ownership.
535    /// KDF limits are rechecked here so parsing with a larger limit cannot bypass policy.
536    pub fn decrypt(
537        &self,
538        password: Password<'_>,
539        limits: KdfLimits,
540    ) -> Result<KeystoreAccount, KeystoreError> {
541        let password = password.guarded()?;
542        let derived = self.kdf.derive(&password, &self.salt, limits)?;
543        let mut mac_data = Zeroizing::new([0u8; 48]);
544        mac_data[..16].copy_from_slice(&derived[16..32]);
545        mac_data[16..].copy_from_slice(&self.ciphertext);
546        if !bool::from(keccak256(&mac_data[..]).ct_eq(&self.mac)) {
547            return Err(KeystoreError::Authentication);
548        }
549        let mut plain = Zeroizing::new(self.ciphertext);
550        ctr::Ctr128BE::<aes::Aes128>::new_from_slices(&derived[..16], &self.iv)
551            .map_err(|_| KeystoreError::Format)?
552            .try_apply_keystream(&mut plain[..])
553            .map_err(|_| KeystoreError::Format)?;
554        let key = SecretKey::from_bytes(&plain).map_err(|_| KeystoreError::Authentication)?;
555        if key.public_key().address() != self.address {
556            return Err(KeystoreError::Authentication);
557        }
558        let mnemonic = if let Some(m) = &self.mnemonic {
559            let mut entropy = Zeroizing::new(m.ciphertext.clone());
560            ctr::Ctr128BE::<aes::Aes256>::new_from_slices(&derived[32..], &m.iv)
561                .map_err(|_| KeystoreError::Format)?
562                .try_apply_keystream(&mut entropy)
563                .map_err(|_| KeystoreError::Format)?;
564            Some(verify_mnemonic(&key, &entropy, m.language, &m.path)?)
565        } else {
566            None
567        };
568        Ok(KeystoreAccount { key, mnemonic })
569    }
570}
571fn verify_mnemonic(
572    key: &SecretKey,
573    entropy: &[u8],
574    language: Language,
575    path: &str,
576) -> Result<VerifiedMnemonic, KeystoreError> {
577    let mnemonic =
578        Mnemonic::from_entropy(language, entropy).map_err(|_| KeystoreError::Authentication)?;
579    let seed = mnemonic.to_seed("");
580    let derived = ExtendedPrivateKey::from_seed(seed.expose())
581        .and_then(|root| root.derive_path(path))
582        .and_then(|node| node.secret_key())
583        .map_err(|_| KeystoreError::Authentication)?;
584    if !bool::from(
585        derived
586            .export_bytes()
587            .as_bytes()
588            .ct_eq(key.export_bytes().as_bytes()),
589    ) {
590        return Err(KeystoreError::Authentication);
591    }
592    Ok(VerifiedMnemonic {
593        mnemonic,
594        path: path.to_owned(),
595    })
596}
597
598/// Encrypted legacy JSON; diagnostics omit ciphertext, identifiers and metadata.
599pub struct EncryptedKeystore(String);
600impl fmt::Debug for EncryptedKeystore {
601    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
602        f.write_str("EncryptedKeystore([ENCRYPTED])")
603    }
604}
605impl EncryptedKeystore {
606    /// Explicit export of encrypted JSON for legacy interchange.
607    pub fn as_json(&self) -> &str {
608        &self.0
609    }
610}
611/// Export a single key using fresh OS/Web Crypto salt, IV and UUID and pinned-JS scrypt defaults.
612/// This synchronous operation uses about 128 MiB of scrypt working memory.
613pub fn encrypt(
614    key: &SecretKey,
615    password: Password<'_>,
616) -> Result<EncryptedKeystore, KeystoreError> {
617    encrypt_randomized(key, password, None)
618}
619/// Export a derivation-verified mnemonic with a legacy key. Only the empty BIP39
620/// passphrase is representable; mismatched entropy/language/path fails before KDF.
621/// Metadata is not authenticated by this legacy format; import always rederives it.
622pub fn encrypt_with_mnemonic(
623    key: &SecretKey,
624    password: Password<'_>,
625    entropy: &[u8],
626    language: Language,
627    path: &str,
628) -> Result<EncryptedKeystore, KeystoreError> {
629    if path.len() > 1024 {
630        return Err(KeystoreError::Limit);
631    }
632    verify_mnemonic(key, entropy, language, path)?;
633    encrypt_randomized(key, password, Some((entropy, language, path)))
634}
635fn encrypt_randomized(
636    key: &SecretKey,
637    password: Password<'_>,
638    mnemonic: Option<(&[u8], Language, &str)>,
639) -> Result<EncryptedKeystore, KeystoreError> {
640    let password = password.guarded()?;
641    let mut random = [0; 80];
642    quai_crypto::fill_random(&mut random).map_err(|_| KeystoreError::Randomness)?;
643    seal(
644        key,
645        &password,
646        mnemonic,
647        Kdf::Scrypt {
648            log_n: 17,
649            r: 8,
650            p: 1,
651        },
652        &random,
653        KdfLimits::default(),
654    )
655}
656fn hex(bytes: &[u8]) -> String {
657    bytes.iter().map(|b| format!("{b:02x}")).collect()
658}
659fn locale(language: Language) -> &'static str {
660    match language {
661        Language::English => "en",
662        Language::Spanish => "es",
663        Language::French => "fr",
664        Language::Italian => "it",
665        Language::Japanese => "ja",
666        Language::Korean => "ko",
667        Language::SimplifiedChinese => "zh_cn",
668        Language::TraditionalChinese => "zh_tw",
669        Language::Czech => "cz",
670        Language::Portuguese => "pt",
671    }
672}
673/// `limits` governs the derivation this export performs. Production callers pass
674/// the defaults; the deterministic JavaScript-parity tests lower the floor so
675/// they can reproduce the reference's deliberately cheap fixture parameters.
676fn seal(
677    key: &SecretKey,
678    password: &[u8],
679    mnemonic: Option<(&[u8], Language, &str)>,
680    kdf: Kdf,
681    random: &[u8; 80],
682    limits: KdfLimits,
683) -> Result<EncryptedKeystore, KeystoreError> {
684    let Kdf::Scrypt { log_n, r, p } = kdf else {
685        return Err(KeystoreError::Format);
686    };
687    // Export parameters are this crate's own constants, not an attacker-authored
688    // document, so only the resource ceilings apply. Coupling export to the
689    // strength floor at runtime would let a future floor increase break the
690    // crate's own exports for every user; the relationship is asserted by a
691    // test instead, which fails at build time rather than in the field.
692    let derived = kdf.derive(password, &random[..32], limits.without_strength_floors())?;
693    let mut ciphertext = Zeroizing::new(*key.export_bytes().as_bytes());
694    ctr::Ctr128BE::<aes::Aes128>::new_from_slices(&derived[..16], &random[32..48])
695        .map_err(|_| KeystoreError::Format)?
696        .try_apply_keystream(&mut ciphertext[..])
697        .map_err(|_| KeystoreError::Format)?;
698    let mut mac_data = Zeroizing::new([0; 48]);
699    mac_data[..16].copy_from_slice(&derived[16..32]);
700    mac_data[16..].copy_from_slice(&ciphertext[..]);
701    let mut uuid: [u8; 16] = random[48..64]
702        .try_into()
703        .map_err(|_| KeystoreError::Format)?;
704    uuid[6] = (uuid[6] & 15) | 64;
705    uuid[8] = (uuid[8] & 63) | 128;
706    let id = hex(&uuid);
707    let id = format!(
708        "{}-{}-{}-{}-{}",
709        &id[..8],
710        &id[8..12],
711        &id[12..16],
712        &id[16..20],
713        &id[20..]
714    );
715    let mut document = serde_json::json!({"address":hex(key.public_key().address().bytes()),"id":id,"version":3,"Crypto":{"cipher":"aes-128-ctr","cipherparams":{"iv":hex(&random[32..48])},"ciphertext":hex(&ciphertext[..]),"kdf":"scrypt","kdfparams":{"salt":hex(&random[..32]),"n":1u64<<log_n,"r":r,"p":p,"dklen":32},"mac":hex(&keccak256(&mac_data[..]))}});
716    if let Some((entropy, language, path)) = mnemonic {
717        let mut encrypted = Zeroizing::new(entropy.to_vec());
718        ctr::Ctr128BE::<aes::Aes256>::new_from_slices(&derived[32..], &random[64..])
719            .map_err(|_| KeystoreError::Format)?
720            .try_apply_keystream(&mut encrypted)
721            .map_err(|_| KeystoreError::Format)?;
722        document["x-quais"] = serde_json::json!({"version":"0.1","client":"quai-rust-sdk","path":path,"locale":locale(language),"mnemonicCounter":hex(&random[64..]),"mnemonicCiphertext":hex(&encrypted)});
723    }
724    Ok(EncryptedKeystore(
725        serde_json::to_string(&document).map_err(|_| KeystoreError::Format)?,
726    ))
727}
728
729#[cfg(test)]
730mod tests {
731    use super::*;
732
733    /// Limits that accept the reference fixtures' deliberately cheap KDF parameters.
734    ///
735    /// The pinned JavaScript vectors use `n=16, r=1, p=1` so the suite runs fast.
736    /// Production defaults reject that as `WeakParameters`; importing a fixture is
737    /// the intended "I know this is weak" case, so it lowers the floor explicitly
738    /// rather than the suite disabling the bound globally.
739    fn fixture_limits() -> KdfLimits {
740        // Uses the same builder an external caller must use. A struct literal
741        // would compile here, inside the defining crate, and would quietly stop
742        // exercising the path every consumer is actually held to.
743        KdfLimits::default().without_strength_floors()
744    }
745
746    #[test]
747    fn normalized_password_growth_is_bounded_before_secret_reallocation() {
748        // U+FDFA expands to a 33-byte Arabic phrase under NFKC.
749        let near_limit = "\u{fdfa}".repeat(124);
750        let guarded = Password::Text(&near_limit).guarded().unwrap();
751        assert_eq!(guarded.len(), 4092);
752        assert_eq!(guarded.capacity(), 4096);
753        let over_limit = "\u{fdfa}".repeat(125);
754        assert!(matches!(
755            Password::Text(&over_limit).guarded(),
756            Err(KeystoreError::Limit)
757        ));
758        assert!(Password::Text("").guarded().unwrap().is_empty());
759    }
760
761    #[test]
762    fn deterministic_rust_encryption_matches_javascript_ciphertext_mac_and_uuid() {
763        let fixture: Value =
764            serde_json::from_str(include_str!("../tests/fixtures/keystores.json")).unwrap();
765        let v = &fixture["vectors"][0];
766        let key_bytes = fixed::<32>(&v["expected"]["privateKey"]).unwrap();
767        let key = SecretKey::from_bytes(&key_bytes).unwrap();
768        let mut random = [0; 80];
769        random[..32].fill(0x11);
770        random[32..48].fill(0x22);
771        random[48..64].fill(0x33);
772        random[64..].fill(0x44);
773        let encrypted = seal(
774            &key,
775            b"PUBLIC password",
776            None,
777            Kdf::Scrypt {
778                log_n: 4,
779                r: 1,
780                p: 1,
781            },
782            &random,
783            fixture_limits(),
784        )
785        .unwrap();
786        assert_eq!(
787            serde_json::from_str::<Value>(encrypted.as_json()).unwrap(),
788            v["json"]
789        );
790        for row in fixture["vectors"]
791            .as_array()
792            .unwrap()
793            .iter()
794            .filter(|r| r["expected"].get("mnemonic").is_some())
795        {
796            let key =
797                SecretKey::from_bytes(&fixed(&row["expected"]["privateKey"]).unwrap()).unwrap();
798            let m = &row["expected"]["mnemonic"];
799            let entropy = bytes(&m["entropy"], 16, 32).unwrap();
800            let language = language(string(&m["locale"]).unwrap()).unwrap();
801            let path = string(&m["path"]).unwrap();
802            let encrypted = seal(
803                &key,
804                b"PUBLIC mnemonic",
805                Some((&entropy, language, path)),
806                Kdf::Scrypt {
807                    log_n: 4,
808                    r: 1,
809                    p: 1,
810                },
811                &random,
812                fixture_limits(),
813            )
814            .unwrap();
815            let result: Value = serde_json::from_str(encrypted.as_json()).unwrap();
816            assert_eq!(result["Crypto"], row["json"]["Crypto"]);
817            for field in ["mnemonicCiphertext", "mnemonicCounter", "path", "locale"] {
818                assert_eq!(result["x-quais"][field], row["json"]["x-quais"][field]);
819            }
820            Keystore::from_json(encrypted.as_json().as_bytes(), fixture_limits())
821                .unwrap()
822                .decrypt(Password::Text("PUBLIC mnemonic"), fixture_limits())
823                .unwrap();
824        }
825    }
826}