forked from octra-labs/wallet-gen
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwallet_generator.ts
More file actions
716 lines (618 loc) · 18.3 KB
/
wallet_generator.ts
File metadata and controls
716 lines (618 loc) · 18.3 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
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
import crypto from "crypto";
import fs from "fs";
import path from "path";
import { fileURLToPath } from "url";
import nacl from "tweetnacl";
import bip39 from "bip39";
import indexHtml from "./index.html" with { type: "text" };
import logoSvg from "./assets/logo.svg" with { type: "text" };
import foundersGroteskFontPath from "./assets/founders-grotesk-bold.woff2" with { type: "file" };
import nationalFontPath from "./assets/national-regular.woff2" with { type: "file" };
// ESM equivalent of __dirname
const __filename: string = fileURLToPath(import.meta.url);
const __dirname: string = path.dirname(__filename);
// Embed static assets for executable builds
let foundersGroteskFont: ArrayBuffer;
let nationalFont: ArrayBuffer;
// Load assets asynchronously
async function loadAssets() {
try {
foundersGroteskFont = await Bun.file(foundersGroteskFontPath).arrayBuffer();
nationalFont = await Bun.file(nationalFontPath).arrayBuffer();
} catch (error) {
console.warn("Could not load embedded assets:", error.message);
// Assets will be served from filesystem instead
}
}
// Type definitions
interface MasterKey {
masterPrivateKey: Buffer;
masterChainCode: Buffer;
}
interface ChildKey {
childPrivateKey: Buffer;
childChainCode: Buffer;
}
interface DerivedPath {
key: Buffer;
chain: Buffer;
}
interface NetworkDerivation {
privateKey: Buffer;
chainCode: Buffer;
publicKey: Buffer;
address: string;
path: number[];
networkTypeName: string;
network: number;
contract: number;
account: number;
index: number;
}
interface WalletData {
mnemonic: string[];
seed_hex: string;
master_chain_hex: string;
private_key_hex: string;
public_key_hex: string;
private_key_b64: string;
public_key_b64: string;
address: string;
entropy_hex: string;
test_message: string;
test_signature: string;
signature_valid: boolean;
}
interface DeriveRequest {
seed_hex: string;
network_type?: number;
index?: number;
}
const BASE58_ALPHABET: string =
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
// Helper functions
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function bufferToHex(buffer: Buffer | Uint8Array): string {
return Buffer.from(buffer).toString("hex");
}
function hexToBuffer(hex: string): Buffer {
return Buffer.from(hex, "hex");
}
function base64Encode(buffer: Buffer | Uint8Array): string {
return Buffer.from(buffer).toString("base64");
}
// Base58 encoding for Octra addresses
function base58Encode(buffer: Buffer): string {
if (buffer.length === 0) return "";
let num: bigint = BigInt("0x" + buffer.toString("hex"));
let encoded: string = "";
while (num > 0n) {
const remainder: bigint = num % 58n;
num = num / 58n;
encoded = BASE58_ALPHABET[Number(remainder)] + encoded;
}
// Handle leading zeros
for (let i = 0; i < buffer.length && buffer[i] === 0; i++) {
encoded = "1" + encoded;
}
return encoded;
}
// Generate entropy using crypto.randomBytes
function generateEntropy(strength: number = 128): Buffer {
if (![128, 160, 192, 224, 256].includes(strength)) {
throw new Error("Strength must be 128, 160, 192, 224 or 256 bits");
}
return crypto.randomBytes(strength / 8);
}
// Derive master key using HMAC-SHA512 with "Octra seed"
function deriveMasterKey(seed: Buffer): MasterKey {
const key: Buffer = Buffer.from("Octra seed", "utf8");
const mac: Buffer = crypto.createHmac("sha512", key).update(seed).digest();
const masterPrivateKey: Buffer = mac.slice(0, 32);
const masterChainCode: Buffer = mac.slice(32, 64);
return { masterPrivateKey, masterChainCode };
}
// HD key derivation for Ed25519
function deriveChildKeyEd25519(
privateKey: Buffer,
chainCode: Buffer,
index: number
): ChildKey {
let data: Buffer;
if (index >= 0x80000000) {
// Hardened derivation
data = Buffer.concat([
Buffer.from([0x00]),
privateKey,
Buffer.from([
(index >>> 24) & 0xff,
(index >>> 16) & 0xff,
(index >>> 8) & 0xff,
index & 0xff,
]),
]);
} else {
// Non-hardened derivation
const keyPair = nacl.sign.keyPair.fromSeed(privateKey);
const publicKey: Buffer = Buffer.from(keyPair.publicKey);
data = Buffer.concat([
publicKey,
Buffer.from([
(index >>> 24) & 0xff,
(index >>> 16) & 0xff,
(index >>> 8) & 0xff,
index & 0xff,
]),
]);
}
const mac: Buffer = crypto
.createHmac("sha512", chainCode)
.update(data)
.digest();
const childPrivateKey: Buffer = mac.slice(0, 32);
const childChainCode: Buffer = mac.slice(32, 64);
return { childPrivateKey, childChainCode };
}
// Derive path from seed
function derivePath(seed: Buffer, path: number[]): DerivedPath {
const { masterPrivateKey, masterChainCode }: MasterKey =
deriveMasterKey(seed);
let key: Buffer = masterPrivateKey;
let chain: Buffer = masterChainCode;
for (const index of path) {
const derived: ChildKey = deriveChildKeyEd25519(key, chain, index);
key = derived.childPrivateKey;
chain = derived.childChainCode;
}
return { key, chain };
}
// Get network type name
function getNetworkTypeName(networkType: number): string {
switch (networkType) {
case 0:
return "MainCoin";
case 1:
return `SubCoin ${networkType}`;
case 2:
return `Contract ${networkType}`;
case 3:
return `Subnet ${networkType}`;
case 4:
return `Account ${networkType}`;
default:
return `Unknown ${networkType}`;
}
}
// Derive for specific network
function deriveForNetwork(
seed: Buffer,
networkType: number = 0,
network: number = 0,
contract: number = 0,
account: number = 0,
index: number = 0,
token: number = 0,
subnet: number = 0
): NetworkDerivation {
const coinType: number = networkType === 0 ? 0 : networkType;
const basePath: number[] = [
0x80000000 + 345, // Purpose
0x80000000 + coinType, // Coin type
0x80000000 + network, // Network
];
const contractPath: number[] = [0x80000000 + contract, 0x80000000 + account];
const optionalPath: number[] = [0x80000000 + token, 0x80000000 + subnet];
const finalPath: number[] = [index];
const fullPath: number[] = [
...basePath,
...contractPath,
...optionalPath,
...finalPath,
];
const { key: derivedKey, chain: derivedChain }: DerivedPath = derivePath(
seed,
fullPath
);
const keyPair = nacl.sign.keyPair.fromSeed(derivedKey);
const derivedAddress: string = createOctraAddress(
Buffer.from(keyPair.publicKey)
);
return {
privateKey: derivedKey,
chainCode: derivedChain,
publicKey: Buffer.from(keyPair.publicKey),
address: derivedAddress,
path: fullPath,
networkTypeName: getNetworkTypeName(networkType),
network,
contract,
account,
index,
};
}
// Create Octra address
function createOctraAddress(publicKey: Buffer): string {
const hash: Buffer = crypto.createHash("sha256").update(publicKey).digest();
const base58Hash: string = base58Encode(hash);
return "oct" + base58Hash;
}
// Verify address format
function verifyAddressFormat(address: string): boolean {
if (!address.startsWith("oct")) return false;
if (address.length !== 47) return false;
const base58Part: string = address.slice(3);
for (const char of base58Part) {
if (!BASE58_ALPHABET.includes(char)) return false;
}
return true;
}
// Route handlers
async function handleGenerateWallet(): Promise<Response> {
const stream = new ReadableStream({
async start(controller) {
const encoder = new TextEncoder();
try {
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({ status: "Generating entropy..." })}\n\n`
)
);
await sleep(200);
const entropy: Buffer = generateEntropy(128);
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({ status: "Entropy generated" })}\n\n`
)
);
await sleep(200);
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({
status: "Creating mnemonic phrase...",
})}\n\n`
)
);
await sleep(200);
const mnemonic: string = bip39.entropyToMnemonic(
entropy.toString("hex")
);
const mnemonicWords: string[] = mnemonic.split(" ");
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({ status: "Mnemonic created" })}\n\n`
)
);
await sleep(200);
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({
status: "Deriving seed from mnemonic...",
})}\n\n`
)
);
await sleep(200);
const seed: Buffer = bip39.mnemonicToSeedSync(mnemonic);
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({ status: "Seed derived" })}\n\n`
)
);
await sleep(200);
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({ status: "Deriving master key..." })}\n\n`
)
);
await sleep(200);
const { masterPrivateKey, masterChainCode }: MasterKey =
deriveMasterKey(seed);
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({ status: "Master key derived" })}\n\n`
)
);
await sleep(200);
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({
status: "Creating Ed25519 keypair...",
})}\n\n`
)
);
await sleep(200);
const keyPair = nacl.sign.keyPair.fromSeed(masterPrivateKey);
const privateKeyRaw: Buffer = Buffer.from(
keyPair.secretKey.slice(0, 32)
);
const publicKeyRaw: Buffer = Buffer.from(keyPair.publicKey);
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({ status: "Keypair created" })}\n\n`
)
);
await sleep(200);
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({
status: "Generating Octra address...",
})}\n\n`
)
);
await sleep(200);
const address: string = createOctraAddress(publicKeyRaw);
if (!verifyAddressFormat(address)) {
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({
status: "ERROR: Invalid address format generated",
})}\n\n`
)
);
controller.close();
return;
}
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({
status: "Address generated and verified",
})}\n\n`
)
);
await sleep(200);
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({
status: "Testing signature functionality...",
})}\n\n`
)
);
await sleep(200);
const testMessage: string =
'{"from":"test","to":"test","amount":"1000000","nonce":1}';
const messageBytes: Buffer = Buffer.from(testMessage, "utf8");
const signature: Uint8Array = nacl.sign.detached(
messageBytes,
keyPair.secretKey
);
const signatureB64: string = base64Encode(signature);
let signatureValid: boolean = false;
try {
signatureValid = nacl.sign.detached.verify(
messageBytes,
signature,
keyPair.publicKey
);
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({ status: "Signature test passed" })}\n\n`
)
);
} catch (error: any) {
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({ status: "Signature test failed" })}\n\n`
)
);
}
await sleep(200);
const walletData: WalletData = {
mnemonic: mnemonicWords,
seed_hex: bufferToHex(seed),
master_chain_hex: bufferToHex(masterChainCode),
private_key_hex: bufferToHex(privateKeyRaw),
public_key_hex: bufferToHex(publicKeyRaw),
private_key_b64: base64Encode(privateKeyRaw),
public_key_b64: base64Encode(publicKeyRaw),
address: address,
entropy_hex: bufferToHex(entropy),
test_message: testMessage,
test_signature: signatureB64,
signature_valid: signatureValid,
};
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({
status: "Wallet generation complete!",
wallet: walletData,
})}\n\n`
)
);
controller.close();
} catch (error: any) {
controller.enqueue(
encoder.encode(
`data: ${JSON.stringify({ status: "ERROR: " + error.message })}\n\n`
)
);
controller.close();
}
},
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
},
});
}
async function handleSaveWallet(request: Request): Promise<Response> {
try {
const data: WalletData = await request.json();
const timestamp: number = Math.floor(Date.now() / 1000);
const filename: string = `octra_wallet_${data.address.slice(
-8
)}_${timestamp}.txt`;
const content: string = `OCTRA WALLET
${"=".repeat(50)}
SECURITY WARNING: KEEP THIS FILE SECURE AND NEVER SHARE YOUR PRIVATE KEY
Generated: ${new Date().toISOString().replace("T", " ").slice(0, 19)}
Address Format: oct + Base58(SHA256(pubkey))
Mnemonic: ${data.mnemonic.join(" ")}
Private Key (B64): ${data.private_key_b64}
Public Key (B64): ${data.public_key_b64}
Address: ${data.address}
Technical Details:
Entropy: ${data.entropy_hex}
Signature Algorithm: Ed25519
Derivation: BIP39-compatible (PBKDF2-HMAC-SHA512, 2048 iterations)
`;
fs.writeFileSync(filename, content);
return Response.json({
success: true,
filename: filename,
content: content,
});
} catch (error: any) {
return Response.json(
{
success: false,
error: error.message,
},
{ status: 500 }
);
}
}
async function handleDeriveWallet(request: Request): Promise<Response> {
try {
const {
seed_hex,
network_type = 0,
index = 0,
}: DeriveRequest = await request.json();
const seed: Buffer = hexToBuffer(seed_hex);
const derived: NetworkDerivation = deriveForNetwork(
seed,
network_type,
0, // network
0, // contract
0, // account
index
);
const pathString: string = derived.path
.map(
(i: number) => (i & 0x7fffffff).toString() + (i & 0x80000000 ? "'" : "")
)
.join("/");
return Response.json({
success: true,
address: derived.address,
path: pathString,
network_type_name: derived.networkTypeName,
});
} catch (error: any) {
return Response.json({
success: false,
error: error.message,
});
}
}
function getContentType(filePath: string): string {
const ext = path.extname(filePath).toLowerCase();
switch (ext) {
case '.html': return 'text/html';
case '.svg': return 'image/svg+xml';
case '.woff2': return 'font/woff2';
case '.css': return 'text/css';
case '.js': return 'application/javascript';
default: return 'application/octet-stream';
}
}
function serveEmbeddedAsset(pathname: string): Response | null {
switch (pathname) {
case '/':
case '/index.html':
if (indexHtml) {
return new Response(indexHtml, {
headers: { 'Content-Type': 'text/html' }
});
}
break;
case '/assets/logo.svg':
if (logoSvg) {
return new Response(logoSvg, {
headers: { 'Content-Type': 'image/svg+xml' }
});
}
break;
case '/assets/founders-grotesk-bold.woff2':
if (foundersGroteskFont) {
return new Response(foundersGroteskFont, {
headers: {
'Content-Type': 'font/woff2',
'Cache-Control': 'public, max-age=31536000'
}
});
}
break;
case '/assets/national-regular.woff2':
if (nationalFont) {
return new Response(nationalFont, {
headers: {
'Content-Type': 'font/woff2',
'Cache-Control': 'public, max-age=31536000'
}
});
}
break;
}
return null;
}
async function serveStaticFile(filePath: string): Promise<Response> {
try {
const file = Bun.file(filePath);
const exists = await file.exists();
if (!exists) {
return new Response("File not found", { status: 404 });
}
return new Response(file);
} catch (error) {
return new Response("Internal server error", { status: 500 });
}
}
// Load embedded assets
await loadAssets();
// Start server
const PORT: number = 8888;
const server = Bun.serve({
port: PORT,
hostname: "0.0.0.0",
async fetch(request: Request): Promise<Response> {
const url = new URL(request.url);
const { pathname, method } = {
pathname: url.pathname,
method: request.method,
};
// Handle GET requests for static assets (embedded or file system)
if (method === "GET") {
// Try to serve embedded asset first
const embeddedAsset = serveEmbeddedAsset(pathname);
if (embeddedAsset) {
return embeddedAsset;
}
// Fallback to file system for development mode
if (pathname === "/" || pathname === "/index.html") {
return serveStaticFile(path.join(__dirname, "index.html"));
}
if (pathname.startsWith("/assets/")) {
const assetPath = path.join(__dirname, pathname);
return serveStaticFile(assetPath);
}
}
// Handle API routes
if (method === "POST" && pathname === "/generate") {
return handleGenerateWallet();
}
if (method === "POST" && pathname === "/save") {
return handleSaveWallet(request);
}
if (method === "POST" && pathname === "/derive") {
return handleDeriveWallet(request);
}
// 404 for all other routes
return new Response("Not Found", { status: 404 });
},
});
console.log("OCTRA Wallet Generator Web Server");