aboutsummaryrefslogtreecommitdiffstats
path: root/src/seed.js
diff options
context:
space:
mode:
Diffstat (limited to 'src/seed.js')
-rw-r--r--src/seed.js53
1 files changed, 53 insertions, 0 deletions
diff --git a/src/seed.js b/src/seed.js
new file mode 100644
index 0000000..0592035
--- /dev/null
+++ b/src/seed.js
@@ -0,0 +1,53 @@
+// The BIP-39 seed of a recovery phrase, stretched once per phrase.
+//
+// Stretching is PBKDF2-HMAC-SHA512 over 2048 rounds. Done in JavaScript
+// (@scure/bip39, nostr-tools' nip06) it cost every launch twice over — the
+// wallet's account key and the nostr identity each stretched the same words —
+// and was the largest single piece of opening a wallet on a phone. The browser
+// has the same function built in (WebCrypto), many times faster but
+// asynchronous: warmSeed() runs it before a wallet opens, and the synchronous
+// readers (seedSync) find the result waiting. A reader that comes first
+// still gets the right seed, the slow way, and leaves it for the rest.
+import { mnemonicToSeedSync } from '@scure/bip39';
+
+const seeds = new Map(); // `${phrase}\n${passphrase}` → Uint8Array(64)
+const MAX = 8; // a few accounts on one device; oldest out first
+const key = (mnemonic, passphrase) => `${mnemonic}\n${passphrase || ''}`;
+function keep(k, seed) {
+ seeds.delete(k);
+ seeds.set(k, seed);
+ while (seeds.size > MAX) seeds.delete(seeds.keys().next().value);
+}
+
+export function seedSync(mnemonic, passphrase = '') {
+ const k = key(mnemonic, passphrase);
+ const hit = seeds.get(k);
+ if (hit) return hit;
+ const seed = mnemonicToSeedSync(mnemonic, passphrase || '');
+ keep(k, seed);
+ return seed;
+}
+
+// BIP-39 exactly: password = NFKD(phrase), salt = NFKD("mnemonic" + passphrase).
+// Anything that goes wrong leaves the cache empty; seedSync does it the slow way.
+export async function warmSeed(mnemonic, passphrase = '') {
+ if (!mnemonic) return;
+ const k = key(mnemonic, passphrase);
+ if (seeds.has(k)) return;
+ // what @scure/bip39 accepts; anything else is left for it to refuse
+ if (![12, 15, 18, 21, 24].includes(mnemonic.normalize('NFKD').split(' ').length)) return;
+ try {
+ const subtle = globalThis.crypto && globalThis.crypto.subtle;
+ if (!subtle) return;
+ const enc = new TextEncoder();
+ const pw = await subtle.importKey('raw', enc.encode(mnemonic.normalize('NFKD')), 'PBKDF2', false, ['deriveBits']);
+ const bits = await subtle.deriveBits(
+ { name: 'PBKDF2', hash: 'SHA-512', salt: enc.encode(('mnemonic' + (passphrase || '')).normalize('NFKD')), iterations: 2048 },
+ pw, 512,
+ );
+ if (!seeds.has(k)) keep(k, new Uint8Array(bits));
+ } catch {}
+}
+
+// A locked or removed wallet's seed doesn't stay behind in memory.
+export function forgetSeeds() { seeds.clear(); }