@neuraiproject/neurai-sign-esp32 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs ADDED
@@ -0,0 +1,576 @@
1
+ var $8zHUo$bitcoinjslib = require("bitcoinjs-lib");
2
+ var $8zHUo$ecpair = require("ecpair");
3
+ var $8zHUo$bitcoinerlabsecp256k1 = require("@bitcoinerlab/secp256k1");
4
+
5
+
6
+ function $parcel$export(e, n, v, s) {
7
+ Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
8
+ }
9
+
10
+ function $parcel$interopDefault(a) {
11
+ return a && a.__esModule ? a.default : a;
12
+ }
13
+
14
+ $parcel$export(module.exports, "NeuraiESP32", () => $4f193116bbff8497$export$fa10ee8b91a777b7);
15
+ $parcel$export(module.exports, "buildPSBT", () => $5da7d5b3a851268c$export$236ea1e009011592);
16
+ $parcel$export(module.exports, "finalizePSBT", () => $5da7d5b3a851268c$export$ce839c4c9bcf7b77);
17
+ $parcel$export(module.exports, "validatePSBT", () => $5da7d5b3a851268c$export$78a5723c75e7be9);
18
+ $parcel$export(module.exports, "SerialConnection", () => $a48f33fba55d0d0b$export$f93edba7156cc57b);
19
+ $parcel$export(module.exports, "getNetwork", () => $8eddb774c9d38ccb$export$7de4970ebfd8206d);
20
+ $parcel$export(module.exports, "neuraiMainnet", () => $8eddb774c9d38ccb$export$6b5a4442fe3d94ae);
21
+ $parcel$export(module.exports, "neuraiTestnet", () => $8eddb774c9d38ccb$export$7eb3dea33add35cf);
22
+ $parcel$export(module.exports, "neuraiLegacyMainnet", () => $8eddb774c9d38ccb$export$688657d38fcd7269);
23
+ $parcel$export(module.exports, "neuraiLegacyTestnet", () => $8eddb774c9d38ccb$export$68e8f8241c8185fe);
24
+ /**
25
+ * @neuraiproject/neurai-sign-esp32
26
+ *
27
+ * Library for creating and signing Neurai (XNA) PSBTs
28
+ * via ESP32 hardware wallet (NeuraiHW).
29
+ */ // Main class
30
+ /**
31
+ * NeuraiESP32 — Main class for interacting with a NeuraiHW hardware wallet.
32
+ *
33
+ * Orchestrates:
34
+ * - USB Serial connection via Web Serial API
35
+ * - Device info, address, and BIP32 pubkey retrieval
36
+ * - PSBT creation, signing, and finalization
37
+ *
38
+ * Usage:
39
+ * ```ts
40
+ * const device = new NeuraiESP32();
41
+ * await device.connect();
42
+ * const info = await device.getInfo();
43
+ * const { address, pubkey } = await device.getAddress();
44
+ * const result = await device.signTransaction({ utxos, outputs, changeAddress: address });
45
+ * console.log(result.txHex); // ready to broadcast
46
+ * await device.disconnect();
47
+ * ```
48
+ */ /**
49
+ * Web Serial API communication layer for ESP32 hardware wallet.
50
+ *
51
+ * Handles USB Serial connection, JSON command/response protocol,
52
+ * and line-based buffering matching the NeuraiHW firmware protocol.
53
+ */ // Default USB filters for ESP32 devices
54
+ const $a48f33fba55d0d0b$var$DEFAULT_FILTERS = [
55
+ {
56
+ usbVendorId: 0x303a,
57
+ usbProductId: 0x1001
58
+ },
59
+ {
60
+ usbVendorId: 0x303a
61
+ },
62
+ {
63
+ usbVendorId: 0x10c4,
64
+ usbProductId: 0xea60
65
+ },
66
+ {
67
+ usbVendorId: 0x1a86,
68
+ usbProductId: 0x7523
69
+ },
70
+ {
71
+ usbVendorId: 0x0403,
72
+ usbProductId: 0x6001
73
+ },
74
+ {
75
+ usbVendorId: 0x067b,
76
+ usbProductId: 0x2303
77
+ },
78
+ {
79
+ usbVendorId: 0x2886
80
+ }
81
+ ];
82
+ const $a48f33fba55d0d0b$var$DEFAULT_BAUD_RATE = 115200;
83
+ class $a48f33fba55d0d0b$export$f93edba7156cc57b {
84
+ constructor(options){
85
+ this.port = null;
86
+ this.reader = null;
87
+ this.writer = null;
88
+ this.readableStreamClosed = null;
89
+ this.writableStreamClosed = null;
90
+ this.isReading = false;
91
+ this.responseQueue = [];
92
+ this.baudRate = options?.baudRate ?? $a48f33fba55d0d0b$var$DEFAULT_BAUD_RATE;
93
+ this.filters = options?.filters ?? $a48f33fba55d0d0b$var$DEFAULT_FILTERS;
94
+ }
95
+ /**
96
+ * Check if Web Serial API is available.
97
+ */ static isSupported() {
98
+ return typeof navigator !== "undefined" && "serial" in navigator;
99
+ }
100
+ /**
101
+ * Open a serial connection to the ESP32.
102
+ * Triggers browser port selection dialog.
103
+ */ async open() {
104
+ if (!$a48f33fba55d0d0b$export$f93edba7156cc57b.isSupported()) throw new Error("Web Serial API not supported. Use Chrome, Edge, or Opera.");
105
+ this.port = await navigator.serial.requestPort({
106
+ filters: this.filters
107
+ });
108
+ await this.port.open({
109
+ baudRate: this.baudRate
110
+ });
111
+ // Set up readable stream (text decoding)
112
+ const decoder = new TextDecoderStream();
113
+ this.readableStreamClosed = this.port.readable.pipeTo(decoder.writable);
114
+ this.reader = decoder.readable.getReader();
115
+ // Set up writable stream (text encoding)
116
+ const encoder = new TextEncoderStream();
117
+ this.writableStreamClosed = encoder.readable.pipeTo(this.port.writable);
118
+ this.writer = encoder.writable.getWriter();
119
+ // Start background read loop
120
+ this.isReading = true;
121
+ this.readLoop();
122
+ }
123
+ /**
124
+ * Close the serial connection.
125
+ */ async close() {
126
+ this.isReading = false;
127
+ if (this.reader) {
128
+ await this.reader.cancel();
129
+ await this.readableStreamClosed?.catch(()=>{});
130
+ this.reader = null;
131
+ }
132
+ if (this.writer) {
133
+ await this.writer.close();
134
+ await this.writableStreamClosed;
135
+ this.writer = null;
136
+ }
137
+ if (this.port) {
138
+ await this.port.close();
139
+ this.port = null;
140
+ }
141
+ this.responseQueue = [];
142
+ }
143
+ /**
144
+ * Whether the serial port is currently connected.
145
+ */ get connected() {
146
+ return this.port !== null && this.writer !== null;
147
+ }
148
+ /**
149
+ * Send a JSON command to the device and wait for a JSON response.
150
+ *
151
+ * @param command - The command object (e.g. { action: "info" })
152
+ * @param timeoutMs - Response timeout in milliseconds (default: 65000 for sign operations)
153
+ * @returns The parsed device response
154
+ */ async sendCommand(command, timeoutMs = 65000) {
155
+ if (!this.writer) throw new Error("Serial port not connected");
156
+ // Clear stale responses
157
+ this.responseQueue = [];
158
+ // Send JSON in small chunks, then newline to trigger processing.
159
+ // The ESP32 CDC serial buffer can lose data if sent too fast in one write.
160
+ const json = JSON.stringify(command);
161
+ await this.writeChunked(json);
162
+ await this.writer.write("\n");
163
+ // Wait for response
164
+ const response = await this.waitForResponse(timeoutMs);
165
+ if (!response) throw new Error("Device response timeout");
166
+ return response;
167
+ }
168
+ /**
169
+ * Send a command and wait, skipping intermediate "processing" status messages.
170
+ * Useful for sign_psbt which sends a processing ACK before the actual response.
171
+ */ async sendCommandFinal(command, timeoutMs = 65000) {
172
+ if (!this.writer) throw new Error("Serial port not connected");
173
+ this.responseQueue = [];
174
+ const json = JSON.stringify(command);
175
+ await this.writeChunked(json);
176
+ await this.writer.write("\n");
177
+ // Wait for a non-processing response
178
+ const startTime = Date.now();
179
+ while(Date.now() - startTime < timeoutMs){
180
+ const response = await this.waitForResponse(timeoutMs - (Date.now() - startTime));
181
+ if (!response) throw new Error("Device response timeout");
182
+ // Skip intermediate "processing" status
183
+ if (response.status === "processing") continue;
184
+ return response;
185
+ }
186
+ throw new Error("Device response timeout");
187
+ }
188
+ // ─── Private ──────────────────────────────────────────────────────────────
189
+ async readLoop() {
190
+ let buffer = "";
191
+ while(this.isReading && this.reader)try {
192
+ const { value: value, done: done } = await this.reader.read();
193
+ if (done) break;
194
+ buffer += value;
195
+ // Process complete lines
196
+ const lines = buffer.split("\n");
197
+ buffer = lines.pop() ?? ""; // Keep incomplete line in buffer
198
+ for (const rawLine of lines){
199
+ const line = rawLine.trim().replace(/\r/g, "");
200
+ if (line.length === 0) continue;
201
+ // Try to parse as JSON response
202
+ if (line.startsWith("{")) try {
203
+ const data = JSON.parse(line);
204
+ this.responseQueue.push(data);
205
+ } catch {
206
+ // Not valid JSON — debug output from firmware, ignore
207
+ }
208
+ // Non-JSON lines are firmware debug output, ignored
209
+ }
210
+ } catch {
211
+ break;
212
+ }
213
+ }
214
+ waitForResponse(timeoutMs) {
215
+ return new Promise((resolve)=>{
216
+ const startTime = Date.now();
217
+ const check = ()=>{
218
+ if (this.responseQueue.length > 0) resolve(this.responseQueue.shift());
219
+ else if (Date.now() - startTime > timeoutMs) resolve(null);
220
+ else setTimeout(check, 50);
221
+ };
222
+ check();
223
+ });
224
+ }
225
+ /**
226
+ * Write data in small chunks with pauses between them.
227
+ *
228
+ * The ESP32 CDC serial buffer can lose data when the host sends a large
229
+ * payload in a single write. Splitting into 32-byte chunks with a 4 ms
230
+ * pause gives the firmware time to drain its receive buffer.
231
+ */ async writeChunked(data, chunkSize = 32, pauseMs = 4) {
232
+ if (!this.writer) throw new Error("Serial port not connected");
233
+ for(let offset = 0; offset < data.length; offset += chunkSize){
234
+ const chunk = data.slice(offset, offset + chunkSize);
235
+ await this.writer.write(chunk);
236
+ if (offset + chunkSize < data.length) await this.delay(pauseMs);
237
+ }
238
+ }
239
+ delay(ms) {
240
+ return new Promise((resolve)=>setTimeout(resolve, ms));
241
+ }
242
+ }
243
+
244
+
245
+ /**
246
+ * PSBT builder for Neurai P2PKH transactions.
247
+ *
248
+ * Creates unsigned PSBTs compatible with the NeuraiHW ESP32 firmware.
249
+ * The ESP32 signs inputs that match its BIP32 derivation path and
250
+ * master fingerprint.
251
+ *
252
+ * Requirements for each UTXO:
253
+ * - rawTxHex: Full raw transaction hex (P2PKH needs nonWitnessUtxo)
254
+ * - scriptPubKey: The output script being spent
255
+ *
256
+ * The PSBT includes BIP32 derivation metadata so the ESP32 can
257
+ * verify and locate the correct signing key.
258
+ */
259
+
260
+
261
+ /**
262
+ * Neurai network configurations for bitcoinjs-lib
263
+ *
264
+ * Defines all Neurai networks (mainnet, testnet, legacy variants)
265
+ * in the format required by bitcoinjs-lib v7.
266
+ */ const $8eddb774c9d38ccb$export$6b5a4442fe3d94ae = {
267
+ messagePrefix: "Neurai Signed Message:\n",
268
+ bech32: "",
269
+ bip32: {
270
+ public: 76067358,
271
+ private: 76066276
272
+ },
273
+ pubKeyHash: 53,
274
+ scriptHash: 117,
275
+ wif: 128
276
+ };
277
+ const $8eddb774c9d38ccb$export$7eb3dea33add35cf = {
278
+ messagePrefix: "Neurai Signed Message:\n",
279
+ bech32: "",
280
+ bip32: {
281
+ public: 70617039,
282
+ private: 70615956
283
+ },
284
+ pubKeyHash: 127,
285
+ scriptHash: 196,
286
+ wif: 239
287
+ };
288
+ const $8eddb774c9d38ccb$export$688657d38fcd7269 = {
289
+ messagePrefix: "Neurai Signed Message:\n",
290
+ bech32: "",
291
+ bip32: {
292
+ public: 76067358,
293
+ private: 76066276
294
+ },
295
+ pubKeyHash: 53,
296
+ scriptHash: 117,
297
+ wif: 128
298
+ };
299
+ const $8eddb774c9d38ccb$export$68e8f8241c8185fe = {
300
+ messagePrefix: "Neurai Signed Message:\n",
301
+ bech32: "",
302
+ bip32: {
303
+ public: 70617039,
304
+ private: 70615956
305
+ },
306
+ pubKeyHash: 127,
307
+ scriptHash: 196,
308
+ wif: 239
309
+ };
310
+ // ─── Network map ─────────────────────────────────────────────────────────────
311
+ const $8eddb774c9d38ccb$var$networkMap = {
312
+ xna: $8eddb774c9d38ccb$export$6b5a4442fe3d94ae,
313
+ "xna-test": $8eddb774c9d38ccb$export$7eb3dea33add35cf,
314
+ "xna-legacy": $8eddb774c9d38ccb$export$688657d38fcd7269,
315
+ "xna-legacy-test": $8eddb774c9d38ccb$export$68e8f8241c8185fe
316
+ };
317
+ function $8eddb774c9d38ccb$export$7de4970ebfd8206d(network) {
318
+ const net = $8eddb774c9d38ccb$var$networkMap[network];
319
+ if (!net) throw new Error(`Unknown network: ${network}`);
320
+ return net;
321
+ }
322
+
323
+
324
+ const $5da7d5b3a851268c$var$ECPair = (0, $8zHUo$ecpair.ECPairFactory)((0, ($parcel$interopDefault($8zHUo$bitcoinerlabsecp256k1))));
325
+ const $5da7d5b3a851268c$var$DEFAULT_FEE_RATE = 1024; // sat/byte
326
+ // Estimated P2PKH tx sizes for fee calculation
327
+ const $5da7d5b3a851268c$var$TX_OVERHEAD = 10; // version(4) + locktime(4) + varint(2)
328
+ const $5da7d5b3a851268c$var$INPUT_SIZE = 148; // P2PKH input with signature
329
+ const $5da7d5b3a851268c$var$OUTPUT_SIZE = 34; // P2PKH output
330
+ /**
331
+ * Estimate transaction size in bytes for P2PKH.
332
+ */ function $5da7d5b3a851268c$var$estimateTxSize(inputCount, outputCount) {
333
+ return $5da7d5b3a851268c$var$TX_OVERHEAD + inputCount * $5da7d5b3a851268c$var$INPUT_SIZE + outputCount * $5da7d5b3a851268c$var$OUTPUT_SIZE;
334
+ }
335
+ /**
336
+ * Parse a master fingerprint hex string (8 chars) into a 4-byte Buffer.
337
+ */ function $5da7d5b3a851268c$var$parseMasterFingerprint(hex) {
338
+ if (hex.length !== 8) throw new Error(`Invalid master fingerprint: expected 8 hex chars, got ${hex.length}`);
339
+ return Buffer.from(hex, "hex");
340
+ }
341
+ /**
342
+ * Parse a BIP44 derivation path string into an array of uint32 indices.
343
+ * e.g. "m/44'/1900'/0'/0/0" → [0x8000002C, 0x8000076C, 0x80000000, 0, 0]
344
+ */ function $5da7d5b3a851268c$var$parseDerivationPath(path) {
345
+ return path.replace(/^m\//, "").split("/").map((part)=>{
346
+ const hardened = part.endsWith("'");
347
+ const index = parseInt(hardened ? part.slice(0, -1) : part, 10);
348
+ return hardened ? index + 0x80000000 : index;
349
+ });
350
+ }
351
+ function $5da7d5b3a851268c$export$236ea1e009011592(options) {
352
+ const { network: networkType, utxos: utxos, outputs: outputs, changeAddress: changeAddress, pubkey: pubkey, masterFingerprint: masterFingerprint, derivationPath: derivationPath, feeRate: feeRate = $5da7d5b3a851268c$var$DEFAULT_FEE_RATE } = options;
353
+ if (utxos.length === 0) throw new Error("No UTXOs provided");
354
+ if (outputs.length === 0) throw new Error("No outputs provided");
355
+ const network = (0, $8eddb774c9d38ccb$export$7de4970ebfd8206d)(networkType);
356
+ const pubkeyBuffer = Buffer.from(pubkey, "hex");
357
+ const fingerprintBuffer = $5da7d5b3a851268c$var$parseMasterFingerprint(masterFingerprint);
358
+ const bip32Path = $5da7d5b3a851268c$var$parseDerivationPath(derivationPath);
359
+ // Calculate total output amount
360
+ const totalOutputValue = outputs.reduce((sum, o)=>sum + o.value, 0);
361
+ // Select UTXOs (use all provided — caller is responsible for UTXO selection)
362
+ const totalInputValue = utxos.reduce((sum, u)=>sum + u.satoshis, 0);
363
+ // Estimate fee: outputs + possible change output
364
+ const estimatedSize = $5da7d5b3a851268c$var$estimateTxSize(utxos.length, outputs.length + 1);
365
+ const fee = estimatedSize * feeRate;
366
+ const change = totalInputValue - totalOutputValue - fee;
367
+ if (change < 0) throw new Error(`Insufficient funds: inputs=${totalInputValue}, outputs=${totalOutputValue}, fee=${fee}`);
368
+ // Build PSBT
369
+ const psbt = new $8zHUo$bitcoinjslib.Psbt({
370
+ network: network
371
+ });
372
+ // BIP32 derivation metadata (same for all inputs from this device)
373
+ const bip32Derivation = [
374
+ {
375
+ masterFingerprint: fingerprintBuffer,
376
+ path: derivationPath,
377
+ pubkey: pubkeyBuffer
378
+ }
379
+ ];
380
+ // Add inputs
381
+ for (const utxo of utxos)psbt.addInput({
382
+ hash: utxo.txid,
383
+ index: utxo.vout,
384
+ nonWitnessUtxo: Buffer.from(utxo.rawTxHex, "hex"),
385
+ bip32Derivation: bip32Derivation
386
+ });
387
+ // Add destination outputs
388
+ for (const output of outputs)psbt.addOutput({
389
+ address: output.address,
390
+ value: BigInt(output.value)
391
+ });
392
+ // Add change output (if change > dust threshold)
393
+ const DUST_THRESHOLD = 546; // standard dust for P2PKH
394
+ if (change >= DUST_THRESHOLD) psbt.addOutput({
395
+ address: changeAddress,
396
+ value: BigInt(change),
397
+ bip32Derivation: bip32Derivation
398
+ });
399
+ return psbt.toBase64();
400
+ }
401
+ function $5da7d5b3a851268c$export$ce839c4c9bcf7b77(signedPsbtBase64, network) {
402
+ const net = (0, $8eddb774c9d38ccb$export$7de4970ebfd8206d)(network);
403
+ const psbt = $8zHUo$bitcoinjslib.Psbt.fromBase64(signedPsbtBase64, {
404
+ network: net
405
+ });
406
+ psbt.finalizeAllInputs();
407
+ const tx = psbt.extractTransaction();
408
+ return {
409
+ txHex: tx.toHex(),
410
+ txId: tx.getId()
411
+ };
412
+ }
413
+ function $5da7d5b3a851268c$export$78a5723c75e7be9(psbtBase64, network) {
414
+ try {
415
+ const net = (0, $8eddb774c9d38ccb$export$7de4970ebfd8206d)(network);
416
+ $8zHUo$bitcoinjslib.Psbt.fromBase64(psbtBase64, {
417
+ network: net
418
+ });
419
+ return true;
420
+ } catch {
421
+ return false;
422
+ }
423
+ }
424
+
425
+
426
+ class $4f193116bbff8497$export$fa10ee8b91a777b7 {
427
+ constructor(options){
428
+ this.deviceInfo = null;
429
+ this.serial = new (0, $a48f33fba55d0d0b$export$f93edba7156cc57b)(options);
430
+ }
431
+ /**
432
+ * Check if Web Serial API is supported in this browser.
433
+ */ static isSupported() {
434
+ return (0, $a48f33fba55d0d0b$export$f93edba7156cc57b).isSupported();
435
+ }
436
+ /**
437
+ * Whether the device is currently connected.
438
+ */ get connected() {
439
+ return this.serial.connected;
440
+ }
441
+ /**
442
+ * Cached device info from the last getInfo() call.
443
+ */ get info() {
444
+ return this.deviceInfo;
445
+ }
446
+ // ─── Connection ─────────────────────────────────────────────────────────
447
+ /**
448
+ * Connect to the ESP32 hardware wallet.
449
+ * Opens the browser port selection dialog.
450
+ */ async connect() {
451
+ await this.serial.open();
452
+ }
453
+ /**
454
+ * Disconnect from the device.
455
+ */ async disconnect() {
456
+ this.deviceInfo = null;
457
+ await this.serial.close();
458
+ }
459
+ // ─── Device commands ────────────────────────────────────────────────────
460
+ /**
461
+ * Get device information (no user confirmation needed).
462
+ * Returns device name, version, network, address, pubkey, etc.
463
+ */ async getInfo() {
464
+ const response = await this.serial.sendCommand({
465
+ action: "info"
466
+ }, 5000);
467
+ this.assertSuccess(response);
468
+ this.deviceInfo = response;
469
+ return this.deviceInfo;
470
+ }
471
+ /**
472
+ * Request the device address and public key.
473
+ * Requires user physical confirmation on the device (30s timeout).
474
+ */ async getAddress() {
475
+ const response = await this.serial.sendCommand({
476
+ action: "get_address"
477
+ }, 35000);
478
+ this.assertSuccess(response);
479
+ return response;
480
+ }
481
+ /**
482
+ * Request the BIP32 account extended public key (xpub).
483
+ * Requires user physical confirmation on the device (30s timeout).
484
+ */ async getBip32Pubkey() {
485
+ const response = await this.serial.sendCommand({
486
+ action: "get_bip32_pubkey"
487
+ }, 35000);
488
+ this.assertSuccess(response);
489
+ return response;
490
+ }
491
+ /**
492
+ * Send a raw PSBT (base64) to the device for signing.
493
+ * Requires user physical confirmation on the device (60s timeout).
494
+ *
495
+ * Use this if you build the PSBT yourself.
496
+ */ async signPsbt(psbtBase64) {
497
+ const response = await this.serial.sendCommandFinal({
498
+ action: "sign_psbt",
499
+ psbt: psbtBase64
500
+ }, 65000);
501
+ this.assertSuccess(response);
502
+ return response;
503
+ }
504
+ // ─── High-level transaction flow ────────────────────────────────────────
505
+ /**
506
+ * Build, sign, and finalize a transaction in one call.
507
+ *
508
+ * This is the main method for sending XNA. It:
509
+ * 1. Builds an unsigned PSBT from the provided UTXOs and outputs
510
+ * 2. Sends it to the ESP32 for signing (user confirms on device)
511
+ * 3. Finalizes the signed PSBT and extracts the raw transaction
512
+ *
513
+ * @param options.network - Network type (default: uses device info)
514
+ * @param options.utxos - UTXOs to spend (must include rawTxHex)
515
+ * @param options.outputs - Destination outputs [{address, value}]
516
+ * @param options.changeAddress - Address for change (typically device address)
517
+ * @param options.pubkey - Compressed public key hex (from getAddress)
518
+ * @param options.masterFingerprint - From getInfo().master_fingerprint
519
+ * @param options.derivationPath - From getAddress().path
520
+ * @param options.feeRate - Fee rate in sat/byte (default: 1024)
521
+ * @returns ISignResult with txHex ready to broadcast
522
+ */ async signTransaction(options) {
523
+ // Use cached device info if available for defaults
524
+ const info = this.deviceInfo;
525
+ const network = options.network ?? this.inferNetworkType(info);
526
+ const pubkey = options.pubkey ?? info?.pubkey;
527
+ const masterFingerprint = options.masterFingerprint ?? info?.master_fingerprint;
528
+ const derivationPath = options.derivationPath ?? info?.path;
529
+ if (!pubkey) throw new Error("pubkey required. Call getInfo() first or provide it explicitly.");
530
+ if (!masterFingerprint) throw new Error("masterFingerprint required. Call getInfo() first or provide it explicitly.");
531
+ if (!derivationPath) throw new Error("derivationPath required. Call getInfo() first or provide it explicitly.");
532
+ // 1. Build unsigned PSBT
533
+ const psbtBase64 = (0, $5da7d5b3a851268c$export$236ea1e009011592)({
534
+ network: network,
535
+ utxos: options.utxos,
536
+ outputs: options.outputs,
537
+ changeAddress: options.changeAddress,
538
+ pubkey: pubkey,
539
+ masterFingerprint: masterFingerprint,
540
+ derivationPath: derivationPath,
541
+ feeRate: options.feeRate
542
+ });
543
+ // 2. Send to ESP32 for signing
544
+ const signResponse = await this.signPsbt(psbtBase64);
545
+ // 3. Finalize and extract raw transaction
546
+ const { txHex: txHex, txId: txId } = (0, $5da7d5b3a851268c$export$ce839c4c9bcf7b77)(signResponse.psbt, network);
547
+ return {
548
+ signedPsbtBase64: signResponse.psbt,
549
+ txHex: txHex,
550
+ txId: txId,
551
+ signedInputs: signResponse.signed_inputs
552
+ };
553
+ }
554
+ // ─── Private helpers ────────────────────────────────────────────────────
555
+ assertSuccess(response) {
556
+ if (response.status === "error") throw new Error(`Device error: ${response.message}`);
557
+ }
558
+ /**
559
+ * Infer the NetworkType from cached device info.
560
+ */ inferNetworkType(info) {
561
+ if (!info) return "xna"; // default
562
+ const networkName = info.network?.toLowerCase() ?? "";
563
+ const coinType = info.coin_type;
564
+ if (networkName.includes("test")) return coinType === 1900 ? "xna-test" : "xna-legacy-test";
565
+ if (networkName.includes("legacy") || coinType === 0) return "xna-legacy";
566
+ return "xna";
567
+ }
568
+ }
569
+
570
+
571
+
572
+
573
+
574
+
575
+
576
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;CAKC,GAED,aAAa;ACPb;;;;;;;;;;;;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ACA,OAAO,QAAQ,KAAK;YACpB,SAAS,QAAQ,OAAO;YACxB,eAAe,QAAQ,aAAa;oBACpC;+BACA;4BACA;YACA,SAAS,QAAQ,OAAO;QAC1B;QAEA,+BAA+B;QAC/B,MAAM,eAAe,MAAM,IAAI,CAAC,QAAQ,CAAC;QAEzC,0CAA0C;QAC1C,MAAM,SAAE,KAAK,QAAE,IAAI,EAAE,GAAG,CAAA,GAAA,yCAAW,EAAE,aAAa,IAAI,EAAE;QAExD,OAAO;YACL,kBAAkB,aAAa,IAAI;mBACnC;kBACA;YACA,cAAc,aAAa,aAAa;QAC1C;IACF;IAEA,2EAA2E;IAEnE,cAAc,QAAwB,EAAQ;QACpD,IAAI,SAAS,MAAM,KAAK,SACtB,MAAM,IAAI,MACR,CAAC,cAAc,EAAE,AAAC,SAA4B,OAAO,EAAE;IAG7D;IAEA;;GAEC,GACD,AAAQ,iBAAiB,IAAwB,EAAe;QAC9D,IAAI,CAAC,MACH,OAAO,OAAO,UAAU;QAG1B,MAAM,cAAc,KAAK,OAAO,EAAE,iBAAiB;QACnD,MAAM,WAAW,KAAK,SAAS;QAE/B,IAAI,YAAY,QAAQ,CAAC,SACvB,OAAO,aAAa,OAAO,aAAa;QAE1C,IAAI,YAAY,QAAQ,CAAC,aAAa,aAAa,GACjD,OAAO;QAET,OAAO;IACT;AACF;","sources":["src/index.ts","src/NeuraiESP32.ts","src/serial.ts","src/psbt.ts","src/networks.ts"],"sourcesContent":["/**\n * @neuraiproject/neurai-sign-esp32\n *\n * Library for creating and signing Neurai (XNA) PSBTs\n * via ESP32 hardware wallet (NeuraiHW).\n */\n\n// Main class\nexport { NeuraiESP32 } from \"./NeuraiESP32.js\";\n\n// PSBT utilities\nexport { buildPSBT, finalizePSBT, validatePSBT } from \"./psbt.js\";\n\n// Serial connection (for advanced use)\nexport { SerialConnection } from \"./serial.js\";\n\n// Network configs\nexport {\n getNetwork,\n neuraiMainnet,\n neuraiTestnet,\n neuraiLegacyMainnet,\n neuraiLegacyTestnet,\n} from \"./networks.js\";\n\n// Types\nexport type {\n IUTXO,\n ITxOutput,\n IBuildPSBTOptions,\n IDeviceInfo,\n IAddressResponse,\n IBip32PubkeyResponse,\n ISignPsbtResponse,\n IErrorResponse,\n ISerialOptions,\n ISignResult,\n NetworkType,\n} from \"./types.js\";\n","/**\n * NeuraiESP32 — Main class for interacting with a NeuraiHW hardware wallet.\n *\n * Orchestrates:\n * - USB Serial connection via Web Serial API\n * - Device info, address, and BIP32 pubkey retrieval\n * - PSBT creation, signing, and finalization\n *\n * Usage:\n * ```ts\n * const device = new NeuraiESP32();\n * await device.connect();\n * const info = await device.getInfo();\n * const { address, pubkey } = await device.getAddress();\n * const result = await device.signTransaction({ utxos, outputs, changeAddress: address });\n * console.log(result.txHex); // ready to broadcast\n * await device.disconnect();\n * ```\n */\n\nimport { SerialConnection } from \"./serial.js\";\nimport { buildPSBT, finalizePSBT } from \"./psbt.js\";\nimport type {\n DeviceResponse,\n IAddressResponse,\n IBip32PubkeyResponse,\n IDeviceInfo,\n IErrorResponse,\n ISerialOptions,\n ISignPsbtResponse,\n ISignResult,\n IUTXO,\n ITxOutput,\n NetworkType,\n} from \"./types.js\";\n\nexport class NeuraiESP32 {\n private serial: SerialConnection;\n private deviceInfo: IDeviceInfo | null = null;\n\n constructor(options?: ISerialOptions) {\n this.serial = new SerialConnection(options);\n }\n\n /**\n * Check if Web Serial API is supported in this browser.\n */\n static isSupported(): boolean {\n return SerialConnection.isSupported();\n }\n\n /**\n * Whether the device is currently connected.\n */\n get connected(): boolean {\n return this.serial.connected;\n }\n\n /**\n * Cached device info from the last getInfo() call.\n */\n get info(): IDeviceInfo | null {\n return this.deviceInfo;\n }\n\n // ─── Connection ─────────────────────────────────────────────────────────\n\n /**\n * Connect to the ESP32 hardware wallet.\n * Opens the browser port selection dialog.\n */\n async connect(): Promise<void> {\n await this.serial.open();\n }\n\n /**\n * Disconnect from the device.\n */\n async disconnect(): Promise<void> {\n this.deviceInfo = null;\n await this.serial.close();\n }\n\n // ─── Device commands ────────────────────────────────────────────────────\n\n /**\n * Get device information (no user confirmation needed).\n * Returns device name, version, network, address, pubkey, etc.\n */\n async getInfo(): Promise<IDeviceInfo> {\n const response = await this.serial.sendCommand(\n { action: \"info\" },\n 5000\n );\n\n this.assertSuccess(response);\n this.deviceInfo = response as IDeviceInfo;\n return this.deviceInfo;\n }\n\n /**\n * Request the device address and public key.\n * Requires user physical confirmation on the device (30s timeout).\n */\n async getAddress(): Promise<IAddressResponse> {\n const response = await this.serial.sendCommand(\n { action: \"get_address\" },\n 35000\n );\n\n this.assertSuccess(response);\n return response as IAddressResponse;\n }\n\n /**\n * Request the BIP32 account extended public key (xpub).\n * Requires user physical confirmation on the device (30s timeout).\n */\n async getBip32Pubkey(): Promise<IBip32PubkeyResponse> {\n const response = await this.serial.sendCommand(\n { action: \"get_bip32_pubkey\" },\n 35000\n );\n\n this.assertSuccess(response);\n return response as IBip32PubkeyResponse;\n }\n\n /**\n * Send a raw PSBT (base64) to the device for signing.\n * Requires user physical confirmation on the device (60s timeout).\n *\n * Use this if you build the PSBT yourself.\n */\n async signPsbt(psbtBase64: string): Promise<ISignPsbtResponse> {\n const response = await this.serial.sendCommandFinal(\n { action: \"sign_psbt\", psbt: psbtBase64 },\n 65000\n );\n\n this.assertSuccess(response);\n return response as ISignPsbtResponse;\n }\n\n // ─── High-level transaction flow ────────────────────────────────────────\n\n /**\n * Build, sign, and finalize a transaction in one call.\n *\n * This is the main method for sending XNA. It:\n * 1. Builds an unsigned PSBT from the provided UTXOs and outputs\n * 2. Sends it to the ESP32 for signing (user confirms on device)\n * 3. Finalizes the signed PSBT and extracts the raw transaction\n *\n * @param options.network - Network type (default: uses device info)\n * @param options.utxos - UTXOs to spend (must include rawTxHex)\n * @param options.outputs - Destination outputs [{address, value}]\n * @param options.changeAddress - Address for change (typically device address)\n * @param options.pubkey - Compressed public key hex (from getAddress)\n * @param options.masterFingerprint - From getInfo().master_fingerprint\n * @param options.derivationPath - From getAddress().path\n * @param options.feeRate - Fee rate in sat/byte (default: 1024)\n * @returns ISignResult with txHex ready to broadcast\n */\n async signTransaction(options: {\n network?: NetworkType;\n utxos: IUTXO[];\n outputs: ITxOutput[];\n changeAddress: string;\n pubkey?: string;\n masterFingerprint?: string;\n derivationPath?: string;\n feeRate?: number;\n }): Promise<ISignResult> {\n // Use cached device info if available for defaults\n const info = this.deviceInfo;\n\n const network =\n options.network ?? this.inferNetworkType(info);\n const pubkey =\n options.pubkey ?? info?.pubkey;\n const masterFingerprint =\n options.masterFingerprint ?? info?.master_fingerprint;\n const derivationPath =\n options.derivationPath ?? info?.path;\n\n if (!pubkey) {\n throw new Error(\n \"pubkey required. Call getInfo() first or provide it explicitly.\"\n );\n }\n if (!masterFingerprint) {\n throw new Error(\n \"masterFingerprint required. Call getInfo() first or provide it explicitly.\"\n );\n }\n if (!derivationPath) {\n throw new Error(\n \"derivationPath required. Call getInfo() first or provide it explicitly.\"\n );\n }\n\n // 1. Build unsigned PSBT\n const psbtBase64 = buildPSBT({\n network,\n utxos: options.utxos,\n outputs: options.outputs,\n changeAddress: options.changeAddress,\n pubkey,\n masterFingerprint,\n derivationPath,\n feeRate: options.feeRate,\n });\n\n // 2. Send to ESP32 for signing\n const signResponse = await this.signPsbt(psbtBase64);\n\n // 3. Finalize and extract raw transaction\n const { txHex, txId } = finalizePSBT(signResponse.psbt, network);\n\n return {\n signedPsbtBase64: signResponse.psbt,\n txHex,\n txId,\n signedInputs: signResponse.signed_inputs,\n };\n }\n\n // ─── Private helpers ────────────────────────────────────────────────────\n\n private assertSuccess(response: DeviceResponse): void {\n if (response.status === \"error\") {\n throw new Error(\n `Device error: ${(response as IErrorResponse).message}`\n );\n }\n }\n\n /**\n * Infer the NetworkType from cached device info.\n */\n private inferNetworkType(info: IDeviceInfo | null): NetworkType {\n if (!info) {\n return \"xna\"; // default\n }\n\n const networkName = info.network?.toLowerCase() ?? \"\";\n const coinType = info.coin_type;\n\n if (networkName.includes(\"test\")) {\n return coinType === 1900 ? \"xna-test\" : \"xna-legacy-test\";\n }\n if (networkName.includes(\"legacy\") || coinType === 0) {\n return \"xna-legacy\";\n }\n return \"xna\";\n }\n}\n","/**\n * Web Serial API communication layer for ESP32 hardware wallet.\n *\n * Handles USB Serial connection, JSON command/response protocol,\n * and line-based buffering matching the NeuraiHW firmware protocol.\n */\n\nimport type { DeviceResponse, ISerialOptions } from \"./types.js\";\n\n// Default USB filters for ESP32 devices\nconst DEFAULT_FILTERS: SerialPortFilter[] = [\n { usbVendorId: 0x303a, usbProductId: 0x1001 }, // ESP32-S3 USB JTAG/Serial\n { usbVendorId: 0x303a }, // Espressif generic\n { usbVendorId: 0x10c4, usbProductId: 0xea60 }, // Silicon Labs CP210x\n { usbVendorId: 0x1a86, usbProductId: 0x7523 }, // CH340\n { usbVendorId: 0x0403, usbProductId: 0x6001 }, // FTDI FT232\n { usbVendorId: 0x067b, usbProductId: 0x2303 }, // Prolific PL2303\n { usbVendorId: 0x2886 }, // Seeed Studio (XIAO)\n];\n\nconst DEFAULT_BAUD_RATE = 115200;\n\nexport class SerialConnection {\n private port: SerialPort | null = null;\n private reader: ReadableStreamDefaultReader<string> | null = null;\n private writer: WritableStreamDefaultWriter<string> | null = null;\n private readableStreamClosed: Promise<void> | null = null;\n private writableStreamClosed: Promise<void> | null = null;\n private isReading = false;\n private responseQueue: DeviceResponse[] = [];\n private baudRate: number;\n private filters: SerialPortFilter[];\n\n constructor(options?: ISerialOptions) {\n this.baudRate = options?.baudRate ?? DEFAULT_BAUD_RATE;\n this.filters = options?.filters ?? DEFAULT_FILTERS;\n }\n\n /**\n * Check if Web Serial API is available.\n */\n static isSupported(): boolean {\n return typeof navigator !== \"undefined\" && \"serial\" in navigator;\n }\n\n /**\n * Open a serial connection to the ESP32.\n * Triggers browser port selection dialog.\n */\n async open(): Promise<void> {\n if (!SerialConnection.isSupported()) {\n throw new Error(\n \"Web Serial API not supported. Use Chrome, Edge, or Opera.\"\n );\n }\n\n this.port = await navigator.serial.requestPort({ filters: this.filters });\n await this.port.open({ baudRate: this.baudRate });\n\n // Set up readable stream (text decoding)\n const decoder = new TextDecoderStream();\n this.readableStreamClosed = this.port.readable!.pipeTo(decoder.writable as unknown as WritableStream<Uint8Array>);\n this.reader = decoder.readable.getReader();\n\n // Set up writable stream (text encoding)\n const encoder = new TextEncoderStream();\n this.writableStreamClosed = encoder.readable.pipeTo(this.port.writable!);\n this.writer = encoder.writable.getWriter();\n\n // Start background read loop\n this.isReading = true;\n this.readLoop();\n }\n\n /**\n * Close the serial connection.\n */\n async close(): Promise<void> {\n this.isReading = false;\n\n if (this.reader) {\n await this.reader.cancel();\n await this.readableStreamClosed?.catch(() => {});\n this.reader = null;\n }\n\n if (this.writer) {\n await this.writer.close();\n await this.writableStreamClosed;\n this.writer = null;\n }\n\n if (this.port) {\n await this.port.close();\n this.port = null;\n }\n\n this.responseQueue = [];\n }\n\n /**\n * Whether the serial port is currently connected.\n */\n get connected(): boolean {\n return this.port !== null && this.writer !== null;\n }\n\n /**\n * Send a JSON command to the device and wait for a JSON response.\n *\n * @param command - The command object (e.g. { action: \"info\" })\n * @param timeoutMs - Response timeout in milliseconds (default: 65000 for sign operations)\n * @returns The parsed device response\n */\n async sendCommand(\n command: Record<string, unknown>,\n timeoutMs = 65000\n ): Promise<DeviceResponse> {\n if (!this.writer) {\n throw new Error(\"Serial port not connected\");\n }\n\n // Clear stale responses\n this.responseQueue = [];\n\n // Send JSON in small chunks, then newline to trigger processing.\n // The ESP32 CDC serial buffer can lose data if sent too fast in one write.\n const json = JSON.stringify(command);\n await this.writeChunked(json);\n await this.writer.write(\"\\n\");\n\n // Wait for response\n const response = await this.waitForResponse(timeoutMs);\n if (!response) {\n throw new Error(\"Device response timeout\");\n }\n\n return response;\n }\n\n /**\n * Send a command and wait, skipping intermediate \"processing\" status messages.\n * Useful for sign_psbt which sends a processing ACK before the actual response.\n */\n async sendCommandFinal(\n command: Record<string, unknown>,\n timeoutMs = 65000\n ): Promise<DeviceResponse> {\n if (!this.writer) {\n throw new Error(\"Serial port not connected\");\n }\n\n this.responseQueue = [];\n\n const json = JSON.stringify(command);\n await this.writeChunked(json);\n await this.writer.write(\"\\n\");\n\n // Wait for a non-processing response\n const startTime = Date.now();\n while (Date.now() - startTime < timeoutMs) {\n const response = await this.waitForResponse(\n timeoutMs - (Date.now() - startTime)\n );\n if (!response) {\n throw new Error(\"Device response timeout\");\n }\n // Skip intermediate \"processing\" status\n if (response.status === \"processing\") {\n continue;\n }\n return response;\n }\n\n throw new Error(\"Device response timeout\");\n }\n\n // ─── Private ──────────────────────────────────────────────────────────────\n\n private async readLoop(): Promise<void> {\n let buffer = \"\";\n\n while (this.isReading && this.reader) {\n try {\n const { value, done } = await this.reader.read();\n if (done) break;\n\n buffer += value;\n\n // Process complete lines\n const lines = buffer.split(\"\\n\");\n buffer = lines.pop() ?? \"\"; // Keep incomplete line in buffer\n\n for (const rawLine of lines) {\n const line = rawLine.trim().replace(/\\r/g, \"\");\n if (line.length === 0) continue;\n\n // Try to parse as JSON response\n if (line.startsWith(\"{\")) {\n try {\n const data = JSON.parse(line) as DeviceResponse;\n this.responseQueue.push(data);\n } catch {\n // Not valid JSON — debug output from firmware, ignore\n }\n }\n // Non-JSON lines are firmware debug output, ignored\n }\n } catch {\n // Read error — connection may have been closed\n break;\n }\n }\n }\n\n private waitForResponse(timeoutMs: number): Promise<DeviceResponse | null> {\n return new Promise((resolve) => {\n const startTime = Date.now();\n const check = () => {\n if (this.responseQueue.length > 0) {\n resolve(this.responseQueue.shift()!);\n } else if (Date.now() - startTime > timeoutMs) {\n resolve(null);\n } else {\n setTimeout(check, 50);\n }\n };\n check();\n });\n }\n\n /**\n * Write data in small chunks with pauses between them.\n *\n * The ESP32 CDC serial buffer can lose data when the host sends a large\n * payload in a single write. Splitting into 32-byte chunks with a 4 ms\n * pause gives the firmware time to drain its receive buffer.\n */\n private async writeChunked(\n data: string,\n chunkSize = 32,\n pauseMs = 4\n ): Promise<void> {\n if (!this.writer) {\n throw new Error(\"Serial port not connected\");\n }\n\n for (let offset = 0; offset < data.length; offset += chunkSize) {\n const chunk = data.slice(offset, offset + chunkSize);\n await this.writer.write(chunk);\n if (offset + chunkSize < data.length) {\n await this.delay(pauseMs);\n }\n }\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n","/**\n * PSBT builder for Neurai P2PKH transactions.\n *\n * Creates unsigned PSBTs compatible with the NeuraiHW ESP32 firmware.\n * The ESP32 signs inputs that match its BIP32 derivation path and\n * master fingerprint.\n *\n * Requirements for each UTXO:\n * - rawTxHex: Full raw transaction hex (P2PKH needs nonWitnessUtxo)\n * - scriptPubKey: The output script being spent\n *\n * The PSBT includes BIP32 derivation metadata so the ESP32 can\n * verify and locate the correct signing key.\n */\n\nimport * as bitcoin from \"bitcoinjs-lib\";\nimport { ECPairFactory } from \"ecpair\";\nimport ecc from \"@bitcoinerlab/secp256k1\";\nimport { getNetwork } from \"./networks.js\";\nimport type { IBuildPSBTOptions, IUTXO } from \"./types.js\";\n\nconst ECPair = ECPairFactory(ecc);\n\nconst DEFAULT_FEE_RATE = 1024; // sat/byte\n\n// Estimated P2PKH tx sizes for fee calculation\nconst TX_OVERHEAD = 10; // version(4) + locktime(4) + varint(2)\nconst INPUT_SIZE = 148; // P2PKH input with signature\nconst OUTPUT_SIZE = 34; // P2PKH output\n\n/**\n * Estimate transaction size in bytes for P2PKH.\n */\nfunction estimateTxSize(inputCount: number, outputCount: number): number {\n return TX_OVERHEAD + inputCount * INPUT_SIZE + outputCount * OUTPUT_SIZE;\n}\n\n/**\n * Parse a master fingerprint hex string (8 chars) into a 4-byte Buffer.\n */\nfunction parseMasterFingerprint(hex: string): Buffer {\n if (hex.length !== 8) {\n throw new Error(\n `Invalid master fingerprint: expected 8 hex chars, got ${hex.length}`\n );\n }\n return Buffer.from(hex, \"hex\");\n}\n\n/**\n * Parse a BIP44 derivation path string into an array of uint32 indices.\n * e.g. \"m/44'/1900'/0'/0/0\" → [0x8000002C, 0x8000076C, 0x80000000, 0, 0]\n */\nfunction parseDerivationPath(path: string): number[] {\n return path\n .replace(/^m\\//, \"\")\n .split(\"/\")\n .map((part) => {\n const hardened = part.endsWith(\"'\");\n const index = parseInt(hardened ? part.slice(0, -1) : part, 10);\n return hardened ? index + 0x80000000 : index;\n });\n}\n\n/**\n * Build an unsigned PSBT for Neurai P2PKH, ready to send to the ESP32.\n *\n * @returns Base64-encoded PSBT string\n */\nexport function buildPSBT(options: IBuildPSBTOptions): string {\n const {\n network: networkType,\n utxos,\n outputs,\n changeAddress,\n pubkey,\n masterFingerprint,\n derivationPath,\n feeRate = DEFAULT_FEE_RATE,\n } = options;\n\n if (utxos.length === 0) {\n throw new Error(\"No UTXOs provided\");\n }\n if (outputs.length === 0) {\n throw new Error(\"No outputs provided\");\n }\n\n const network = getNetwork(networkType);\n const pubkeyBuffer = Buffer.from(pubkey, \"hex\");\n const fingerprintBuffer = parseMasterFingerprint(masterFingerprint);\n const bip32Path = parseDerivationPath(derivationPath);\n\n // Calculate total output amount\n const totalOutputValue = outputs.reduce((sum, o) => sum + o.value, 0);\n\n // Select UTXOs (use all provided — caller is responsible for UTXO selection)\n const totalInputValue = utxos.reduce((sum, u) => sum + u.satoshis, 0);\n\n // Estimate fee: outputs + possible change output\n const estimatedSize = estimateTxSize(utxos.length, outputs.length + 1);\n const fee = estimatedSize * feeRate;\n\n const change = totalInputValue - totalOutputValue - fee;\n\n if (change < 0) {\n throw new Error(\n `Insufficient funds: inputs=${totalInputValue}, outputs=${totalOutputValue}, fee=${fee}`\n );\n }\n\n // Build PSBT\n const psbt = new bitcoin.Psbt({ network });\n\n // BIP32 derivation metadata (same for all inputs from this device)\n const bip32Derivation = [\n {\n masterFingerprint: fingerprintBuffer,\n path: derivationPath,\n pubkey: pubkeyBuffer,\n },\n ];\n\n // Add inputs\n for (const utxo of utxos) {\n psbt.addInput({\n hash: utxo.txid,\n index: utxo.vout,\n nonWitnessUtxo: Buffer.from(utxo.rawTxHex, \"hex\"),\n bip32Derivation,\n });\n }\n\n // Add destination outputs\n for (const output of outputs) {\n psbt.addOutput({\n address: output.address,\n value: BigInt(output.value),\n });\n }\n\n // Add change output (if change > dust threshold)\n const DUST_THRESHOLD = 546; // standard dust for P2PKH\n if (change >= DUST_THRESHOLD) {\n psbt.addOutput({\n address: changeAddress,\n value: BigInt(change),\n bip32Derivation,\n });\n }\n\n return psbt.toBase64();\n}\n\n/**\n * Finalize a signed PSBT and extract the raw transaction.\n *\n * Call this after receiving the signed PSBT back from the ESP32.\n *\n * @param signedPsbtBase64 - Base64-encoded signed PSBT from the device\n * @param network - Network type\n * @returns Object with txHex (raw tx for broadcast) and txId\n */\nexport function finalizePSBT(\n signedPsbtBase64: string,\n network: \"xna\" | \"xna-test\" | \"xna-legacy\" | \"xna-legacy-test\"\n): { txHex: string; txId: string } {\n const net = getNetwork(network);\n const psbt = bitcoin.Psbt.fromBase64(signedPsbtBase64, { network: net });\n\n psbt.finalizeAllInputs();\n\n const tx = psbt.extractTransaction();\n return {\n txHex: tx.toHex(),\n txId: tx.getId(),\n };\n}\n\n/**\n * Validate that a PSBT base64 string is parseable.\n */\nexport function validatePSBT(\n psbtBase64: string,\n network: \"xna\" | \"xna-test\" | \"xna-legacy\" | \"xna-legacy-test\"\n): boolean {\n try {\n const net = getNetwork(network);\n bitcoin.Psbt.fromBase64(psbtBase64, { network: net });\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * Neurai network configurations for bitcoinjs-lib\n *\n * Defines all Neurai networks (mainnet, testnet, legacy variants)\n * in the format required by bitcoinjs-lib v7.\n */\n\nimport type { Network } from \"bitcoinjs-lib\";\nimport type { NetworkType } from \"./types.js\";\n\n// ─── Neurai Mainnet (coin type 1900) ────────────────────────────────────────\n\nexport const neuraiMainnet: Network = {\n messagePrefix: \"Neurai Signed Message:\\n\",\n bech32: \"\",\n bip32: {\n public: 76067358,\n private: 76066276,\n },\n pubKeyHash: 53, // 0x35 → prefix \"N\"\n scriptHash: 117, // 0x75\n wif: 128, // 0x80\n};\n\n// ─── Neurai Testnet ──────────────────────────────────────────────────────────\n\nexport const neuraiTestnet: Network = {\n messagePrefix: \"Neurai Signed Message:\\n\",\n bech32: \"\",\n bip32: {\n public: 70617039,\n private: 70615956,\n },\n pubKeyHash: 127, // 0x7f\n scriptHash: 196, // 0xc4\n wif: 239, // 0xef\n};\n\n// ─── Neurai Legacy Mainnet (coin type 0) ─────────────────────────────────────\n\nexport const neuraiLegacyMainnet: Network = {\n messagePrefix: \"Neurai Signed Message:\\n\",\n bech32: \"\",\n bip32: {\n public: 76067358,\n private: 76066276,\n },\n pubKeyHash: 53,\n scriptHash: 117,\n wif: 128,\n};\n\n// ─── Neurai Legacy Testnet ───────────────────────────────────────────────────\n\nexport const neuraiLegacyTestnet: Network = {\n messagePrefix: \"Neurai Signed Message:\\n\",\n bech32: \"\",\n bip32: {\n public: 70617039,\n private: 70615956,\n },\n pubKeyHash: 127,\n scriptHash: 196,\n wif: 239,\n};\n\n// ─── Network map ─────────────────────────────────────────────────────────────\n\nconst networkMap: Record<NetworkType, Network> = {\n xna: neuraiMainnet,\n \"xna-test\": neuraiTestnet,\n \"xna-legacy\": neuraiLegacyMainnet,\n \"xna-legacy-test\": neuraiLegacyTestnet,\n};\n\n/**\n * Get the bitcoinjs-lib Network object for a given Neurai network type.\n */\nexport function getNetwork(network: NetworkType): Network {\n const net = networkMap[network];\n if (!net) {\n throw new Error(`Unknown network: ${network}`);\n }\n return net;\n}\n"],"names":[],"version":3,"file":"index.cjs.map"}