aboutsummaryrefslogtreecommitdiffstats
path: root/src/seed.js
blob: 05920358b858c8d2fcb13f6e156240a9e04723f1 (plain) (blame)
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
// 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(); }