@neuraiproject/neurai-sign-esp32 0.1.0 → 0.2.1

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 CHANGED
@@ -1,19 +1,16 @@
1
+ var $8zHUo$buffer = require("buffer");
1
2
  var $8zHUo$bitcoinjslib = require("bitcoinjs-lib");
2
- var $8zHUo$ecpair = require("ecpair");
3
- var $8zHUo$bitcoinerlabsecp256k1 = require("@bitcoinerlab/secp256k1");
4
3
 
5
4
 
6
5
  function $parcel$export(e, n, v, s) {
7
6
  Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
8
7
  }
9
8
 
10
- function $parcel$interopDefault(a) {
11
- return a && a.__esModule ? a.default : a;
12
- }
13
-
14
9
  $parcel$export(module.exports, "NeuraiESP32", () => $4f193116bbff8497$export$fa10ee8b91a777b7);
15
10
  $parcel$export(module.exports, "buildPSBT", () => $5da7d5b3a851268c$export$236ea1e009011592);
11
+ $parcel$export(module.exports, "buildPSBTFromRawTransaction", () => $5da7d5b3a851268c$export$e0e3d6f226ea0b0a);
16
12
  $parcel$export(module.exports, "finalizePSBT", () => $5da7d5b3a851268c$export$ce839c4c9bcf7b77);
13
+ $parcel$export(module.exports, "finalizeSignedPSBT", () => $5da7d5b3a851268c$export$3a31c64c43aacd3);
17
14
  $parcel$export(module.exports, "validatePSBT", () => $5da7d5b3a851268c$export$78a5723c75e7be9);
18
15
  $parcel$export(module.exports, "SerialConnection", () => $a48f33fba55d0d0b$export$f93edba7156cc57b);
19
16
  $parcel$export(module.exports, "getNetwork", () => $8eddb774c9d38ccb$export$7de4970ebfd8206d);
@@ -106,7 +103,12 @@ class $a48f33fba55d0d0b$export$f93edba7156cc57b {
106
103
  filters: this.filters
107
104
  });
108
105
  await this.port.open({
109
- baudRate: this.baudRate
106
+ baudRate: this.baudRate,
107
+ dataBits: 8,
108
+ stopBits: 1,
109
+ parity: "none",
110
+ flowControl: "none",
111
+ bufferSize: 8192
110
112
  });
111
113
  // Set up readable stream (text decoding)
112
114
  const decoder = new TextDecoderStream();
@@ -119,6 +121,9 @@ class $a48f33fba55d0d0b$export$f93edba7156cc57b {
119
121
  // Start background read loop
120
122
  this.isReading = true;
121
123
  this.readLoop();
124
+ // Give the ESP32 CDC port time to settle after connect/re-enumeration.
125
+ await this.delay(1200);
126
+ this.responseQueue = [];
122
127
  }
123
128
  /**
124
129
  * Close the serial connection.
@@ -159,6 +164,7 @@ class $a48f33fba55d0d0b$export$f93edba7156cc57b {
159
164
  // The ESP32 CDC serial buffer can lose data if sent too fast in one write.
160
165
  const json = JSON.stringify(command);
161
166
  await this.writeChunked(json);
167
+ await this.writer.ready;
162
168
  await this.writer.write("\n");
163
169
  // Wait for response
164
170
  const response = await this.waitForResponse(timeoutMs);
@@ -173,6 +179,7 @@ class $a48f33fba55d0d0b$export$f93edba7156cc57b {
173
179
  this.responseQueue = [];
174
180
  const json = JSON.stringify(command);
175
181
  await this.writeChunked(json);
182
+ await this.writer.ready;
176
183
  await this.writer.write("\n");
177
184
  // Wait for a non-processing response
178
185
  const startTime = Date.now();
@@ -232,6 +239,7 @@ class $a48f33fba55d0d0b$export$f93edba7156cc57b {
232
239
  if (!this.writer) throw new Error("Serial port not connected");
233
240
  for(let offset = 0; offset < data.length; offset += chunkSize){
234
241
  const chunk = data.slice(offset, offset + chunkSize);
242
+ await this.writer.ready;
235
243
  await this.writer.write(chunk);
236
244
  if (offset + chunkSize < data.length) await this.delay(pauseMs);
237
245
  }
@@ -243,21 +251,16 @@ class $a48f33fba55d0d0b$export$f93edba7156cc57b {
243
251
 
244
252
 
245
253
  /**
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.
254
+ * PSBT helpers for Neurai P2PKH transactions.
251
255
  *
252
- * Requirements for each UTXO:
253
- * - rawTxHex: Full raw transaction hex (P2PKH needs nonWitnessUtxo)
254
- * - scriptPubKey: The output script being spent
256
+ * This package supports two build paths:
257
+ * - high-level build from UTXOs + outputs + fee estimation
258
+ * - low-level build from an already-created raw unsigned transaction
255
259
  *
256
- * The PSBT includes BIP32 derivation metadata so the ESP32 can
257
- * verify and locate the correct signing key.
260
+ * The second path matches the webwallet integration, where coin selection
261
+ * and fee calculation already happen elsewhere.
258
262
  */
259
263
 
260
-
261
264
  /**
262
265
  * Neurai network configurations for bitcoinjs-lib
263
266
  *
@@ -321,76 +324,48 @@ function $8eddb774c9d38ccb$export$7de4970ebfd8206d(network) {
321
324
  }
322
325
 
323
326
 
324
- const $5da7d5b3a851268c$var$ECPair = (0, $8zHUo$ecpair.ECPairFactory)((0, ($parcel$interopDefault($8zHUo$bitcoinerlabsecp256k1))));
325
327
  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) {
328
+ const $5da7d5b3a851268c$var$TX_OVERHEAD = 10;
329
+ const $5da7d5b3a851268c$var$INPUT_SIZE = 148;
330
+ const $5da7d5b3a851268c$var$OUTPUT_SIZE = 34;
331
+ function $5da7d5b3a851268c$var$estimateTxSize(inputCount, outputCount) {
333
332
  return $5da7d5b3a851268c$var$TX_OVERHEAD + inputCount * $5da7d5b3a851268c$var$INPUT_SIZE + outputCount * $5da7d5b3a851268c$var$OUTPUT_SIZE;
334
333
  }
335
- /**
336
- * Parse a master fingerprint hex string (8 chars) into a 4-byte Buffer.
337
- */ function $5da7d5b3a851268c$var$parseMasterFingerprint(hex) {
334
+ function $5da7d5b3a851268c$var$parseMasterFingerprint(hex) {
338
335
  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
- });
336
+ return (0, $8zHUo$buffer.Buffer).from(hex, "hex");
350
337
  }
351
338
  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;
339
+ const { network: network, utxos: utxos, outputs: outputs, changeAddress: changeAddress, pubkey: pubkey, masterFingerprint: masterFingerprint, derivationPath: derivationPath, feeRate: feeRate = $5da7d5b3a851268c$var$DEFAULT_FEE_RATE } = options;
353
340
  if (utxos.length === 0) throw new Error("No UTXOs provided");
354
341
  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
342
+ const totalOutputValue = outputs.reduce((sum, output)=>sum + output.value, 0);
343
+ const totalInputValue = utxos.reduce((sum, utxo)=>sum + utxo.satoshis, 0);
364
344
  const estimatedSize = $5da7d5b3a851268c$var$estimateTxSize(utxos.length, outputs.length + 1);
365
345
  const fee = estimatedSize * feeRate;
366
346
  const change = totalInputValue - totalOutputValue - fee;
367
347
  if (change < 0) throw new Error(`Insufficient funds: inputs=${totalInputValue}, outputs=${totalOutputValue}, fee=${fee}`);
368
- // Build PSBT
369
348
  const psbt = new $8zHUo$bitcoinjslib.Psbt({
370
- network: network
349
+ network: (0, $8eddb774c9d38ccb$export$7de4970ebfd8206d)(network)
371
350
  });
372
- // BIP32 derivation metadata (same for all inputs from this device)
373
351
  const bip32Derivation = [
374
352
  {
375
- masterFingerprint: fingerprintBuffer,
353
+ masterFingerprint: $5da7d5b3a851268c$var$parseMasterFingerprint(masterFingerprint),
376
354
  path: derivationPath,
377
- pubkey: pubkeyBuffer
355
+ pubkey: (0, $8zHUo$buffer.Buffer).from(pubkey, "hex")
378
356
  }
379
357
  ];
380
- // Add inputs
381
358
  for (const utxo of utxos)psbt.addInput({
382
359
  hash: utxo.txid,
383
360
  index: utxo.vout,
384
- nonWitnessUtxo: Buffer.from(utxo.rawTxHex, "hex"),
361
+ nonWitnessUtxo: (0, $8zHUo$buffer.Buffer).from(utxo.rawTxHex, "hex"),
385
362
  bip32Derivation: bip32Derivation
386
363
  });
387
- // Add destination outputs
388
364
  for (const output of outputs)psbt.addOutput({
389
365
  address: output.address,
390
366
  value: BigInt(output.value)
391
367
  });
392
- // Add change output (if change > dust threshold)
393
- const DUST_THRESHOLD = 546; // standard dust for P2PKH
368
+ const DUST_THRESHOLD = 546;
394
369
  if (change >= DUST_THRESHOLD) psbt.addOutput({
395
370
  address: changeAddress,
396
371
  value: BigInt(change),
@@ -398,10 +373,41 @@ function $5da7d5b3a851268c$export$236ea1e009011592(options) {
398
373
  });
399
374
  return psbt.toBase64();
400
375
  }
376
+ function $5da7d5b3a851268c$export$e0e3d6f226ea0b0a(options) {
377
+ const network = (0, $8eddb774c9d38ccb$export$7de4970ebfd8206d)(options.network);
378
+ const tx = $8zHUo$bitcoinjslib.Transaction.fromHex(options.rawUnsignedTransaction);
379
+ const psbt = new $8zHUo$bitcoinjslib.Psbt({
380
+ network: network
381
+ });
382
+ psbt.setVersion(tx.version);
383
+ psbt.setLocktime(tx.locktime);
384
+ for(let index = 0; index < tx.ins.length; index += 1){
385
+ const input = tx.ins[index];
386
+ const metadata = options.inputs[index];
387
+ if (!metadata) throw new Error(`Missing input metadata for input #${index}`);
388
+ psbt.addInput({
389
+ hash: metadata.txid,
390
+ index: metadata.vout,
391
+ sequence: metadata.sequence ?? input.sequence,
392
+ nonWitnessUtxo: (0, $8zHUo$buffer.Buffer).from(metadata.rawTxHex, "hex"),
393
+ bip32Derivation: [
394
+ {
395
+ masterFingerprint: $5da7d5b3a851268c$var$parseMasterFingerprint(metadata.masterFingerprint),
396
+ path: metadata.derivationPath,
397
+ pubkey: (0, $8zHUo$buffer.Buffer).from(metadata.pubkey, "hex")
398
+ }
399
+ ]
400
+ });
401
+ }
402
+ for (const output of tx.outs)psbt.addOutput({
403
+ script: (0, $8zHUo$buffer.Buffer).from(output.script),
404
+ value: output.value
405
+ });
406
+ return psbt.toBase64();
407
+ }
401
408
  function $5da7d5b3a851268c$export$ce839c4c9bcf7b77(signedPsbtBase64, network) {
402
- const net = (0, $8eddb774c9d38ccb$export$7de4970ebfd8206d)(network);
403
409
  const psbt = $8zHUo$bitcoinjslib.Psbt.fromBase64(signedPsbtBase64, {
404
- network: net
410
+ network: (0, $8eddb774c9d38ccb$export$7de4970ebfd8206d)(network)
405
411
  });
406
412
  psbt.finalizeAllInputs();
407
413
  const tx = psbt.extractTransaction();
@@ -410,17 +416,132 @@ function $5da7d5b3a851268c$export$ce839c4c9bcf7b77(signedPsbtBase64, network) {
410
416
  txId: tx.getId()
411
417
  };
412
418
  }
419
+ function $5da7d5b3a851268c$export$3a31c64c43aacd3(originalPsbtBase64, signedPsbtBase64, network) {
420
+ const net = (0, $8eddb774c9d38ccb$export$7de4970ebfd8206d)(network);
421
+ const psbt = $8zHUo$bitcoinjslib.Psbt.fromBase64(originalPsbtBase64, {
422
+ network: net
423
+ });
424
+ let mergedWithStandardPsbt = false;
425
+ try {
426
+ const signedPsbt = $8zHUo$bitcoinjslib.Psbt.fromBase64(signedPsbtBase64, {
427
+ network: net
428
+ });
429
+ psbt.combine(signedPsbt);
430
+ mergedWithStandardPsbt = true;
431
+ } catch {
432
+ // uNeurai can return a minimal signed PSBT that bitcoinjs-lib cannot fully parse.
433
+ }
434
+ if (!mergedWithStandardPsbt) {
435
+ const partialSigsByInput = $5da7d5b3a851268c$var$extractPartialSigsFromUNeuraiPsbt(originalPsbtBase64, signedPsbtBase64, psbt.inputCount);
436
+ partialSigsByInput.forEach((partialSig, index)=>{
437
+ if (partialSig.length === 0) return;
438
+ psbt.updateInput(index, {
439
+ partialSig: partialSig
440
+ });
441
+ });
442
+ }
443
+ try {
444
+ psbt.finalizeAllInputs();
445
+ } catch {
446
+ $5da7d5b3a851268c$var$finalizeLegacyP2pkhInputs(psbt);
447
+ }
448
+ const tx = psbt.extractTransaction(true);
449
+ return {
450
+ txHex: tx.toHex(),
451
+ txId: tx.getId()
452
+ };
453
+ }
413
454
  function $5da7d5b3a851268c$export$78a5723c75e7be9(psbtBase64, network) {
414
455
  try {
415
- const net = (0, $8eddb774c9d38ccb$export$7de4970ebfd8206d)(network);
416
456
  $8zHUo$bitcoinjslib.Psbt.fromBase64(psbtBase64, {
417
- network: net
457
+ network: (0, $8eddb774c9d38ccb$export$7de4970ebfd8206d)(network)
418
458
  });
419
459
  return true;
420
460
  } catch {
421
461
  return false;
422
462
  }
423
463
  }
464
+ function $5da7d5b3a851268c$var$extractPartialSigsFromUNeuraiPsbt(originalBase64, signedBase64, inputCount) {
465
+ const originalBuffer = (0, $8zHUo$buffer.Buffer).from(originalBase64, "base64");
466
+ const buffer = (0, $8zHUo$buffer.Buffer).from(signedBase64, "base64");
467
+ const partialSigsByInput = Array.from({
468
+ length: inputCount
469
+ }, ()=>[]);
470
+ if (buffer.length < 5 || buffer.toString("ascii", 0, 4) !== "psbt" || buffer[4] !== 0xff) throw new Error("NeuraiHW returned an invalid PSBT header");
471
+ let offset = $5da7d5b3a851268c$var$getFirstInputSectionOffset(originalBuffer);
472
+ for(let inputIndex = 0; inputIndex < inputCount; inputIndex += 1)while(offset < buffer.length){
473
+ const keyLen = $5da7d5b3a851268c$var$readPsbtVarInt(buffer, offset);
474
+ offset += keyLen.size;
475
+ if (keyLen.value === 0) break;
476
+ const key = buffer.subarray(offset, offset + keyLen.value);
477
+ offset += keyLen.value;
478
+ const valueLen = $5da7d5b3a851268c$var$readPsbtVarInt(buffer, offset);
479
+ offset += valueLen.size;
480
+ const value = buffer.subarray(offset, offset + valueLen.value);
481
+ offset += valueLen.value;
482
+ if (key.length > 1 && key[0] === 0x02) partialSigsByInput[inputIndex].push({
483
+ pubkey: (0, $8zHUo$buffer.Buffer).from(key.subarray(1)),
484
+ signature: (0, $8zHUo$buffer.Buffer).from(value)
485
+ });
486
+ }
487
+ return partialSigsByInput;
488
+ }
489
+ function $5da7d5b3a851268c$var$getFirstInputSectionOffset(buffer) {
490
+ if (buffer.length < 5 || buffer.toString("ascii", 0, 4) !== "psbt" || buffer[4] !== 0xff) throw new Error("Invalid original PSBT header");
491
+ let offset = 5;
492
+ const globalKeyLen = $5da7d5b3a851268c$var$readPsbtVarInt(buffer, offset);
493
+ offset += globalKeyLen.size + globalKeyLen.value;
494
+ const globalValueLen = $5da7d5b3a851268c$var$readPsbtVarInt(buffer, offset);
495
+ offset += globalValueLen.size + globalValueLen.value;
496
+ if (offset >= buffer.length || buffer[offset] !== 0x00) throw new Error("Invalid original PSBT global section");
497
+ return offset + 1;
498
+ }
499
+ function $5da7d5b3a851268c$var$readPsbtVarInt(buffer, offset) {
500
+ if (offset >= buffer.length) throw new Error("Format Error: Unexpected End of PSBT");
501
+ const first = buffer[offset];
502
+ if (first < 0xfd) return {
503
+ value: first,
504
+ size: 1
505
+ };
506
+ if (first === 0xfd) {
507
+ if (offset + 2 >= buffer.length) throw new Error("Format Error: Unexpected End of PSBT");
508
+ return {
509
+ value: buffer.readUInt16LE(offset + 1),
510
+ size: 3
511
+ };
512
+ }
513
+ if (first === 0xfe) {
514
+ if (offset + 4 >= buffer.length) throw new Error("Format Error: Unexpected End of PSBT");
515
+ return {
516
+ value: buffer.readUInt32LE(offset + 1),
517
+ size: 5
518
+ };
519
+ }
520
+ throw new Error("PSBT values larger than 32 bits are not supported");
521
+ }
522
+ function $5da7d5b3a851268c$var$finalizeLegacyP2pkhInputs(psbt) {
523
+ for(let index = 0; index < psbt.inputCount; index += 1){
524
+ const input = psbt.data.inputs[index];
525
+ if (input.finalScriptSig || input.finalScriptWitness) continue;
526
+ const partialSig = input.partialSig?.[0];
527
+ const nonWitnessUtxo = input.nonWitnessUtxo;
528
+ const txInput = psbt.txInputs[index];
529
+ if (!partialSig || !nonWitnessUtxo || !txInput) throw new Error(`Missing data to finalize input #${index}`);
530
+ const prevTx = $8zHUo$bitcoinjslib.Transaction.fromBuffer(nonWitnessUtxo);
531
+ const prevOut = prevTx.outs[txInput.index];
532
+ if (!prevOut) throw new Error(`Missing prevout to finalize input #${index}`);
533
+ const chunks = $8zHUo$bitcoinjslib.script.decompile(prevOut.script);
534
+ const isP2pkh = !!chunks && chunks.length === 5 && chunks[0] === $8zHUo$bitcoinjslib.opcodes.OP_DUP && chunks[1] === $8zHUo$bitcoinjslib.opcodes.OP_HASH160 && (0, $8zHUo$buffer.Buffer).isBuffer(chunks[2]) && chunks[3] === $8zHUo$bitcoinjslib.opcodes.OP_EQUALVERIFY && chunks[4] === $8zHUo$bitcoinjslib.opcodes.OP_CHECKSIG;
535
+ if (!isP2pkh) throw new Error(`Unsupported script type for input #${index}`);
536
+ psbt.finalizeInput(index, ()=>({
537
+ finalScriptSig: $8zHUo$bitcoinjslib.script.compile([
538
+ partialSig.signature,
539
+ partialSig.pubkey
540
+ ]),
541
+ finalScriptWitness: undefined
542
+ }));
543
+ }
544
+ }
424
545
 
425
546
 
426
547
  class $4f193116bbff8497$export$fa10ee8b91a777b7 {
@@ -543,7 +664,7 @@ class $4f193116bbff8497$export$fa10ee8b91a777b7 {
543
664
  // 2. Send to ESP32 for signing
544
665
  const signResponse = await this.signPsbt(psbtBase64);
545
666
  // 3. Finalize and extract raw transaction
546
- const { txHex: txHex, txId: txId } = (0, $5da7d5b3a851268c$export$ce839c4c9bcf7b77)(signResponse.psbt, network);
667
+ const { txHex: txHex, txId: txId } = (0, $5da7d5b3a851268c$export$3a31c64c43aacd3)(psbtBase64, signResponse.psbt, network);
547
668
  return {
548
669
  signedPsbtBase64: signResponse.psbt,
549
670
  txHex: txHex,
@@ -1 +1 @@
1
- {"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA;;;;;CAKC,GAED,aAAa;ACPb;;;;;;;;;;;;;;;;;;ACAA;;;;;CAKC,GAID,wCAAwC;AACxC,MAAM,wCAAsC;IAC1C;QAAE,aAAa;QAAQ,cAAc;IAAO;IAC5C;QAAE,aAAa;IAAO;IACtB;QAAE,aAAa;QAAQ,cAAc;IAAO;IAC5C;QAAE,aAAa;QAAQ,cAAc;IAAO;IAC5C;QAAE,aAAa;QAAQ,cAAc;IAAO;IAC5C;QAAE,aAAa;QAAQ,cAAc;IAAO;IAC5C;QAAE,aAAa;IAAO;CACvB;AAED,MAAM,0CAAoB;AAEnB,MAAM;IAWX,YAAY,OAAwB,CAAE;aAV9B,OAA0B;aAC1B,SAAqD;aACrD,SAAqD;aACrD,uBAA6C;aAC7C,uBAA6C;aAC7C,YAAY;aACZ,gBAAkC,EAAE;QAK1C,IAAI,CAAC,QAAQ,GAAG,SAAS,YAAY;QACrC,IAAI,CAAC,OAAO,GAAG,SAAS,WAAW;IACrC;IAEA;;GAEC,GACD,OAAO,cAAuB;QAC5B,OAAO,OAA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,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"}
1
+ {"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;;;;;CAKC,GAED,aAAa;ACPb;;;;;;;;;;;;;;;;;;ACAA;;;;;CAKC,GAID,wCAAwC;AACxC,MAAM,wCAAsC;IAC1C;QAAE,aAAa;QAAQ,cAAc;IAAO;IAC5C;QAAE,aAAa;IAAO;IACtB;QAAE,aAAa;QAAQ,cAAc;IAAO;IAC5C;QAAE,aAAa;QAAQ,cAAc;IAAO;IAC5C;QAAE,aAAa;QAAQ,cAAc;IAAO;IAC5C;QAAE,aAAa;QAAQ,cAAc;IAAO;IAC5C;QAAE,aAAa;IAAO;CACvB;AAED,MAAM,0CAAoB;AAEnB,MAAM;IAWX,YAAY,OAAwB,CAAE;aAV9B,OAA0B;aAC1B,SAAqD;aACrD,SAAqD;aACrD,uBAA6C;aAC7C,uBAA6C;aAC7C,YAAY;aACZ,gBAAkC,EAAE;QAK1C,IAAI,CAAC,QAAQ,GAAG,SAAS,YAAY;QACrC,IAAI,CAAC,OAAO,GAAG,SAAS,WAAW;IACrC;IAEA;;GAEC,GACD,OAAO,cAAuB;QAC5B,OAAO,OAAO,cAAc,eAAe,YAAY;IACzD;IAEA;;;GAGC,GACD,MAAM,OAAsB;QAC1B,IAAI,CAAC,0CAAiB,WAAW,IAC/B,MAAM,IAAI,MACR;QAIJ,IAAI,CAAC,IAAI,GAAG,MAAM,UAAU,MAAM,CAAC,WAAW,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M,IAAI,MACR;QAGJ,IAAI,CAAC,mBACH,MAAM,IAAI,MACR;QAGJ,IAAI,CAAC,gBACH,MAAM,IAAI,MACR;QAIJ,yBAAyB;QACzB,MAAM,aAAa,CAAA,GAAA,yCAAQ,EAAE;qBAC3B;YACA,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,wCAAiB,EACvC,YACA,aAAa,IAAI,EACjB;QAGF,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 {\n buildPSBT,\n buildPSBTFromRawTransaction,\n finalizePSBT,\n finalizeSignedPSBT,\n validatePSBT,\n} 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 IBuildPSBTFromRawOptions,\n IPSBTInputMetadata,\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, finalizeSignedPSBT } 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 } = finalizeSignedPSBT(\n psbtBase64,\n signResponse.psbt,\n network\n );\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({\n baudRate: this.baudRate,\n dataBits: 8,\n stopBits: 1,\n parity: \"none\",\n flowControl: \"none\",\n bufferSize: 8192,\n });\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 void this.readLoop();\n\n // Give the ESP32 CDC port time to settle after connect/re-enumeration.\n await this.delay(1200);\n this.responseQueue = [];\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.ready;\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.ready;\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.ready;\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 helpers for Neurai P2PKH transactions.\n *\n * This package supports two build paths:\n * - high-level build from UTXOs + outputs + fee estimation\n * - low-level build from an already-created raw unsigned transaction\n *\n * The second path matches the webwallet integration, where coin selection\n * and fee calculation already happen elsewhere.\n */\n\nimport { Buffer } from \"buffer\";\nimport * as bitcoin from \"bitcoinjs-lib\";\nimport { getNetwork } from \"./networks.js\";\nimport type {\n IBuildPSBTFromRawOptions,\n IBuildPSBTOptions,\n IPSBTInputMetadata,\n NetworkType,\n} from \"./types.js\";\n\nconst DEFAULT_FEE_RATE = 1024; // sat/byte\n\nconst TX_OVERHEAD = 10;\nconst INPUT_SIZE = 148;\nconst OUTPUT_SIZE = 34;\n\nfunction estimateTxSize(inputCount: number, outputCount: number): number {\n return TX_OVERHEAD + inputCount * INPUT_SIZE + outputCount * OUTPUT_SIZE;\n}\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\nexport function buildPSBT(options: IBuildPSBTOptions): string {\n const {\n network,\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 totalOutputValue = outputs.reduce((sum, output) => sum + output.value, 0);\n const totalInputValue = utxos.reduce((sum, utxo) => sum + utxo.satoshis, 0);\n const estimatedSize = estimateTxSize(utxos.length, outputs.length + 1);\n const fee = estimatedSize * feeRate;\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 const psbt = new bitcoin.Psbt({ network: getNetwork(network) });\n const bip32Derivation = [\n {\n masterFingerprint: parseMasterFingerprint(masterFingerprint),\n path: derivationPath,\n pubkey: Buffer.from(pubkey, \"hex\"),\n },\n ];\n\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 for (const output of outputs) {\n psbt.addOutput({\n address: output.address,\n value: BigInt(output.value),\n });\n }\n\n const DUST_THRESHOLD = 546;\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\nexport function buildPSBTFromRawTransaction(options: IBuildPSBTFromRawOptions): string {\n const network = getNetwork(options.network);\n const tx = bitcoin.Transaction.fromHex(options.rawUnsignedTransaction);\n const psbt = new bitcoin.Psbt({ network });\n\n psbt.setVersion(tx.version);\n psbt.setLocktime(tx.locktime);\n\n for (let index = 0; index < tx.ins.length; index += 1) {\n const input = tx.ins[index];\n const metadata = options.inputs[index];\n\n if (!metadata) {\n throw new Error(`Missing input metadata for input #${index}`);\n }\n\n psbt.addInput({\n hash: metadata.txid,\n index: metadata.vout,\n sequence: metadata.sequence ?? input.sequence,\n nonWitnessUtxo: Buffer.from(metadata.rawTxHex, \"hex\"),\n bip32Derivation: [\n {\n masterFingerprint: parseMasterFingerprint(metadata.masterFingerprint),\n path: metadata.derivationPath,\n pubkey: Buffer.from(metadata.pubkey, \"hex\"),\n },\n ],\n });\n }\n\n for (const output of tx.outs) {\n psbt.addOutput({\n script: Buffer.from(output.script),\n value: output.value,\n });\n }\n\n return psbt.toBase64();\n}\n\nexport function finalizePSBT(\n signedPsbtBase64: string,\n network: NetworkType\n): { txHex: string; txId: string } {\n const psbt = bitcoin.Psbt.fromBase64(signedPsbtBase64, {\n network: getNetwork(network),\n });\n\n psbt.finalizeAllInputs();\n\n const tx = psbt.extractTransaction();\n return {\n txHex: tx.toHex(),\n txId: tx.getId(),\n };\n}\n\nexport function finalizeSignedPSBT(\n originalPsbtBase64: string,\n signedPsbtBase64: string,\n network: NetworkType\n): { txHex: string; txId: string } {\n const net = getNetwork(network);\n const psbt = bitcoin.Psbt.fromBase64(originalPsbtBase64, { network: net });\n\n let mergedWithStandardPsbt = false;\n try {\n const signedPsbt = bitcoin.Psbt.fromBase64(signedPsbtBase64, { network: net });\n psbt.combine(signedPsbt);\n mergedWithStandardPsbt = true;\n } catch {\n // uNeurai can return a minimal signed PSBT that bitcoinjs-lib cannot fully parse.\n }\n\n if (!mergedWithStandardPsbt) {\n const partialSigsByInput = extractPartialSigsFromUNeuraiPsbt(\n originalPsbtBase64,\n signedPsbtBase64,\n psbt.inputCount\n );\n\n partialSigsByInput.forEach((partialSig, index) => {\n if (partialSig.length === 0) {\n return;\n }\n psbt.updateInput(index, { partialSig });\n });\n }\n\n try {\n psbt.finalizeAllInputs();\n } catch {\n finalizeLegacyP2pkhInputs(psbt);\n }\n\n const tx = psbt.extractTransaction(true);\n return {\n txHex: tx.toHex(),\n txId: tx.getId(),\n };\n}\n\nexport function validatePSBT(psbtBase64: string, network: NetworkType): boolean {\n try {\n bitcoin.Psbt.fromBase64(psbtBase64, { network: getNetwork(network) });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction extractPartialSigsFromUNeuraiPsbt(\n originalBase64: string,\n signedBase64: string,\n inputCount: number\n) {\n const originalBuffer = Buffer.from(originalBase64, \"base64\");\n const buffer = Buffer.from(signedBase64, \"base64\");\n const partialSigsByInput: { pubkey: Buffer; signature: Buffer }[][] = Array.from(\n { length: inputCount },\n () => []\n );\n\n if (buffer.length < 5 || buffer.toString(\"ascii\", 0, 4) !== \"psbt\" || buffer[4] !== 0xff) {\n throw new Error(\"NeuraiHW returned an invalid PSBT header\");\n }\n\n let offset = getFirstInputSectionOffset(originalBuffer);\n\n for (let inputIndex = 0; inputIndex < inputCount; inputIndex += 1) {\n while (offset < buffer.length) {\n const keyLen = readPsbtVarInt(buffer, offset);\n offset += keyLen.size;\n\n if (keyLen.value === 0) {\n break;\n }\n\n const key = buffer.subarray(offset, offset + keyLen.value);\n offset += keyLen.value;\n\n const valueLen = readPsbtVarInt(buffer, offset);\n offset += valueLen.size;\n const value = buffer.subarray(offset, offset + valueLen.value);\n offset += valueLen.value;\n\n if (key.length > 1 && key[0] === 0x02) {\n partialSigsByInput[inputIndex].push({\n pubkey: Buffer.from(key.subarray(1)),\n signature: Buffer.from(value),\n });\n }\n }\n }\n\n return partialSigsByInput;\n}\n\nfunction getFirstInputSectionOffset(buffer: Buffer) {\n if (buffer.length < 5 || buffer.toString(\"ascii\", 0, 4) !== \"psbt\" || buffer[4] !== 0xff) {\n throw new Error(\"Invalid original PSBT header\");\n }\n\n let offset = 5;\n\n const globalKeyLen = readPsbtVarInt(buffer, offset);\n offset += globalKeyLen.size + globalKeyLen.value;\n\n const globalValueLen = readPsbtVarInt(buffer, offset);\n offset += globalValueLen.size + globalValueLen.value;\n\n if (offset >= buffer.length || buffer[offset] !== 0x00) {\n throw new Error(\"Invalid original PSBT global section\");\n }\n\n return offset + 1;\n}\n\nfunction readPsbtVarInt(buffer: Buffer, offset: number) {\n if (offset >= buffer.length) {\n throw new Error(\"Format Error: Unexpected End of PSBT\");\n }\n\n const first = buffer[offset];\n if (first < 0xfd) {\n return { value: first, size: 1 };\n }\n if (first === 0xfd) {\n if (offset + 2 >= buffer.length) {\n throw new Error(\"Format Error: Unexpected End of PSBT\");\n }\n return { value: buffer.readUInt16LE(offset + 1), size: 3 };\n }\n if (first === 0xfe) {\n if (offset + 4 >= buffer.length) {\n throw new Error(\"Format Error: Unexpected End of PSBT\");\n }\n return { value: buffer.readUInt32LE(offset + 1), size: 5 };\n }\n throw new Error(\"PSBT values larger than 32 bits are not supported\");\n}\n\nfunction finalizeLegacyP2pkhInputs(psbt: bitcoin.Psbt) {\n for (let index = 0; index < psbt.inputCount; index += 1) {\n const input = psbt.data.inputs[index];\n if (input.finalScriptSig || input.finalScriptWitness) {\n continue;\n }\n\n const partialSig = input.partialSig?.[0];\n const nonWitnessUtxo = input.nonWitnessUtxo;\n const txInput = psbt.txInputs[index];\n\n if (!partialSig || !nonWitnessUtxo || !txInput) {\n throw new Error(`Missing data to finalize input #${index}`);\n }\n\n const prevTx = bitcoin.Transaction.fromBuffer(nonWitnessUtxo);\n const prevOut = prevTx.outs[txInput.index];\n if (!prevOut) {\n throw new Error(`Missing prevout to finalize input #${index}`);\n }\n\n const chunks = bitcoin.script.decompile(prevOut.script);\n const isP2pkh =\n !!chunks &&\n chunks.length === 5 &&\n chunks[0] === bitcoin.opcodes.OP_DUP &&\n chunks[1] === bitcoin.opcodes.OP_HASH160 &&\n Buffer.isBuffer(chunks[2]) &&\n chunks[3] === bitcoin.opcodes.OP_EQUALVERIFY &&\n chunks[4] === bitcoin.opcodes.OP_CHECKSIG;\n\n if (!isP2pkh) {\n throw new Error(`Unsupported script type for input #${index}`);\n }\n\n psbt.finalizeInput(index, () => ({\n finalScriptSig: bitcoin.script.compile([\n partialSig.signature,\n partialSig.pubkey,\n ]),\n finalScriptWitness: undefined,\n }));\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"}
package/dist/index.d.ts CHANGED
@@ -38,6 +38,20 @@ export interface IBuildPSBTOptions {
38
38
  /** Fee rate in satoshis per byte (default: 1024) */
39
39
  feeRate?: number;
40
40
  }
41
+ export interface IPSBTInputMetadata {
42
+ txid: string;
43
+ vout: number;
44
+ sequence?: number;
45
+ rawTxHex: string;
46
+ pubkey: string;
47
+ masterFingerprint: string;
48
+ derivationPath: string;
49
+ }
50
+ export interface IBuildPSBTFromRawOptions {
51
+ network: NetworkType;
52
+ rawUnsignedTransaction: string;
53
+ inputs: IPSBTInputMetadata[];
54
+ }
41
55
  export interface IDeviceInfo {
42
56
  status: string;
43
57
  device: string;
@@ -134,29 +148,17 @@ export const neuraiLegacyTestnet: Network;
134
148
  * Get the bitcoinjs-lib Network object for a given Neurai network type.
135
149
  */
136
150
  export function getNetwork(network: NetworkType): Network;
137
- /**
138
- * Build an unsigned PSBT for Neurai P2PKH, ready to send to the ESP32.
139
- *
140
- * @returns Base64-encoded PSBT string
141
- */
142
151
  export function buildPSBT(options: IBuildPSBTOptions): string;
143
- /**
144
- * Finalize a signed PSBT and extract the raw transaction.
145
- *
146
- * Call this after receiving the signed PSBT back from the ESP32.
147
- *
148
- * @param signedPsbtBase64 - Base64-encoded signed PSBT from the device
149
- * @param network - Network type
150
- * @returns Object with txHex (raw tx for broadcast) and txId
151
- */
152
- export function finalizePSBT(signedPsbtBase64: string, network: "xna" | "xna-test" | "xna-legacy" | "xna-legacy-test"): {
152
+ export function buildPSBTFromRawTransaction(options: IBuildPSBTFromRawOptions): string;
153
+ export function finalizePSBT(signedPsbtBase64: string, network: NetworkType): {
153
154
  txHex: string;
154
155
  txId: string;
155
156
  };
156
- /**
157
- * Validate that a PSBT base64 string is parseable.
158
- */
159
- export function validatePSBT(psbtBase64: string, network: "xna" | "xna-test" | "xna-legacy" | "xna-legacy-test"): boolean;
157
+ export function finalizeSignedPSBT(originalPsbtBase64: string, signedPsbtBase64: string, network: NetworkType): {
158
+ txHex: string;
159
+ txId: string;
160
+ };
161
+ export function validatePSBT(psbtBase64: string, network: NetworkType): boolean;
160
162
  export class NeuraiESP32 {
161
163
  constructor(options?: ISerialOptions);
162
164
  /**
@@ -1 +1 @@
1
- {"mappings":";AAAA;;GAEG;AAIH;IACE,qBAAqB;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,sCAAsC;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,uBAAuB;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,wBAAwB;IACxB,QAAQ,EAAE,MAAM,CAAC;IACjB,mEAAmE;IACnE,QAAQ,EAAE,MAAM,CAAC;CAClB;AAID;IACE,0BAA0B;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,wBAAwB;IACxB,KAAK,EAAE,MAAM,CAAC;CACf;AAID;IACE,qEAAqE;IACrE,OAAO,EAAE,WAAW,CAAC;IACrB,qBAAqB;IACrB,KAAK,EAAE,KAAK,EAAE,CAAC;IACf,6CAA6C;IAC7C,OAAO,EAAE,SAAS,EAAE,CAAC;IACrB,sCAAsC;IACtC,aAAa,EAAE,MAAM,CAAC;IACtB,8CAA8C;IAC9C,MAAM,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,iBAAiB,EAAE,MAAM,CAAC;IAC1B,uDAAuD;IACvD,cAAc,EAAE,MAAM,CAAC;IACvB,oDAAoD;IACpD,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAID;IACE,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CAAC;IAChB,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IA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AI,CAAC;IAI9B;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAOjC;;;OAGG;IACG,OAAO,IAAI,OAAO,CAAC,WAAW,CAAC;IAWrC;;;OAGG;IACG,UAAU,IAAI,OAAO,CAAC,gBAAgB,CAAC;IAU7C;;;OAGG;IACG,cAAc,IAAI,OAAO,CAAC,oBAAoB,CAAC;IAUrD;;;;;OAKG;IACG,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAY9D;;;;;;;;;;;;;;;;;OAiBG;IACG,eAAe,CAAC,OAAO,EAAE;QAC7B,OAAO,CAAC,EAAE,WAAW,CAAC;QACtB,KAAK,EAAE,KAAK,EAAE,CAAC;QACf,OAAO,EAAE,SAAS,EAAE,CAAC;QACrB,aAAa,EAAE,MAAM,CAAC;QACtB,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,iBAAiB,CAAC,EAAE,MAAM,CAAC;QAC3B,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,GAAG,OAAO,CAAC,WAAW,CAAC;CAoFzB","sources":["src/src/types.ts","src/src/serial.ts","src/src/networks.ts","src/src/psbt.ts","src/src/NeuraiESP32.ts","src/src/index.ts","src/index.ts"],"sourcesContent":[null,null,null,null,null,null,"/**\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"],"names":[],"version":3,"file":"index.d.ts.map"}
1
+ {"mappings":";AAAA;;GAEG;AAIH;IACE,qBAAqB;IACrB,IAAI,EAAE,MAAM,CAAC;IACb,sCAAsC;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,uBAAuB;IACvB,YAAY,EAAE,MAAM,CAAC;IACrB,wBAAwB;IACxB,QAAQ,EAAE,MAAM,CAAC;IACjB,mEAAmE;IACnE,QAAQ,EAAE,MAAM,CAAC;CAClB;AAID;IACE,0BAA0B;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,wBAAwB;IACxB,KAAK,EAAE,MAAM,CAAC;CACf;AAID;IACE,qEAAqE;IACrE,OAAO,EAAE,WAAW,CAAC;IACrB,qBAAqB;IACrB,KAAK,EAAE,KAAK,EAAE,CAAC;IACf,6CAA6C;IAC7C,OAAO,EAAE,SAAS,EAAE,CAAC;IACrB,sCAAsC;IACtC,aAAa,EAAE,MAAM,CAAC;IACtB,8CAA8C;IAC9C,MAAM,EAAE,MAAM,CAAC;IACf,gDAAgD;IAChD,iBAAiB,EAAE,MAAM,CAAC;IAC1B,uDAAuD;IACvD,cAAc,EAAE,MAAM,CAAC;IACvB,oDAAoD;IACpD,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;IACE,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,QAAQ,EAAE,MAAM,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;IACf,iBAAiB,EAAE,MAAM,CAAC;IAC1B,cAAc,EAAE,MAAM,CAAC;CACxB;AAED;IACE,OAAO,EAAE,WAAW,CAAC;IACrB,sBAAsB,EAAE,MAAM,CAAC;IAC/B,MAAM,EAAE,kBAAkB,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EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,GAAG,OAAO,CAO9E;ACtLD;gBAIc,OAAO,CAAC,EAAE,cAAc;IAIpC;;OAEG;IACH,MAAM,CAAC,WAAW,IAAI,OAAO;IAI7B;;OAEG;IACH,IAAI,SAAS,IAAI,OAAO,CAEvB;IAED;;OAEG;IACH,IAAI,IAAI,IAAI,WAAW,GAAG,IAAI,CAE7B;IAID;;;OAGG;IACG,OAAO,IAAI,OAAO,CAAC,IAAI,CAAC;IAI9B;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAOjC;;;OAGG;IACG,OAAO,IAAI,OAAO,CAAC,WAAW,CAAC;IAWrC;;;OAGG;IACG,UAAU,IAAI,OAAO,CAAC,gBAAgB,CAAC;IAU7C;;;OAGG;IACG,cAAc,IAAI,OAAO,CAAC,oBAAoB,CAAC;IAUrD;;;;;OAKG;IACG,QAAQ,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAY9D;;;;;;;;;;;;;;;;;OAiBG;IACG,eAAe,CAAC,OAAO,EAAE;QAC7B,OAAO,CAAC,EAAE,WAAW,CAAC;QACtB,KAAK,EAAE,KAAK,EAAE,CAAC;QACf,OAAO,EAAE,SAAS,EAAE,CAAC;QACrB,aAAa,EAAE,MAAM,CAAC;QACtB,MAAM,CAAC,EAAE,MAAM,CAAC;QAChB,iBAAiB,CAAC,EAAE,MAAM,CAAC;QAC3B,cAAc,CAAC,EAAE,MAAM,CAAC;QACxB,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,GAAG,OAAO,CAAC,WAAW,CAAC;CAwFzB","sources":["src/src/types.ts","src/src/serial.ts","src/src/networks.ts","src/src/psbt.ts","src/src/NeuraiESP32.ts","src/src/index.ts","src/index.ts"],"sourcesContent":[null,null,null,null,null,null,"/**\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 {\n buildPSBT,\n buildPSBTFromRawTransaction,\n finalizePSBT,\n finalizeSignedPSBT,\n validatePSBT,\n} 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 IBuildPSBTFromRawOptions,\n IPSBTInputMetadata,\n IDeviceInfo,\n IAddressResponse,\n IBip32PubkeyResponse,\n ISignPsbtResponse,\n IErrorResponse,\n ISerialOptions,\n ISignResult,\n NetworkType,\n} from \"./types.js\";\n"],"names":[],"version":3,"file":"index.d.ts.map"}
package/dist/index.mjs CHANGED
@@ -1,6 +1,5 @@
1
- import {Psbt as $hgUW1$Psbt} from "bitcoinjs-lib";
2
- import {ECPairFactory as $hgUW1$ECPairFactory} from "ecpair";
3
- import $hgUW1$bitcoinerlabsecp256k1 from "@bitcoinerlab/secp256k1";
1
+ import {Buffer as $hgUW1$Buffer} from "buffer";
2
+ import {Psbt as $hgUW1$Psbt, Transaction as $hgUW1$Transaction, script as $hgUW1$script, opcodes as $hgUW1$opcodes} from "bitcoinjs-lib";
4
3
 
5
4
  /**
6
5
  * @neuraiproject/neurai-sign-esp32
@@ -87,7 +86,12 @@ class $f1b85200f32d8427$export$f93edba7156cc57b {
87
86
  filters: this.filters
88
87
  });
89
88
  await this.port.open({
90
- baudRate: this.baudRate
89
+ baudRate: this.baudRate,
90
+ dataBits: 8,
91
+ stopBits: 1,
92
+ parity: "none",
93
+ flowControl: "none",
94
+ bufferSize: 8192
91
95
  });
92
96
  // Set up readable stream (text decoding)
93
97
  const decoder = new TextDecoderStream();
@@ -100,6 +104,9 @@ class $f1b85200f32d8427$export$f93edba7156cc57b {
100
104
  // Start background read loop
101
105
  this.isReading = true;
102
106
  this.readLoop();
107
+ // Give the ESP32 CDC port time to settle after connect/re-enumeration.
108
+ await this.delay(1200);
109
+ this.responseQueue = [];
103
110
  }
104
111
  /**
105
112
  * Close the serial connection.
@@ -140,6 +147,7 @@ class $f1b85200f32d8427$export$f93edba7156cc57b {
140
147
  // The ESP32 CDC serial buffer can lose data if sent too fast in one write.
141
148
  const json = JSON.stringify(command);
142
149
  await this.writeChunked(json);
150
+ await this.writer.ready;
143
151
  await this.writer.write("\n");
144
152
  // Wait for response
145
153
  const response = await this.waitForResponse(timeoutMs);
@@ -154,6 +162,7 @@ class $f1b85200f32d8427$export$f93edba7156cc57b {
154
162
  this.responseQueue = [];
155
163
  const json = JSON.stringify(command);
156
164
  await this.writeChunked(json);
165
+ await this.writer.ready;
157
166
  await this.writer.write("\n");
158
167
  // Wait for a non-processing response
159
168
  const startTime = Date.now();
@@ -213,6 +222,7 @@ class $f1b85200f32d8427$export$f93edba7156cc57b {
213
222
  if (!this.writer) throw new Error("Serial port not connected");
214
223
  for(let offset = 0; offset < data.length; offset += chunkSize){
215
224
  const chunk = data.slice(offset, offset + chunkSize);
225
+ await this.writer.ready;
216
226
  await this.writer.write(chunk);
217
227
  if (offset + chunkSize < data.length) await this.delay(pauseMs);
218
228
  }
@@ -224,21 +234,16 @@ class $f1b85200f32d8427$export$f93edba7156cc57b {
224
234
 
225
235
 
226
236
  /**
227
- * PSBT builder for Neurai P2PKH transactions.
228
- *
229
- * Creates unsigned PSBTs compatible with the NeuraiHW ESP32 firmware.
230
- * The ESP32 signs inputs that match its BIP32 derivation path and
231
- * master fingerprint.
237
+ * PSBT helpers for Neurai P2PKH transactions.
232
238
  *
233
- * Requirements for each UTXO:
234
- * - rawTxHex: Full raw transaction hex (P2PKH needs nonWitnessUtxo)
235
- * - scriptPubKey: The output script being spent
239
+ * This package supports two build paths:
240
+ * - high-level build from UTXOs + outputs + fee estimation
241
+ * - low-level build from an already-created raw unsigned transaction
236
242
  *
237
- * The PSBT includes BIP32 derivation metadata so the ESP32 can
238
- * verify and locate the correct signing key.
243
+ * The second path matches the webwallet integration, where coin selection
244
+ * and fee calculation already happen elsewhere.
239
245
  */
240
246
 
241
-
242
247
  /**
243
248
  * Neurai network configurations for bitcoinjs-lib
244
249
  *
@@ -302,76 +307,48 @@ function $ab66056610f04b01$export$7de4970ebfd8206d(network) {
302
307
  }
303
308
 
304
309
 
305
- const $68e2926fe257f2e4$var$ECPair = (0, $hgUW1$ECPairFactory)((0, $hgUW1$bitcoinerlabsecp256k1));
306
310
  const $68e2926fe257f2e4$var$DEFAULT_FEE_RATE = 1024; // sat/byte
307
- // Estimated P2PKH tx sizes for fee calculation
308
- const $68e2926fe257f2e4$var$TX_OVERHEAD = 10; // version(4) + locktime(4) + varint(2)
309
- const $68e2926fe257f2e4$var$INPUT_SIZE = 148; // P2PKH input with signature
310
- const $68e2926fe257f2e4$var$OUTPUT_SIZE = 34; // P2PKH output
311
- /**
312
- * Estimate transaction size in bytes for P2PKH.
313
- */ function $68e2926fe257f2e4$var$estimateTxSize(inputCount, outputCount) {
311
+ const $68e2926fe257f2e4$var$TX_OVERHEAD = 10;
312
+ const $68e2926fe257f2e4$var$INPUT_SIZE = 148;
313
+ const $68e2926fe257f2e4$var$OUTPUT_SIZE = 34;
314
+ function $68e2926fe257f2e4$var$estimateTxSize(inputCount, outputCount) {
314
315
  return $68e2926fe257f2e4$var$TX_OVERHEAD + inputCount * $68e2926fe257f2e4$var$INPUT_SIZE + outputCount * $68e2926fe257f2e4$var$OUTPUT_SIZE;
315
316
  }
316
- /**
317
- * Parse a master fingerprint hex string (8 chars) into a 4-byte Buffer.
318
- */ function $68e2926fe257f2e4$var$parseMasterFingerprint(hex) {
317
+ function $68e2926fe257f2e4$var$parseMasterFingerprint(hex) {
319
318
  if (hex.length !== 8) throw new Error(`Invalid master fingerprint: expected 8 hex chars, got ${hex.length}`);
320
- return Buffer.from(hex, "hex");
321
- }
322
- /**
323
- * Parse a BIP44 derivation path string into an array of uint32 indices.
324
- * e.g. "m/44'/1900'/0'/0/0" → [0x8000002C, 0x8000076C, 0x80000000, 0, 0]
325
- */ function $68e2926fe257f2e4$var$parseDerivationPath(path) {
326
- return path.replace(/^m\//, "").split("/").map((part)=>{
327
- const hardened = part.endsWith("'");
328
- const index = parseInt(hardened ? part.slice(0, -1) : part, 10);
329
- return hardened ? index + 0x80000000 : index;
330
- });
319
+ return (0, $hgUW1$Buffer).from(hex, "hex");
331
320
  }
332
321
  function $68e2926fe257f2e4$export$236ea1e009011592(options) {
333
- const { network: networkType, utxos: utxos, outputs: outputs, changeAddress: changeAddress, pubkey: pubkey, masterFingerprint: masterFingerprint, derivationPath: derivationPath, feeRate: feeRate = $68e2926fe257f2e4$var$DEFAULT_FEE_RATE } = options;
322
+ const { network: network, utxos: utxos, outputs: outputs, changeAddress: changeAddress, pubkey: pubkey, masterFingerprint: masterFingerprint, derivationPath: derivationPath, feeRate: feeRate = $68e2926fe257f2e4$var$DEFAULT_FEE_RATE } = options;
334
323
  if (utxos.length === 0) throw new Error("No UTXOs provided");
335
324
  if (outputs.length === 0) throw new Error("No outputs provided");
336
- const network = (0, $ab66056610f04b01$export$7de4970ebfd8206d)(networkType);
337
- const pubkeyBuffer = Buffer.from(pubkey, "hex");
338
- const fingerprintBuffer = $68e2926fe257f2e4$var$parseMasterFingerprint(masterFingerprint);
339
- const bip32Path = $68e2926fe257f2e4$var$parseDerivationPath(derivationPath);
340
- // Calculate total output amount
341
- const totalOutputValue = outputs.reduce((sum, o)=>sum + o.value, 0);
342
- // Select UTXOs (use all provided — caller is responsible for UTXO selection)
343
- const totalInputValue = utxos.reduce((sum, u)=>sum + u.satoshis, 0);
344
- // Estimate fee: outputs + possible change output
325
+ const totalOutputValue = outputs.reduce((sum, output)=>sum + output.value, 0);
326
+ const totalInputValue = utxos.reduce((sum, utxo)=>sum + utxo.satoshis, 0);
345
327
  const estimatedSize = $68e2926fe257f2e4$var$estimateTxSize(utxos.length, outputs.length + 1);
346
328
  const fee = estimatedSize * feeRate;
347
329
  const change = totalInputValue - totalOutputValue - fee;
348
330
  if (change < 0) throw new Error(`Insufficient funds: inputs=${totalInputValue}, outputs=${totalOutputValue}, fee=${fee}`);
349
- // Build PSBT
350
331
  const psbt = new $hgUW1$Psbt({
351
- network: network
332
+ network: (0, $ab66056610f04b01$export$7de4970ebfd8206d)(network)
352
333
  });
353
- // BIP32 derivation metadata (same for all inputs from this device)
354
334
  const bip32Derivation = [
355
335
  {
356
- masterFingerprint: fingerprintBuffer,
336
+ masterFingerprint: $68e2926fe257f2e4$var$parseMasterFingerprint(masterFingerprint),
357
337
  path: derivationPath,
358
- pubkey: pubkeyBuffer
338
+ pubkey: (0, $hgUW1$Buffer).from(pubkey, "hex")
359
339
  }
360
340
  ];
361
- // Add inputs
362
341
  for (const utxo of utxos)psbt.addInput({
363
342
  hash: utxo.txid,
364
343
  index: utxo.vout,
365
- nonWitnessUtxo: Buffer.from(utxo.rawTxHex, "hex"),
344
+ nonWitnessUtxo: (0, $hgUW1$Buffer).from(utxo.rawTxHex, "hex"),
366
345
  bip32Derivation: bip32Derivation
367
346
  });
368
- // Add destination outputs
369
347
  for (const output of outputs)psbt.addOutput({
370
348
  address: output.address,
371
349
  value: BigInt(output.value)
372
350
  });
373
- // Add change output (if change > dust threshold)
374
- const DUST_THRESHOLD = 546; // standard dust for P2PKH
351
+ const DUST_THRESHOLD = 546;
375
352
  if (change >= DUST_THRESHOLD) psbt.addOutput({
376
353
  address: changeAddress,
377
354
  value: BigInt(change),
@@ -379,10 +356,41 @@ function $68e2926fe257f2e4$export$236ea1e009011592(options) {
379
356
  });
380
357
  return psbt.toBase64();
381
358
  }
359
+ function $68e2926fe257f2e4$export$e0e3d6f226ea0b0a(options) {
360
+ const network = (0, $ab66056610f04b01$export$7de4970ebfd8206d)(options.network);
361
+ const tx = $hgUW1$Transaction.fromHex(options.rawUnsignedTransaction);
362
+ const psbt = new $hgUW1$Psbt({
363
+ network: network
364
+ });
365
+ psbt.setVersion(tx.version);
366
+ psbt.setLocktime(tx.locktime);
367
+ for(let index = 0; index < tx.ins.length; index += 1){
368
+ const input = tx.ins[index];
369
+ const metadata = options.inputs[index];
370
+ if (!metadata) throw new Error(`Missing input metadata for input #${index}`);
371
+ psbt.addInput({
372
+ hash: metadata.txid,
373
+ index: metadata.vout,
374
+ sequence: metadata.sequence ?? input.sequence,
375
+ nonWitnessUtxo: (0, $hgUW1$Buffer).from(metadata.rawTxHex, "hex"),
376
+ bip32Derivation: [
377
+ {
378
+ masterFingerprint: $68e2926fe257f2e4$var$parseMasterFingerprint(metadata.masterFingerprint),
379
+ path: metadata.derivationPath,
380
+ pubkey: (0, $hgUW1$Buffer).from(metadata.pubkey, "hex")
381
+ }
382
+ ]
383
+ });
384
+ }
385
+ for (const output of tx.outs)psbt.addOutput({
386
+ script: (0, $hgUW1$Buffer).from(output.script),
387
+ value: output.value
388
+ });
389
+ return psbt.toBase64();
390
+ }
382
391
  function $68e2926fe257f2e4$export$ce839c4c9bcf7b77(signedPsbtBase64, network) {
383
- const net = (0, $ab66056610f04b01$export$7de4970ebfd8206d)(network);
384
392
  const psbt = $hgUW1$Psbt.fromBase64(signedPsbtBase64, {
385
- network: net
393
+ network: (0, $ab66056610f04b01$export$7de4970ebfd8206d)(network)
386
394
  });
387
395
  psbt.finalizeAllInputs();
388
396
  const tx = psbt.extractTransaction();
@@ -391,17 +399,132 @@ function $68e2926fe257f2e4$export$ce839c4c9bcf7b77(signedPsbtBase64, network) {
391
399
  txId: tx.getId()
392
400
  };
393
401
  }
402
+ function $68e2926fe257f2e4$export$3a31c64c43aacd3(originalPsbtBase64, signedPsbtBase64, network) {
403
+ const net = (0, $ab66056610f04b01$export$7de4970ebfd8206d)(network);
404
+ const psbt = $hgUW1$Psbt.fromBase64(originalPsbtBase64, {
405
+ network: net
406
+ });
407
+ let mergedWithStandardPsbt = false;
408
+ try {
409
+ const signedPsbt = $hgUW1$Psbt.fromBase64(signedPsbtBase64, {
410
+ network: net
411
+ });
412
+ psbt.combine(signedPsbt);
413
+ mergedWithStandardPsbt = true;
414
+ } catch {
415
+ // uNeurai can return a minimal signed PSBT that bitcoinjs-lib cannot fully parse.
416
+ }
417
+ if (!mergedWithStandardPsbt) {
418
+ const partialSigsByInput = $68e2926fe257f2e4$var$extractPartialSigsFromUNeuraiPsbt(originalPsbtBase64, signedPsbtBase64, psbt.inputCount);
419
+ partialSigsByInput.forEach((partialSig, index)=>{
420
+ if (partialSig.length === 0) return;
421
+ psbt.updateInput(index, {
422
+ partialSig: partialSig
423
+ });
424
+ });
425
+ }
426
+ try {
427
+ psbt.finalizeAllInputs();
428
+ } catch {
429
+ $68e2926fe257f2e4$var$finalizeLegacyP2pkhInputs(psbt);
430
+ }
431
+ const tx = psbt.extractTransaction(true);
432
+ return {
433
+ txHex: tx.toHex(),
434
+ txId: tx.getId()
435
+ };
436
+ }
394
437
  function $68e2926fe257f2e4$export$78a5723c75e7be9(psbtBase64, network) {
395
438
  try {
396
- const net = (0, $ab66056610f04b01$export$7de4970ebfd8206d)(network);
397
439
  $hgUW1$Psbt.fromBase64(psbtBase64, {
398
- network: net
440
+ network: (0, $ab66056610f04b01$export$7de4970ebfd8206d)(network)
399
441
  });
400
442
  return true;
401
443
  } catch {
402
444
  return false;
403
445
  }
404
446
  }
447
+ function $68e2926fe257f2e4$var$extractPartialSigsFromUNeuraiPsbt(originalBase64, signedBase64, inputCount) {
448
+ const originalBuffer = (0, $hgUW1$Buffer).from(originalBase64, "base64");
449
+ const buffer = (0, $hgUW1$Buffer).from(signedBase64, "base64");
450
+ const partialSigsByInput = Array.from({
451
+ length: inputCount
452
+ }, ()=>[]);
453
+ if (buffer.length < 5 || buffer.toString("ascii", 0, 4) !== "psbt" || buffer[4] !== 0xff) throw new Error("NeuraiHW returned an invalid PSBT header");
454
+ let offset = $68e2926fe257f2e4$var$getFirstInputSectionOffset(originalBuffer);
455
+ for(let inputIndex = 0; inputIndex < inputCount; inputIndex += 1)while(offset < buffer.length){
456
+ const keyLen = $68e2926fe257f2e4$var$readPsbtVarInt(buffer, offset);
457
+ offset += keyLen.size;
458
+ if (keyLen.value === 0) break;
459
+ const key = buffer.subarray(offset, offset + keyLen.value);
460
+ offset += keyLen.value;
461
+ const valueLen = $68e2926fe257f2e4$var$readPsbtVarInt(buffer, offset);
462
+ offset += valueLen.size;
463
+ const value = buffer.subarray(offset, offset + valueLen.value);
464
+ offset += valueLen.value;
465
+ if (key.length > 1 && key[0] === 0x02) partialSigsByInput[inputIndex].push({
466
+ pubkey: (0, $hgUW1$Buffer).from(key.subarray(1)),
467
+ signature: (0, $hgUW1$Buffer).from(value)
468
+ });
469
+ }
470
+ return partialSigsByInput;
471
+ }
472
+ function $68e2926fe257f2e4$var$getFirstInputSectionOffset(buffer) {
473
+ if (buffer.length < 5 || buffer.toString("ascii", 0, 4) !== "psbt" || buffer[4] !== 0xff) throw new Error("Invalid original PSBT header");
474
+ let offset = 5;
475
+ const globalKeyLen = $68e2926fe257f2e4$var$readPsbtVarInt(buffer, offset);
476
+ offset += globalKeyLen.size + globalKeyLen.value;
477
+ const globalValueLen = $68e2926fe257f2e4$var$readPsbtVarInt(buffer, offset);
478
+ offset += globalValueLen.size + globalValueLen.value;
479
+ if (offset >= buffer.length || buffer[offset] !== 0x00) throw new Error("Invalid original PSBT global section");
480
+ return offset + 1;
481
+ }
482
+ function $68e2926fe257f2e4$var$readPsbtVarInt(buffer, offset) {
483
+ if (offset >= buffer.length) throw new Error("Format Error: Unexpected End of PSBT");
484
+ const first = buffer[offset];
485
+ if (first < 0xfd) return {
486
+ value: first,
487
+ size: 1
488
+ };
489
+ if (first === 0xfd) {
490
+ if (offset + 2 >= buffer.length) throw new Error("Format Error: Unexpected End of PSBT");
491
+ return {
492
+ value: buffer.readUInt16LE(offset + 1),
493
+ size: 3
494
+ };
495
+ }
496
+ if (first === 0xfe) {
497
+ if (offset + 4 >= buffer.length) throw new Error("Format Error: Unexpected End of PSBT");
498
+ return {
499
+ value: buffer.readUInt32LE(offset + 1),
500
+ size: 5
501
+ };
502
+ }
503
+ throw new Error("PSBT values larger than 32 bits are not supported");
504
+ }
505
+ function $68e2926fe257f2e4$var$finalizeLegacyP2pkhInputs(psbt) {
506
+ for(let index = 0; index < psbt.inputCount; index += 1){
507
+ const input = psbt.data.inputs[index];
508
+ if (input.finalScriptSig || input.finalScriptWitness) continue;
509
+ const partialSig = input.partialSig?.[0];
510
+ const nonWitnessUtxo = input.nonWitnessUtxo;
511
+ const txInput = psbt.txInputs[index];
512
+ if (!partialSig || !nonWitnessUtxo || !txInput) throw new Error(`Missing data to finalize input #${index}`);
513
+ const prevTx = $hgUW1$Transaction.fromBuffer(nonWitnessUtxo);
514
+ const prevOut = prevTx.outs[txInput.index];
515
+ if (!prevOut) throw new Error(`Missing prevout to finalize input #${index}`);
516
+ const chunks = $hgUW1$script.decompile(prevOut.script);
517
+ const isP2pkh = !!chunks && chunks.length === 5 && chunks[0] === $hgUW1$opcodes.OP_DUP && chunks[1] === $hgUW1$opcodes.OP_HASH160 && (0, $hgUW1$Buffer).isBuffer(chunks[2]) && chunks[3] === $hgUW1$opcodes.OP_EQUALVERIFY && chunks[4] === $hgUW1$opcodes.OP_CHECKSIG;
518
+ if (!isP2pkh) throw new Error(`Unsupported script type for input #${index}`);
519
+ psbt.finalizeInput(index, ()=>({
520
+ finalScriptSig: $hgUW1$script.compile([
521
+ partialSig.signature,
522
+ partialSig.pubkey
523
+ ]),
524
+ finalScriptWitness: undefined
525
+ }));
526
+ }
527
+ }
405
528
 
406
529
 
407
530
  class $a6c8409f4f68b3eb$export$fa10ee8b91a777b7 {
@@ -524,7 +647,7 @@ class $a6c8409f4f68b3eb$export$fa10ee8b91a777b7 {
524
647
  // 2. Send to ESP32 for signing
525
648
  const signResponse = await this.signPsbt(psbtBase64);
526
649
  // 3. Finalize and extract raw transaction
527
- const { txHex: txHex, txId: txId } = (0, $68e2926fe257f2e4$export$ce839c4c9bcf7b77)(signResponse.psbt, network);
650
+ const { txHex: txHex, txId: txId } = (0, $68e2926fe257f2e4$export$3a31c64c43aacd3)(psbtBase64, signResponse.psbt, network);
528
651
  return {
529
652
  signedPsbtBase64: signResponse.psbt,
530
653
  txHex: txHex,
@@ -554,5 +677,5 @@ class $a6c8409f4f68b3eb$export$fa10ee8b91a777b7 {
554
677
 
555
678
 
556
679
 
557
- export {$a6c8409f4f68b3eb$export$fa10ee8b91a777b7 as NeuraiESP32, $68e2926fe257f2e4$export$236ea1e009011592 as buildPSBT, $68e2926fe257f2e4$export$ce839c4c9bcf7b77 as finalizePSBT, $68e2926fe257f2e4$export$78a5723c75e7be9 as validatePSBT, $f1b85200f32d8427$export$f93edba7156cc57b as SerialConnection, $ab66056610f04b01$export$7de4970ebfd8206d as getNetwork, $ab66056610f04b01$export$6b5a4442fe3d94ae as neuraiMainnet, $ab66056610f04b01$export$7eb3dea33add35cf as neuraiTestnet, $ab66056610f04b01$export$688657d38fcd7269 as neuraiLegacyMainnet, $ab66056610f04b01$export$68e8f8241c8185fe as neuraiLegacyTestnet};
680
+ export {$a6c8409f4f68b3eb$export$fa10ee8b91a777b7 as NeuraiESP32, $68e2926fe257f2e4$export$236ea1e009011592 as buildPSBT, $68e2926fe257f2e4$export$e0e3d6f226ea0b0a as buildPSBTFromRawTransaction, $68e2926fe257f2e4$export$ce839c4c9bcf7b77 as finalizePSBT, $68e2926fe257f2e4$export$3a31c64c43aacd3 as finalizeSignedPSBT, $68e2926fe257f2e4$export$78a5723c75e7be9 as validatePSBT, $f1b85200f32d8427$export$f93edba7156cc57b as SerialConnection, $ab66056610f04b01$export$7de4970ebfd8206d as getNetwork, $ab66056610f04b01$export$6b5a4442fe3d94ae as neuraiMainnet, $ab66056610f04b01$export$7eb3dea33add35cf as neuraiTestnet, $ab66056610f04b01$export$688657d38fcd7269 as neuraiLegacyMainnet, $ab66056610f04b01$export$68e8f8241c8185fe as neuraiLegacyTestnet};
558
681
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
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B;QACzB,MAAM,aAAa,CAAA,GAAA,yCAAQ,EAAE;qBAC3B;YACA,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.mjs.map"}
1
+ {"mappings":";;;AAAA;;;;;CAKC,GAED,aAAa;ACPb;;;;;;;;;;;;;;;;;;ACAA;;;;;CAKC,GAID,wCAAwC;AACxC,MAAM,wCAAsC;IAC1C;QAAE,aAAa;QAAQ,cAAc;IAAO;IAC5C;QAAE,aAAa;IAAO;IACtB;QAAE,aAAa;QA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S,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 {\n buildPSBT,\n buildPSBTFromRawTransaction,\n finalizePSBT,\n finalizeSignedPSBT,\n validatePSBT,\n} 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 IBuildPSBTFromRawOptions,\n IPSBTInputMetadata,\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, finalizeSignedPSBT } 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 } = finalizeSignedPSBT(\n psbtBase64,\n signResponse.psbt,\n network\n );\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({\n baudRate: this.baudRate,\n dataBits: 8,\n stopBits: 1,\n parity: \"none\",\n flowControl: \"none\",\n bufferSize: 8192,\n });\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 void this.readLoop();\n\n // Give the ESP32 CDC port time to settle after connect/re-enumeration.\n await this.delay(1200);\n this.responseQueue = [];\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.ready;\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.ready;\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.ready;\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 helpers for Neurai P2PKH transactions.\n *\n * This package supports two build paths:\n * - high-level build from UTXOs + outputs + fee estimation\n * - low-level build from an already-created raw unsigned transaction\n *\n * The second path matches the webwallet integration, where coin selection\n * and fee calculation already happen elsewhere.\n */\n\nimport { Buffer } from \"buffer\";\nimport * as bitcoin from \"bitcoinjs-lib\";\nimport { getNetwork } from \"./networks.js\";\nimport type {\n IBuildPSBTFromRawOptions,\n IBuildPSBTOptions,\n IPSBTInputMetadata,\n NetworkType,\n} from \"./types.js\";\n\nconst DEFAULT_FEE_RATE = 1024; // sat/byte\n\nconst TX_OVERHEAD = 10;\nconst INPUT_SIZE = 148;\nconst OUTPUT_SIZE = 34;\n\nfunction estimateTxSize(inputCount: number, outputCount: number): number {\n return TX_OVERHEAD + inputCount * INPUT_SIZE + outputCount * OUTPUT_SIZE;\n}\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\nexport function buildPSBT(options: IBuildPSBTOptions): string {\n const {\n network,\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 totalOutputValue = outputs.reduce((sum, output) => sum + output.value, 0);\n const totalInputValue = utxos.reduce((sum, utxo) => sum + utxo.satoshis, 0);\n const estimatedSize = estimateTxSize(utxos.length, outputs.length + 1);\n const fee = estimatedSize * feeRate;\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 const psbt = new bitcoin.Psbt({ network: getNetwork(network) });\n const bip32Derivation = [\n {\n masterFingerprint: parseMasterFingerprint(masterFingerprint),\n path: derivationPath,\n pubkey: Buffer.from(pubkey, \"hex\"),\n },\n ];\n\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 for (const output of outputs) {\n psbt.addOutput({\n address: output.address,\n value: BigInt(output.value),\n });\n }\n\n const DUST_THRESHOLD = 546;\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\nexport function buildPSBTFromRawTransaction(options: IBuildPSBTFromRawOptions): string {\n const network = getNetwork(options.network);\n const tx = bitcoin.Transaction.fromHex(options.rawUnsignedTransaction);\n const psbt = new bitcoin.Psbt({ network });\n\n psbt.setVersion(tx.version);\n psbt.setLocktime(tx.locktime);\n\n for (let index = 0; index < tx.ins.length; index += 1) {\n const input = tx.ins[index];\n const metadata = options.inputs[index];\n\n if (!metadata) {\n throw new Error(`Missing input metadata for input #${index}`);\n }\n\n psbt.addInput({\n hash: metadata.txid,\n index: metadata.vout,\n sequence: metadata.sequence ?? input.sequence,\n nonWitnessUtxo: Buffer.from(metadata.rawTxHex, \"hex\"),\n bip32Derivation: [\n {\n masterFingerprint: parseMasterFingerprint(metadata.masterFingerprint),\n path: metadata.derivationPath,\n pubkey: Buffer.from(metadata.pubkey, \"hex\"),\n },\n ],\n });\n }\n\n for (const output of tx.outs) {\n psbt.addOutput({\n script: Buffer.from(output.script),\n value: output.value,\n });\n }\n\n return psbt.toBase64();\n}\n\nexport function finalizePSBT(\n signedPsbtBase64: string,\n network: NetworkType\n): { txHex: string; txId: string } {\n const psbt = bitcoin.Psbt.fromBase64(signedPsbtBase64, {\n network: getNetwork(network),\n });\n\n psbt.finalizeAllInputs();\n\n const tx = psbt.extractTransaction();\n return {\n txHex: tx.toHex(),\n txId: tx.getId(),\n };\n}\n\nexport function finalizeSignedPSBT(\n originalPsbtBase64: string,\n signedPsbtBase64: string,\n network: NetworkType\n): { txHex: string; txId: string } {\n const net = getNetwork(network);\n const psbt = bitcoin.Psbt.fromBase64(originalPsbtBase64, { network: net });\n\n let mergedWithStandardPsbt = false;\n try {\n const signedPsbt = bitcoin.Psbt.fromBase64(signedPsbtBase64, { network: net });\n psbt.combine(signedPsbt);\n mergedWithStandardPsbt = true;\n } catch {\n // uNeurai can return a minimal signed PSBT that bitcoinjs-lib cannot fully parse.\n }\n\n if (!mergedWithStandardPsbt) {\n const partialSigsByInput = extractPartialSigsFromUNeuraiPsbt(\n originalPsbtBase64,\n signedPsbtBase64,\n psbt.inputCount\n );\n\n partialSigsByInput.forEach((partialSig, index) => {\n if (partialSig.length === 0) {\n return;\n }\n psbt.updateInput(index, { partialSig });\n });\n }\n\n try {\n psbt.finalizeAllInputs();\n } catch {\n finalizeLegacyP2pkhInputs(psbt);\n }\n\n const tx = psbt.extractTransaction(true);\n return {\n txHex: tx.toHex(),\n txId: tx.getId(),\n };\n}\n\nexport function validatePSBT(psbtBase64: string, network: NetworkType): boolean {\n try {\n bitcoin.Psbt.fromBase64(psbtBase64, { network: getNetwork(network) });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction extractPartialSigsFromUNeuraiPsbt(\n originalBase64: string,\n signedBase64: string,\n inputCount: number\n) {\n const originalBuffer = Buffer.from(originalBase64, \"base64\");\n const buffer = Buffer.from(signedBase64, \"base64\");\n const partialSigsByInput: { pubkey: Buffer; signature: Buffer }[][] = Array.from(\n { length: inputCount },\n () => []\n );\n\n if (buffer.length < 5 || buffer.toString(\"ascii\", 0, 4) !== \"psbt\" || buffer[4] !== 0xff) {\n throw new Error(\"NeuraiHW returned an invalid PSBT header\");\n }\n\n let offset = getFirstInputSectionOffset(originalBuffer);\n\n for (let inputIndex = 0; inputIndex < inputCount; inputIndex += 1) {\n while (offset < buffer.length) {\n const keyLen = readPsbtVarInt(buffer, offset);\n offset += keyLen.size;\n\n if (keyLen.value === 0) {\n break;\n }\n\n const key = buffer.subarray(offset, offset + keyLen.value);\n offset += keyLen.value;\n\n const valueLen = readPsbtVarInt(buffer, offset);\n offset += valueLen.size;\n const value = buffer.subarray(offset, offset + valueLen.value);\n offset += valueLen.value;\n\n if (key.length > 1 && key[0] === 0x02) {\n partialSigsByInput[inputIndex].push({\n pubkey: Buffer.from(key.subarray(1)),\n signature: Buffer.from(value),\n });\n }\n }\n }\n\n return partialSigsByInput;\n}\n\nfunction getFirstInputSectionOffset(buffer: Buffer) {\n if (buffer.length < 5 || buffer.toString(\"ascii\", 0, 4) !== \"psbt\" || buffer[4] !== 0xff) {\n throw new Error(\"Invalid original PSBT header\");\n }\n\n let offset = 5;\n\n const globalKeyLen = readPsbtVarInt(buffer, offset);\n offset += globalKeyLen.size + globalKeyLen.value;\n\n const globalValueLen = readPsbtVarInt(buffer, offset);\n offset += globalValueLen.size + globalValueLen.value;\n\n if (offset >= buffer.length || buffer[offset] !== 0x00) {\n throw new Error(\"Invalid original PSBT global section\");\n }\n\n return offset + 1;\n}\n\nfunction readPsbtVarInt(buffer: Buffer, offset: number) {\n if (offset >= buffer.length) {\n throw new Error(\"Format Error: Unexpected End of PSBT\");\n }\n\n const first = buffer[offset];\n if (first < 0xfd) {\n return { value: first, size: 1 };\n }\n if (first === 0xfd) {\n if (offset + 2 >= buffer.length) {\n throw new Error(\"Format Error: Unexpected End of PSBT\");\n }\n return { value: buffer.readUInt16LE(offset + 1), size: 3 };\n }\n if (first === 0xfe) {\n if (offset + 4 >= buffer.length) {\n throw new Error(\"Format Error: Unexpected End of PSBT\");\n }\n return { value: buffer.readUInt32LE(offset + 1), size: 5 };\n }\n throw new Error(\"PSBT values larger than 32 bits are not supported\");\n}\n\nfunction finalizeLegacyP2pkhInputs(psbt: bitcoin.Psbt) {\n for (let index = 0; index < psbt.inputCount; index += 1) {\n const input = psbt.data.inputs[index];\n if (input.finalScriptSig || input.finalScriptWitness) {\n continue;\n }\n\n const partialSig = input.partialSig?.[0];\n const nonWitnessUtxo = input.nonWitnessUtxo;\n const txInput = psbt.txInputs[index];\n\n if (!partialSig || !nonWitnessUtxo || !txInput) {\n throw new Error(`Missing data to finalize input #${index}`);\n }\n\n const prevTx = bitcoin.Transaction.fromBuffer(nonWitnessUtxo);\n const prevOut = prevTx.outs[txInput.index];\n if (!prevOut) {\n throw new Error(`Missing prevout to finalize input #${index}`);\n }\n\n const chunks = bitcoin.script.decompile(prevOut.script);\n const isP2pkh =\n !!chunks &&\n chunks.length === 5 &&\n chunks[0] === bitcoin.opcodes.OP_DUP &&\n chunks[1] === bitcoin.opcodes.OP_HASH160 &&\n Buffer.isBuffer(chunks[2]) &&\n chunks[3] === bitcoin.opcodes.OP_EQUALVERIFY &&\n chunks[4] === bitcoin.opcodes.OP_CHECKSIG;\n\n if (!isP2pkh) {\n throw new Error(`Unsupported script type for input #${index}`);\n }\n\n psbt.finalizeInput(index, () => ({\n finalScriptSig: bitcoin.script.compile([\n partialSig.signature,\n partialSig.pubkey,\n ]),\n finalScriptWitness: undefined,\n }));\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.mjs.map"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@neuraiproject/neurai-sign-esp32",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "Create and sign PSBTs for Neurai via ESP32 hardware wallet",
5
5
  "type": "module",
6
6
  "source": "src/index.ts",
@@ -35,6 +35,7 @@
35
35
  "dependencies": {
36
36
  "@bitcoinerlab/secp256k1": "1.2.0",
37
37
  "bitcoinjs-lib": "7.0.1",
38
+ "buffer": "^6.0.3",
38
39
  "ecpair": "3.0.0",
39
40
  "varuint-bitcoin": "2.0.0"
40
41
  },