forked from xlnfinance/xln
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbrainvault.ts
More file actions
308 lines (248 loc) · 11.2 KB
/
Copy pathbrainvault.ts
File metadata and controls
308 lines (248 loc) · 11.2 KB
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
#!/usr/bin/env bun
/**
* BrainVault CLI - Production wallet derivation
*
* Usage:
* bun brainvault.ts # Interactive
* bun brainvault.ts test secret123 100 --w=64 # Non-interactive (JSON output)
* bun brainvault.ts --test # Run deterministic tests
* bun brainvault.ts --bench # Benchmark performance
* bun brainvault.ts --lib=wasm # Force hash-wasm (slower, compat check)
* bun brainvault.ts --lib=native # Force @node-rs/argon2 (default, faster)
*/
import { stdin } from 'process';
import * as readline from 'readline/promises';
import { Worker } from 'worker_threads';
import {
getShardCount, hashName, combineShards, deriveKey, entropyToMnemonic,
deriveEthereumAddress, formatDuration, hexToBytes, bytesToHex, estimatePasswordStrength,
BRAINVAULT_V2, deriveSitePassword,
} from './runtime/brainvault.ts';
const args = process.argv.slice(2);
// ============================================================================
// CORE DERIVATION
// ============================================================================
async function derive(name: string, passphrase: string, shardInput: number, workers = 64, useWasm = false) {
const isPreset = shardInput >= 1 && shardInput <= 5;
const shardCount = isPreset ? getShardCount(shardInput) : shardInput;
const factor = isPreset ? shardInput : Math.ceil(Math.log10(shardCount)) + 1;
// Cap workers at shard count (no point having more workers than shards)
const actualWorkers = Math.min(workers, shardCount);
const nameHashHex = await hashName(name);
const shardResults: Uint8Array[] = new Array(shardCount);
const start = Date.now();
let completed = 0;
let nextShard = 0;
let failed = false;
// Choose worker based on library
const workerPath = import.meta.dir + (useWasm ? '/brainvault-worker-bun.ts' : '/brainvault-worker-native.ts');
const pool: Worker[] = [];
if (useWasm) {
console.log('Using hash-wasm (WASM) - slower but browser-compatible');
}
function safeTerminate(w: Worker) {
try {
w.terminate();
} catch (e) {
// Ignore
}
}
await new Promise<void>((resolve, reject) => {
let lastUpdate = 0;
for (let i = 0; i < actualWorkers; i++) {
const w = new Worker(workerPath);
pool.push(w);
w.on('error', (err) => {
if (failed) return;
failed = true;
console.error('\nWorker error:', err);
pool.forEach(safeTerminate);
reject(err);
});
w.on('message', ({ shardIndex, result }) => {
if (failed) return;
shardResults[shardIndex] = hexToBytes(result);
completed++;
const now = Date.now();
const elapsed = now - start;
// Live progress bar
if ((now - lastUpdate > 100) || (completed % Math.max(1, Math.ceil(shardCount / 20)) === 0) || completed === shardCount) {
lastUpdate = now;
const pct = completed / shardCount;
const filled = Math.round(pct * 40);
const bar = '█'.repeat(filled) + '░'.repeat(40 - filled);
const rate = completed / (elapsed / 1000);
const eta = (shardCount - completed) / rate * 1000;
process.stdout.write(`\r[${bar}] ${Math.round(pct * 100)}% ${completed}/${shardCount} | ${actualWorkers}w | ${formatDuration(elapsed)} | ETA: ${formatDuration(eta)} `);
}
if (completed >= shardCount) {
console.log('');
pool.forEach(safeTerminate);
resolve();
} else if (nextShard < shardCount) {
w.postMessage({ nameHashHex, passphrase, shardIndex: nextShard++, shardCount });
}
});
if (nextShard < shardCount) {
w.postMessage({ nameHashHex, passphrase, shardIndex: nextShard++, shardCount });
}
}
});
const derivationTime = Date.now() - start;
const masterKey = await combineShards(shardResults, factor);
const entropy256 = await deriveKey(masterKey, 'bip39/entropy/v2.0', 32);
const mnemonic24 = await entropyToMnemonic(entropy256);
const entropy128 = await deriveKey(masterKey, 'bip39/entropy-128/v2.0', 16);
const mnemonic12 = await entropyToMnemonic(entropy128);
const devicePass = bytesToHex(await deriveKey(masterKey, 'bip39/passphrase/v2.0', 32));
const ethAddr = await deriveEthereumAddress(mnemonic24);
return {
name, shardCount, workers, derivationTime,
mnemonic24, mnemonic12, devicePass, ethAddr,
masterKey: bytesToHex(masterKey),
};
}
// ============================================================================
// TESTS (deterministic vectors)
// ============================================================================
async function runTests() {
console.log('Running deterministic tests...\n');
const vectors = [
{
name: 'alice', pass: 'secret123456', shards: 1,
expect: {
mnemonic24: 'guilt ritual boat license winner wisdom unfair drop patient eyebrow mixed carbon move dad slogan perfect rescue luggage segment setup mirror gym gentle stick',
ethAddr: '0x1c2eAD08d0DD315aebC645339d160cbFf7736063',
}
},
{
name: 'bob', pass: 'password123', shards: 1,
expect: {
mnemonic24: 'best warm clerk scene tool cherry olive meat snack lecture target together wisdom giraffe major arrest stage claw blood ceiling prevent vapor sad verb',
ethAddr: '0x6b4060B112eC5CF7EE4E47bd4ce5C845994a7A9c',
}
},
];
for (const v of vectors) {
const result = await derive(v.name, v.pass, v.shards, 1);
const match24 = result.mnemonic24 === v.expect.mnemonic24;
const matchAddr = result.ethAddr === v.expect.ethAddr;
console.log(`Test: ${v.name}/${v.pass}/${v.shards} shards`);
console.log(` Mnemonic: ${match24 ? '✅' : '❌'}`);
console.log(` Address: ${matchAddr ? '✅' : '❌'}`);
if (!match24) console.log(` Got: ${result.mnemonic24.split(' ').slice(0, 6).join(' ')}...`);
if (!matchAddr) console.log(` Got: ${result.ethAddr}`);
console.log('');
if (!match24 || !matchAddr) process.exit(1);
}
console.log('✅ All tests passed');
}
// ============================================================================
// BENCHMARK
// ============================================================================
async function runBenchmark() {
console.log('Benchmarking argon2id performance...\n');
const configs = [
{ shards: 1, workers: 1 },
{ shards: 10, workers: 10 },
{ shards: 10, workers: 1 },
];
for (const { shards, workers } of configs) {
const result = await derive('bench', 'password', shards, workers);
const perShard = result.derivationTime / shards;
const speedup = workers > 1 ? (perShard * shards / result.derivationTime) : 1;
console.log(`${shards} shards × ${workers} workers: ${result.derivationTime}ms (${perShard.toFixed(0)}ms/shard, ${speedup.toFixed(1)}x speedup)`);
}
}
// ============================================================================
// INTERACTIVE MODE
// ============================================================================
async function interactive() {
const rl = readline.createInterface({ input: stdin, output: process.stdout, terminal: true });
console.log('BrainVault v2.1\n');
const name = (await rl.question('Name: ')).trim();
const pass = (await rl.question('Pass: ')).trim();
if (!name || !pass || pass.length < 6) {
console.log('Error: Invalid input');
rl.close();
return;
}
console.log('\nShards (quick presets or any number):');
console.log(' 1 → 1 shard (256MB) ~0.2s');
console.log(' 2 → 10 shards (2.5GB) ~0.2s');
console.log(' 3 → 100 shards (25GB) ~1s');
console.log(' 4 → 1,000 shards (256GB) ~11s');
console.log(' 5 → 10,000 shards (2.5TB) ~2min');
console.log(' 6+ → any number (e.g., 64, 256, 528)\n');
const shardInput = parseInt((await rl.question('Shards (100): ')).trim() || '100');
const shardCount = shardInput >= 1 && shardInput <= 5 ? getShardCount(shardInput) : shardInput;
// Calculate recommended workers (2/3 of RAM)
const totalGB = Math.floor((await import('os')).totalmem() / (1024**3));
const twoThirdsRAM = Math.floor((totalGB * 0.66) / 0.256);
const recommended = Math.min(twoThirdsRAM, shardCount);
console.log(`\nSystem: ${totalGB}GB RAM → recommended ${recommended} parallel workers (uses ${(recommended * 0.256).toFixed(0)}GB, 2/3 of RAM)\n`);
const workersInput = parseInt((await rl.question(`Number of parallel workers (${recommended}): `)).trim() || `${recommended}`);
rl.close();
console.log(`\n${shardCount} shards × ${workersInput} workers\n`);
try {
const result = await derive(name, pass, shardInput, workersInput);
console.log(`\n✅ ${formatDuration(result.derivationTime)}\n`);
console.log('24w:', result.mnemonic24.split(' ').slice(0, 12).join(' '));
console.log(' ', result.mnemonic24.split(' ').slice(12).join(' '));
console.log('12w:', result.mnemonic12);
console.log('ETH:', result.ethAddr);
console.log('Dev:', result.devicePass);
console.log('Key:', result.masterKey);
} catch (err) {
console.error('Derivation failed:', err);
process.exit(1);
}
}
// ============================================================================
// PASSWORD MANAGER
// ============================================================================
async function derivePassword() {
const rl = readline.createInterface({ input: stdin, output: process.stdout });
console.log('BrainVault Password Manager\n');
const name = await rl.question('Name: ');
const pass = await rl.question('Pass: ');
const shardInput = parseInt((await rl.question('Shards (3): ')).trim() || '3');
rl.close();
console.log('\nDeriving master key...');
const result = await derive(name, pass, shardInput, 1);
console.log('\n✅ Master key ready\n');
const rlPassword = readline.createInterface({ input: stdin, output: process.stdout });
while (true) {
const domain = await rlPassword.question('Domain (or Enter to exit): ');
if (!domain) break;
const sitePass = await deriveSitePassword(result.masterKey, domain);
console.log(` ${domain}: ${sitePass}\n`);
}
rlPassword.close();
}
// ============================================================================
// MAIN
// ============================================================================
const useWasm = args.includes('--lib=wasm');
const useNative = args.includes('--lib=native');
if (useWasm && useNative) {
console.error('Error: Cannot use both --lib=wasm and --lib=native');
process.exit(1);
}
if (args.includes('--test')) {
await runTests();
} else if (args.includes('--bench')) {
await runBenchmark();
} else if (args.includes('--password')) {
await derivePassword();
} else if (args.length >= 3 && !args[0]?.startsWith('--')) {
// Non-interactive: name pass shards [--w=N] [--lib=wasm|native]
const [name, pass, shardStr] = args;
const shards = parseInt(shardStr!);
const wFlag = args.find(a => a.startsWith('--w='));
const workers = wFlag ? parseInt(wFlag.split('=')[1]!) : 64;
const result = await derive(name!, pass!, shards, workers, useWasm);
console.log(JSON.stringify(result, null, 2));
} else {
await interactive();
}