@neuraiproject/neurai-sign-esp32 0.2.1 → 0.3.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/README.md +77 -3
- package/dist/index.cjs +72 -11
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +49 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +73 -13
- package/dist/index.mjs.map +1 -1
- package/package.json +8 -1
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# neurai-sign-esp32
|
|
2
2
|
|
|
3
|
-
Create and sign Neurai (XNA) transactions via ESP32 hardware wallet.
|
|
3
|
+
Create and sign Neurai (XNA) and asset transactions via ESP32 hardware wallet.
|
|
4
4
|
|
|
5
5
|
This library handles the full PSBT workflow against a NeuraiHW device:
|
|
6
6
|
build an unsigned PSBT, send it over USB Serial for signing, receive
|
|
@@ -14,8 +14,16 @@ PSBT construction and the Web Serial API for device communication.
|
|
|
14
14
|
|
|
15
15
|
EXPERIMENTAL.
|
|
16
16
|
|
|
17
|
-
|
|
18
|
-
|
|
17
|
+
This library supports:
|
|
18
|
+
- XNA transfers
|
|
19
|
+
- Asset transfers
|
|
20
|
+
- BIP32 account discovery via `get_bip32_pubkey`
|
|
21
|
+
- Message signing (prove address ownership)
|
|
22
|
+
|
|
23
|
+
Asset transfers use the same PSBT signing flow as XNA transfers. The transaction
|
|
24
|
+
outputs are still signed from the raw unsigned transaction, while optional
|
|
25
|
+
display metadata can be provided to the device so the firmware can show the
|
|
26
|
+
asset name, transferred amount, destination address, and fee more clearly.
|
|
19
27
|
|
|
20
28
|
## Install
|
|
21
29
|
|
|
@@ -112,6 +120,57 @@ console.log(txHex); // ready for sendrawtransaction
|
|
|
112
120
|
await device.disconnect();
|
|
113
121
|
```
|
|
114
122
|
|
|
123
|
+
### Asset transfer display metadata
|
|
124
|
+
|
|
125
|
+
When signing an asset transfer, you can attach optional display metadata to
|
|
126
|
+
the `sign_psbt` request. This does not affect the signature itself. It only
|
|
127
|
+
helps the ESP32 firmware render a better transaction review screen.
|
|
128
|
+
|
|
129
|
+
```javascript
|
|
130
|
+
import {
|
|
131
|
+
NeuraiESP32,
|
|
132
|
+
buildAssetTransferDisplayMetadata,
|
|
133
|
+
} from "@neuraiproject/neurai-sign-esp32";
|
|
134
|
+
|
|
135
|
+
const device = new NeuraiESP32();
|
|
136
|
+
await device.connect();
|
|
137
|
+
|
|
138
|
+
const display = buildAssetTransferDisplayMetadata({
|
|
139
|
+
assetName: "MY_ASSET",
|
|
140
|
+
assetAmount: 1,
|
|
141
|
+
destinationAddress: "Nxxx...",
|
|
142
|
+
destinationCount: 1,
|
|
143
|
+
changeAddress: "Nchange...",
|
|
144
|
+
changeCount: 1,
|
|
145
|
+
inputAddresses: ["Ninput1...", "Ninput2..."],
|
|
146
|
+
feeAmount: 0.01234567,
|
|
147
|
+
baseCurrency: "XNA",
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
const signed = await device.signPsbt(psbtBase64, display);
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
This metadata is especially useful for asset transfers because a standard PSBT
|
|
154
|
+
does not expose high-level fields such as `assetName` or `assetAmount` in a
|
|
155
|
+
simple, display-ready form.
|
|
156
|
+
|
|
157
|
+
### Sign a message (prove address ownership)
|
|
158
|
+
|
|
159
|
+
```javascript
|
|
160
|
+
const device = new NeuraiESP32();
|
|
161
|
+
await device.connect();
|
|
162
|
+
|
|
163
|
+
// User must press Confirm on device
|
|
164
|
+
const result = await device.signMessage("Hello, I own this address");
|
|
165
|
+
console.log(result.signature); // base64-encoded recoverable signature
|
|
166
|
+
console.log(result.address); // address that signed the message
|
|
167
|
+
console.log(result.message); // the original message
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
The signature uses the standard Bitcoin message signing format with the
|
|
171
|
+
`"Neurai Signed Message:\n"` prefix. It is compatible with
|
|
172
|
+
`NeuraiMessage.verify()` from the Neurai addon.
|
|
173
|
+
|
|
115
174
|
### Get BIP32 extended public key
|
|
116
175
|
|
|
117
176
|
```javascript
|
|
@@ -182,6 +241,7 @@ using JSON messages. Supported commands:
|
|
|
182
241
|
| `get_address` | Physical button | 30s |
|
|
183
242
|
| `get_bip32_pubkey` | Physical button | 30s |
|
|
184
243
|
| `sign_psbt` | Physical button + TX review | 60s |
|
|
244
|
+
| `sign_message` | Physical button | 30s |
|
|
185
245
|
|
|
186
246
|
## API
|
|
187
247
|
|
|
@@ -197,16 +257,30 @@ Main class for device interaction.
|
|
|
197
257
|
| `getAddress()` | Get address + pubkey (requires confirmation) |
|
|
198
258
|
| `getBip32Pubkey()` | Get account xpub (requires confirmation) |
|
|
199
259
|
| `signPsbt(base64)` | Sign a PSBT (requires confirmation) |
|
|
260
|
+
| `signPsbt(base64, display?)` | Sign a PSBT and optionally send display metadata |
|
|
261
|
+
| `signMessage(message)` | Sign a message to prove address ownership (requires confirmation) |
|
|
200
262
|
| `signTransaction(opts)` | Build + sign + finalize in one call |
|
|
201
263
|
|
|
202
264
|
### `buildPSBT(options)`
|
|
203
265
|
|
|
204
266
|
Build an unsigned PSBT for P2PKH. Returns base64 string.
|
|
205
267
|
|
|
268
|
+
### `buildPSBTFromRawTransaction(options)`
|
|
269
|
+
|
|
270
|
+
Build an unsigned PSBT from an already-created raw unsigned transaction plus
|
|
271
|
+
input metadata. This is the preferred path when the wallet already handles coin
|
|
272
|
+
selection, fee calculation, asset outputs, and change outputs externally.
|
|
273
|
+
|
|
206
274
|
### `finalizePSBT(base64, network)`
|
|
207
275
|
|
|
208
276
|
Finalize a signed PSBT. Returns `{ txHex, txId }`.
|
|
209
277
|
|
|
278
|
+
### `finalizeSignedPSBT(originalPsbtBase64, signedPsbtBase64, network)`
|
|
279
|
+
|
|
280
|
+
Merge a signed PSBT returned by NeuraiHW with the original PSBT and finalize it.
|
|
281
|
+
This helper also supports the minimal PSBT format returned by `uNeurai`, and
|
|
282
|
+
includes fallback logic for legacy P2PKH finalization used by Neurai.
|
|
283
|
+
|
|
210
284
|
### `validatePSBT(base64, network)`
|
|
211
285
|
|
|
212
286
|
Check if a PSBT base64 string is parseable. Returns boolean.
|
package/dist/index.cjs
CHANGED
|
@@ -12,6 +12,7 @@ $parcel$export(module.exports, "buildPSBTFromRawTransaction", () => $5da7d5b3a85
|
|
|
12
12
|
$parcel$export(module.exports, "finalizePSBT", () => $5da7d5b3a851268c$export$ce839c4c9bcf7b77);
|
|
13
13
|
$parcel$export(module.exports, "finalizeSignedPSBT", () => $5da7d5b3a851268c$export$3a31c64c43aacd3);
|
|
14
14
|
$parcel$export(module.exports, "validatePSBT", () => $5da7d5b3a851268c$export$78a5723c75e7be9);
|
|
15
|
+
$parcel$export(module.exports, "buildAssetTransferDisplayMetadata", () => $d38ddd247dfd773e$export$fccc4f737c7e9291);
|
|
15
16
|
$parcel$export(module.exports, "SerialConnection", () => $a48f33fba55d0d0b$export$f93edba7156cc57b);
|
|
16
17
|
$parcel$export(module.exports, "getNetwork", () => $8eddb774c9d38ccb$export$7de4970ebfd8206d);
|
|
17
18
|
$parcel$export(module.exports, "neuraiMainnet", () => $8eddb774c9d38ccb$export$6b5a4442fe3d94ae);
|
|
@@ -163,6 +164,11 @@ class $a48f33fba55d0d0b$export$f93edba7156cc57b {
|
|
|
163
164
|
// Send JSON in small chunks, then newline to trigger processing.
|
|
164
165
|
// The ESP32 CDC serial buffer can lose data if sent too fast in one write.
|
|
165
166
|
const json = JSON.stringify(command);
|
|
167
|
+
console.debug("[NeuraiESP32 Serial] Sending command", {
|
|
168
|
+
action: command.action,
|
|
169
|
+
payloadLength: json.length + 1,
|
|
170
|
+
timeoutMs: timeoutMs
|
|
171
|
+
});
|
|
166
172
|
await this.writeChunked(json);
|
|
167
173
|
await this.writer.ready;
|
|
168
174
|
await this.writer.write("\n");
|
|
@@ -178,6 +184,11 @@ class $a48f33fba55d0d0b$export$f93edba7156cc57b {
|
|
|
178
184
|
if (!this.writer) throw new Error("Serial port not connected");
|
|
179
185
|
this.responseQueue = [];
|
|
180
186
|
const json = JSON.stringify(command);
|
|
187
|
+
console.debug("[NeuraiESP32 Serial] Sending command", {
|
|
188
|
+
action: command.action,
|
|
189
|
+
payloadLength: json.length + 1,
|
|
190
|
+
timeoutMs: timeoutMs
|
|
191
|
+
});
|
|
181
192
|
await this.writeChunked(json);
|
|
182
193
|
await this.writer.ready;
|
|
183
194
|
await this.writer.write("\n");
|
|
@@ -208,11 +219,12 @@ class $a48f33fba55d0d0b$export$f93edba7156cc57b {
|
|
|
208
219
|
// Try to parse as JSON response
|
|
209
220
|
if (line.startsWith("{")) try {
|
|
210
221
|
const data = JSON.parse(line);
|
|
222
|
+
console.debug("[NeuraiESP32 Serial] JSON line received", data);
|
|
211
223
|
this.responseQueue.push(data);
|
|
212
224
|
} catch {
|
|
213
|
-
|
|
225
|
+
console.debug("[NeuraiESP32 Serial] Invalid JSON line", line);
|
|
214
226
|
}
|
|
215
|
-
|
|
227
|
+
else console.debug("[NeuraiESP32 Serial] Non-JSON serial line", line);
|
|
216
228
|
}
|
|
217
229
|
} catch {
|
|
218
230
|
break;
|
|
@@ -222,9 +234,21 @@ class $a48f33fba55d0d0b$export$f93edba7156cc57b {
|
|
|
222
234
|
return new Promise((resolve)=>{
|
|
223
235
|
const startTime = Date.now();
|
|
224
236
|
const check = ()=>{
|
|
225
|
-
if (this.responseQueue.length > 0)
|
|
226
|
-
|
|
227
|
-
|
|
237
|
+
if (this.responseQueue.length > 0) {
|
|
238
|
+
const response = this.responseQueue.shift();
|
|
239
|
+
console.debug("[NeuraiESP32 Serial] Response dequeued", {
|
|
240
|
+
waitedMs: Date.now() - startTime,
|
|
241
|
+
pendingResponses: this.responseQueue.length,
|
|
242
|
+
status: response.status
|
|
243
|
+
});
|
|
244
|
+
resolve(response);
|
|
245
|
+
} else if (Date.now() - startTime > timeoutMs) {
|
|
246
|
+
console.error("[NeuraiESP32 Serial] Response timeout", {
|
|
247
|
+
timeoutMs: timeoutMs,
|
|
248
|
+
queuedResponses: this.responseQueue.length
|
|
249
|
+
});
|
|
250
|
+
resolve(null);
|
|
251
|
+
} else setTimeout(check, 50);
|
|
228
252
|
};
|
|
229
253
|
check();
|
|
230
254
|
});
|
|
@@ -530,9 +554,6 @@ function $5da7d5b3a851268c$var$finalizeLegacyP2pkhInputs(psbt) {
|
|
|
530
554
|
const prevTx = $8zHUo$bitcoinjslib.Transaction.fromBuffer(nonWitnessUtxo);
|
|
531
555
|
const prevOut = prevTx.outs[txInput.index];
|
|
532
556
|
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
557
|
psbt.finalizeInput(index, ()=>({
|
|
537
558
|
finalScriptSig: $8zHUo$bitcoinjslib.script.compile([
|
|
538
559
|
partialSig.signature,
|
|
@@ -610,14 +631,34 @@ class $4f193116bbff8497$export$fa10ee8b91a777b7 {
|
|
|
610
631
|
return response;
|
|
611
632
|
}
|
|
612
633
|
/**
|
|
634
|
+
* Sign a message to prove address ownership.
|
|
635
|
+
* Requires user physical confirmation on the device (30s timeout).
|
|
636
|
+
*
|
|
637
|
+
* The signature is base64-encoded, compatible with Bitcoin/Neurai message
|
|
638
|
+
* signing (recoverable ECDSA with "Neurai Signed Message:\n" prefix).
|
|
639
|
+
*
|
|
640
|
+
* @param message - The message string to sign (max 1024 bytes)
|
|
641
|
+
* @returns Signature (base64), address, and the original message
|
|
642
|
+
*/ async signMessage(message) {
|
|
643
|
+
const response = await this.serial.sendCommand({
|
|
644
|
+
action: "sign_message",
|
|
645
|
+
message: message
|
|
646
|
+
}, 35000);
|
|
647
|
+
this.assertSuccess(response);
|
|
648
|
+
return response;
|
|
649
|
+
}
|
|
650
|
+
/**
|
|
613
651
|
* Send a raw PSBT (base64) to the device for signing.
|
|
614
652
|
* Requires user physical confirmation on the device (60s timeout).
|
|
615
653
|
*
|
|
616
654
|
* Use this if you build the PSBT yourself.
|
|
617
|
-
*/ async signPsbt(psbtBase64) {
|
|
655
|
+
*/ async signPsbt(psbtBase64, display) {
|
|
618
656
|
const response = await this.serial.sendCommandFinal({
|
|
619
657
|
action: "sign_psbt",
|
|
620
|
-
psbt: psbtBase64
|
|
658
|
+
psbt: psbtBase64,
|
|
659
|
+
...display ? {
|
|
660
|
+
display: display
|
|
661
|
+
} : {}
|
|
621
662
|
}, 65000);
|
|
622
663
|
this.assertSuccess(response);
|
|
623
664
|
return response;
|
|
@@ -662,7 +703,7 @@ class $4f193116bbff8497$export$fa10ee8b91a777b7 {
|
|
|
662
703
|
feeRate: options.feeRate
|
|
663
704
|
});
|
|
664
705
|
// 2. Send to ESP32 for signing
|
|
665
|
-
const signResponse = await this.signPsbt(psbtBase64);
|
|
706
|
+
const signResponse = await this.signPsbt(psbtBase64, options.display);
|
|
666
707
|
// 3. Finalize and extract raw transaction
|
|
667
708
|
const { txHex: txHex, txId: txId } = (0, $5da7d5b3a851268c$export$3a31c64c43aacd3)(psbtBase64, signResponse.psbt, network);
|
|
668
709
|
return {
|
|
@@ -690,6 +731,26 @@ class $4f193116bbff8497$export$fa10ee8b91a777b7 {
|
|
|
690
731
|
|
|
691
732
|
|
|
692
733
|
|
|
734
|
+
function $d38ddd247dfd773e$var$formatAmount(value) {
|
|
735
|
+
if (typeof value === "string") return value;
|
|
736
|
+
return value.toFixed(8);
|
|
737
|
+
}
|
|
738
|
+
function $d38ddd247dfd773e$export$fccc4f737c7e9291(options) {
|
|
739
|
+
return {
|
|
740
|
+
kind: "asset_transfer",
|
|
741
|
+
assetName: options.assetName,
|
|
742
|
+
assetAmount: $d38ddd247dfd773e$var$formatAmount(options.assetAmount),
|
|
743
|
+
destinationAddress: options.destinationAddress,
|
|
744
|
+
destinationCount: options.destinationCount ?? 1,
|
|
745
|
+
changeAddress: options.changeAddress,
|
|
746
|
+
changeCount: options.changeCount ?? 0,
|
|
747
|
+
inputAddresses: options.inputAddresses ?? [],
|
|
748
|
+
feeAmount: options.feeAmount === undefined ? undefined : $d38ddd247dfd773e$var$formatAmount(options.feeAmount),
|
|
749
|
+
baseCurrency: options.baseCurrency ?? "XNA"
|
|
750
|
+
};
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
|
|
693
754
|
|
|
694
755
|
|
|
695
756
|
|
package/dist/index.cjs.map
CHANGED
|
@@ -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,OAAO,cAAc,eAA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"],"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"}
|
|
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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K,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;;;;AI9RA,SAAS,mCAAa,KAAsB;IAC1C,IAAI,OAAO,UAAU,UACnB,OAAO;IAET,OAAO,MAAM,OAAO,CAAC;AACvB;AAEO,SAAS,0CACd,OAAkD;IAElD,OAAO;QACL,MAAM;QACN,WAAW,QAAQ,SAAS;QAC5B,aAAa,mCAAa,QAAQ,WAAW;QAC7C,oBAAoB,QAAQ,kBAAkB;QAC9C,kBAAkB,QAAQ,gBAAgB,IAAI;QAC9C,eAAe,QAAQ,aAAa;QACpC,aAAa,QAAQ,WAAW,IAAI;QACpC,gBAAgB,QAAQ,cAAc,IAAI,EAAE;QAC5C,WACE,QAAQ,SAAS,KAAK,YAAY,YAAY,mCAAa,QAAQ,SAAS;QAC9E,cAAc,QAAQ,YAAY,IAAI;IACxC;AACF;;","sources":["src/index.ts","src/NeuraiESP32.ts","src/serial.ts","src/psbt.ts","src/networks.ts","src/display.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// Display metadata helpers\nexport { buildAssetTransferDisplayMetadata } from \"./display.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 IBuildAssetTransferDisplayMetadataOptions,\n IPSBTInputMetadata,\n IAssetTransferDisplayMetadata,\n ISigningDisplayMetadata,\n IDeviceInfo,\n IAddressResponse,\n IBip32PubkeyResponse,\n ISignPsbtResponse,\n ISignMessageResponse,\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 ISigningDisplayMetadata,\n ISignMessageResponse,\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 * Sign a message to prove address ownership.\n * Requires user physical confirmation on the device (30s timeout).\n *\n * The signature is base64-encoded, compatible with Bitcoin/Neurai message\n * signing (recoverable ECDSA with \"Neurai Signed Message:\\n\" prefix).\n *\n * @param message - The message string to sign (max 1024 bytes)\n * @returns Signature (base64), address, and the original message\n */\n async signMessage(message: string): Promise<ISignMessageResponse> {\n const response = await this.serial.sendCommand(\n { action: \"sign_message\", message },\n 35000\n );\n\n this.assertSuccess(response);\n return response as ISignMessageResponse;\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(\n psbtBase64: string,\n display?: ISigningDisplayMetadata\n ): Promise<ISignPsbtResponse> {\n const response = await this.serial.sendCommandFinal(\n {\n action: \"sign_psbt\",\n psbt: psbtBase64,\n ...(display ? { display } : {}),\n },\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 display?: ISigningDisplayMetadata;\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, options.display);\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 console.debug(\"[NeuraiESP32 Serial] Sending command\", {\n action: command.action,\n payloadLength: json.length + 1,\n timeoutMs,\n });\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 console.debug(\"[NeuraiESP32 Serial] Sending command\", {\n action: command.action,\n payloadLength: json.length + 1,\n timeoutMs,\n });\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 console.debug(\"[NeuraiESP32 Serial] JSON line received\", data);\n this.responseQueue.push(data);\n } catch {\n console.debug(\"[NeuraiESP32 Serial] Invalid JSON line\", line);\n }\n } else {\n console.debug(\"[NeuraiESP32 Serial] Non-JSON serial line\", line);\n }\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 const response = this.responseQueue.shift()!;\n console.debug(\"[NeuraiESP32 Serial] Response dequeued\", {\n waitedMs: Date.now() - startTime,\n pendingResponses: this.responseQueue.length,\n status: response.status,\n });\n resolve(response);\n } else if (Date.now() - startTime > timeoutMs) {\n console.error(\"[NeuraiESP32 Serial] Response timeout\", {\n timeoutMs,\n queuedResponses: this.responseQueue.length,\n });\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 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","import type {\n IAssetTransferDisplayMetadata,\n IBuildAssetTransferDisplayMetadataOptions,\n} from \"./types.js\";\n\nfunction formatAmount(value: number | string): string {\n if (typeof value === \"string\") {\n return value;\n }\n return value.toFixed(8);\n}\n\nexport function buildAssetTransferDisplayMetadata(\n options: IBuildAssetTransferDisplayMetadataOptions\n): IAssetTransferDisplayMetadata {\n return {\n kind: \"asset_transfer\",\n assetName: options.assetName,\n assetAmount: formatAmount(options.assetAmount),\n destinationAddress: options.destinationAddress,\n destinationCount: options.destinationCount ?? 1,\n changeAddress: options.changeAddress,\n changeCount: options.changeCount ?? 0,\n inputAddresses: options.inputAddresses ?? [],\n feeAmount:\n options.feeAmount === undefined ? undefined : formatAmount(options.feeAmount),\n baseCurrency: options.baseCurrency ?? \"XNA\",\n };\n}\n"],"names":[],"version":3,"file":"index.cjs.map"}
|
package/dist/index.d.ts
CHANGED
|
@@ -47,10 +47,35 @@ export interface IPSBTInputMetadata {
|
|
|
47
47
|
masterFingerprint: string;
|
|
48
48
|
derivationPath: string;
|
|
49
49
|
}
|
|
50
|
+
export interface IAssetTransferDisplayMetadata {
|
|
51
|
+
kind: "asset_transfer";
|
|
52
|
+
assetName: string;
|
|
53
|
+
assetAmount: string;
|
|
54
|
+
destinationAddress: string;
|
|
55
|
+
destinationCount?: number;
|
|
56
|
+
changeAddress?: string;
|
|
57
|
+
changeCount?: number;
|
|
58
|
+
inputAddresses?: string[];
|
|
59
|
+
feeAmount?: string;
|
|
60
|
+
baseCurrency?: string;
|
|
61
|
+
}
|
|
62
|
+
export type ISigningDisplayMetadata = IAssetTransferDisplayMetadata;
|
|
50
63
|
export interface IBuildPSBTFromRawOptions {
|
|
51
64
|
network: NetworkType;
|
|
52
65
|
rawUnsignedTransaction: string;
|
|
53
66
|
inputs: IPSBTInputMetadata[];
|
|
67
|
+
display?: ISigningDisplayMetadata;
|
|
68
|
+
}
|
|
69
|
+
export interface IBuildAssetTransferDisplayMetadataOptions {
|
|
70
|
+
assetName: string;
|
|
71
|
+
assetAmount: number | string;
|
|
72
|
+
destinationAddress: string;
|
|
73
|
+
destinationCount?: number;
|
|
74
|
+
changeAddress?: string;
|
|
75
|
+
changeCount?: number;
|
|
76
|
+
inputAddresses?: string[];
|
|
77
|
+
feeAmount?: number | string;
|
|
78
|
+
baseCurrency?: string;
|
|
54
79
|
}
|
|
55
80
|
export interface IDeviceInfo {
|
|
56
81
|
status: string;
|
|
@@ -81,6 +106,15 @@ export interface ISignPsbtResponse {
|
|
|
81
106
|
psbt: string;
|
|
82
107
|
signed_inputs: number;
|
|
83
108
|
}
|
|
109
|
+
export interface ISignMessageResponse {
|
|
110
|
+
status: string;
|
|
111
|
+
/** Base64-encoded recoverable signature (65 bytes) */
|
|
112
|
+
signature: string;
|
|
113
|
+
/** Address that signed the message */
|
|
114
|
+
address: string;
|
|
115
|
+
/** The original message that was signed */
|
|
116
|
+
message: string;
|
|
117
|
+
}
|
|
84
118
|
export interface IErrorResponse {
|
|
85
119
|
status: "error";
|
|
86
120
|
message: string;
|
|
@@ -89,7 +123,7 @@ interface IProcessingResponse {
|
|
|
89
123
|
status: "processing";
|
|
90
124
|
stage: string;
|
|
91
125
|
}
|
|
92
|
-
type DeviceResponse = IDeviceInfo | IAddressResponse | IBip32PubkeyResponse | ISignPsbtResponse | IErrorResponse | IProcessingResponse;
|
|
126
|
+
type DeviceResponse = IDeviceInfo | IAddressResponse | IBip32PubkeyResponse | ISignPsbtResponse | ISignMessageResponse | IErrorResponse | IProcessingResponse;
|
|
93
127
|
export interface ISerialOptions {
|
|
94
128
|
/** Baud rate (default: 115200) */
|
|
95
129
|
baudRate?: number;
|
|
@@ -197,13 +231,24 @@ export class NeuraiESP32 {
|
|
|
197
231
|
* Requires user physical confirmation on the device (30s timeout).
|
|
198
232
|
*/
|
|
199
233
|
getBip32Pubkey(): Promise<IBip32PubkeyResponse>;
|
|
234
|
+
/**
|
|
235
|
+
* Sign a message to prove address ownership.
|
|
236
|
+
* Requires user physical confirmation on the device (30s timeout).
|
|
237
|
+
*
|
|
238
|
+
* The signature is base64-encoded, compatible with Bitcoin/Neurai message
|
|
239
|
+
* signing (recoverable ECDSA with "Neurai Signed Message:\n" prefix).
|
|
240
|
+
*
|
|
241
|
+
* @param message - The message string to sign (max 1024 bytes)
|
|
242
|
+
* @returns Signature (base64), address, and the original message
|
|
243
|
+
*/
|
|
244
|
+
signMessage(message: string): Promise<ISignMessageResponse>;
|
|
200
245
|
/**
|
|
201
246
|
* Send a raw PSBT (base64) to the device for signing.
|
|
202
247
|
* Requires user physical confirmation on the device (60s timeout).
|
|
203
248
|
*
|
|
204
249
|
* Use this if you build the PSBT yourself.
|
|
205
250
|
*/
|
|
206
|
-
signPsbt(psbtBase64: string): Promise<ISignPsbtResponse>;
|
|
251
|
+
signPsbt(psbtBase64: string, display?: ISigningDisplayMetadata): Promise<ISignPsbtResponse>;
|
|
207
252
|
/**
|
|
208
253
|
* Build, sign, and finalize a transaction in one call.
|
|
209
254
|
*
|
|
@@ -231,7 +276,9 @@ export class NeuraiESP32 {
|
|
|
231
276
|
masterFingerprint?: string;
|
|
232
277
|
derivationPath?: string;
|
|
233
278
|
feeRate?: number;
|
|
279
|
+
display?: ISigningDisplayMetadata;
|
|
234
280
|
}): Promise<ISignResult>;
|
|
235
281
|
}
|
|
282
|
+
export function buildAssetTransferDisplayMetadata(options: IBuildAssetTransferDisplayMetadataOptions): IAssetTransferDisplayMetadata;
|
|
236
283
|
|
|
237
284
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.d.ts.map
CHANGED
|
@@ -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;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;CACx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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;;;;;;;;;OASG;IACG,WAAW,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,oBAAoB,CAAC;IAUjE;;;;;OAKG;IACG,QAAQ,CACZ,UAAU,EAAE,MAAM,EAClB,OAAO,CAAC,EAAE,uBAAuB,GAChC,OAAO,CAAC,iBAAiB,CAAC;IAgB7B;;;;;;;;;;;;;;;;;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;QACjB,OAAO,CAAC,EAAE,uBAAuB,CAAC;KACnC,GAAG,OAAO,CAAC,WAAW,CAAC;CAwFzB;ACvRD,kDACE,OAAO,EAAE,yCAAyC,GACjD,6BAA6B,CAc/B","sources":["src/src/types.ts","src/src/serial.ts","src/src/networks.ts","src/src/psbt.ts","src/src/NeuraiESP32.ts","src/src/display.ts","src/src/index.ts","src/index.ts"],"sourcesContent":[null,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// Display metadata helpers\nexport { buildAssetTransferDisplayMetadata } from \"./display.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 IBuildAssetTransferDisplayMetadataOptions,\n IPSBTInputMetadata,\n IAssetTransferDisplayMetadata,\n ISigningDisplayMetadata,\n IDeviceInfo,\n IAddressResponse,\n IBip32PubkeyResponse,\n ISignPsbtResponse,\n ISignMessageResponse,\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,5 +1,5 @@
|
|
|
1
1
|
import {Buffer as $hgUW1$Buffer} from "buffer";
|
|
2
|
-
import {Psbt as $hgUW1$Psbt, Transaction as $hgUW1$Transaction, script as $hgUW1$script
|
|
2
|
+
import {Psbt as $hgUW1$Psbt, Transaction as $hgUW1$Transaction, script as $hgUW1$script} from "bitcoinjs-lib";
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
5
|
* @neuraiproject/neurai-sign-esp32
|
|
@@ -146,6 +146,11 @@ class $f1b85200f32d8427$export$f93edba7156cc57b {
|
|
|
146
146
|
// Send JSON in small chunks, then newline to trigger processing.
|
|
147
147
|
// The ESP32 CDC serial buffer can lose data if sent too fast in one write.
|
|
148
148
|
const json = JSON.stringify(command);
|
|
149
|
+
console.debug("[NeuraiESP32 Serial] Sending command", {
|
|
150
|
+
action: command.action,
|
|
151
|
+
payloadLength: json.length + 1,
|
|
152
|
+
timeoutMs: timeoutMs
|
|
153
|
+
});
|
|
149
154
|
await this.writeChunked(json);
|
|
150
155
|
await this.writer.ready;
|
|
151
156
|
await this.writer.write("\n");
|
|
@@ -161,6 +166,11 @@ class $f1b85200f32d8427$export$f93edba7156cc57b {
|
|
|
161
166
|
if (!this.writer) throw new Error("Serial port not connected");
|
|
162
167
|
this.responseQueue = [];
|
|
163
168
|
const json = JSON.stringify(command);
|
|
169
|
+
console.debug("[NeuraiESP32 Serial] Sending command", {
|
|
170
|
+
action: command.action,
|
|
171
|
+
payloadLength: json.length + 1,
|
|
172
|
+
timeoutMs: timeoutMs
|
|
173
|
+
});
|
|
164
174
|
await this.writeChunked(json);
|
|
165
175
|
await this.writer.ready;
|
|
166
176
|
await this.writer.write("\n");
|
|
@@ -191,11 +201,12 @@ class $f1b85200f32d8427$export$f93edba7156cc57b {
|
|
|
191
201
|
// Try to parse as JSON response
|
|
192
202
|
if (line.startsWith("{")) try {
|
|
193
203
|
const data = JSON.parse(line);
|
|
204
|
+
console.debug("[NeuraiESP32 Serial] JSON line received", data);
|
|
194
205
|
this.responseQueue.push(data);
|
|
195
206
|
} catch {
|
|
196
|
-
|
|
207
|
+
console.debug("[NeuraiESP32 Serial] Invalid JSON line", line);
|
|
197
208
|
}
|
|
198
|
-
|
|
209
|
+
else console.debug("[NeuraiESP32 Serial] Non-JSON serial line", line);
|
|
199
210
|
}
|
|
200
211
|
} catch {
|
|
201
212
|
break;
|
|
@@ -205,9 +216,21 @@ class $f1b85200f32d8427$export$f93edba7156cc57b {
|
|
|
205
216
|
return new Promise((resolve)=>{
|
|
206
217
|
const startTime = Date.now();
|
|
207
218
|
const check = ()=>{
|
|
208
|
-
if (this.responseQueue.length > 0)
|
|
209
|
-
|
|
210
|
-
|
|
219
|
+
if (this.responseQueue.length > 0) {
|
|
220
|
+
const response = this.responseQueue.shift();
|
|
221
|
+
console.debug("[NeuraiESP32 Serial] Response dequeued", {
|
|
222
|
+
waitedMs: Date.now() - startTime,
|
|
223
|
+
pendingResponses: this.responseQueue.length,
|
|
224
|
+
status: response.status
|
|
225
|
+
});
|
|
226
|
+
resolve(response);
|
|
227
|
+
} else if (Date.now() - startTime > timeoutMs) {
|
|
228
|
+
console.error("[NeuraiESP32 Serial] Response timeout", {
|
|
229
|
+
timeoutMs: timeoutMs,
|
|
230
|
+
queuedResponses: this.responseQueue.length
|
|
231
|
+
});
|
|
232
|
+
resolve(null);
|
|
233
|
+
} else setTimeout(check, 50);
|
|
211
234
|
};
|
|
212
235
|
check();
|
|
213
236
|
});
|
|
@@ -513,9 +536,6 @@ function $68e2926fe257f2e4$var$finalizeLegacyP2pkhInputs(psbt) {
|
|
|
513
536
|
const prevTx = $hgUW1$Transaction.fromBuffer(nonWitnessUtxo);
|
|
514
537
|
const prevOut = prevTx.outs[txInput.index];
|
|
515
538
|
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
539
|
psbt.finalizeInput(index, ()=>({
|
|
520
540
|
finalScriptSig: $hgUW1$script.compile([
|
|
521
541
|
partialSig.signature,
|
|
@@ -593,14 +613,34 @@ class $a6c8409f4f68b3eb$export$fa10ee8b91a777b7 {
|
|
|
593
613
|
return response;
|
|
594
614
|
}
|
|
595
615
|
/**
|
|
616
|
+
* Sign a message to prove address ownership.
|
|
617
|
+
* Requires user physical confirmation on the device (30s timeout).
|
|
618
|
+
*
|
|
619
|
+
* The signature is base64-encoded, compatible with Bitcoin/Neurai message
|
|
620
|
+
* signing (recoverable ECDSA with "Neurai Signed Message:\n" prefix).
|
|
621
|
+
*
|
|
622
|
+
* @param message - The message string to sign (max 1024 bytes)
|
|
623
|
+
* @returns Signature (base64), address, and the original message
|
|
624
|
+
*/ async signMessage(message) {
|
|
625
|
+
const response = await this.serial.sendCommand({
|
|
626
|
+
action: "sign_message",
|
|
627
|
+
message: message
|
|
628
|
+
}, 35000);
|
|
629
|
+
this.assertSuccess(response);
|
|
630
|
+
return response;
|
|
631
|
+
}
|
|
632
|
+
/**
|
|
596
633
|
* Send a raw PSBT (base64) to the device for signing.
|
|
597
634
|
* Requires user physical confirmation on the device (60s timeout).
|
|
598
635
|
*
|
|
599
636
|
* Use this if you build the PSBT yourself.
|
|
600
|
-
*/ async signPsbt(psbtBase64) {
|
|
637
|
+
*/ async signPsbt(psbtBase64, display) {
|
|
601
638
|
const response = await this.serial.sendCommandFinal({
|
|
602
639
|
action: "sign_psbt",
|
|
603
|
-
psbt: psbtBase64
|
|
640
|
+
psbt: psbtBase64,
|
|
641
|
+
...display ? {
|
|
642
|
+
display: display
|
|
643
|
+
} : {}
|
|
604
644
|
}, 65000);
|
|
605
645
|
this.assertSuccess(response);
|
|
606
646
|
return response;
|
|
@@ -645,7 +685,7 @@ class $a6c8409f4f68b3eb$export$fa10ee8b91a777b7 {
|
|
|
645
685
|
feeRate: options.feeRate
|
|
646
686
|
});
|
|
647
687
|
// 2. Send to ESP32 for signing
|
|
648
|
-
const signResponse = await this.signPsbt(psbtBase64);
|
|
688
|
+
const signResponse = await this.signPsbt(psbtBase64, options.display);
|
|
649
689
|
// 3. Finalize and extract raw transaction
|
|
650
690
|
const { txHex: txHex, txId: txId } = (0, $68e2926fe257f2e4$export$3a31c64c43aacd3)(psbtBase64, signResponse.psbt, network);
|
|
651
691
|
return {
|
|
@@ -673,9 +713,29 @@ class $a6c8409f4f68b3eb$export$fa10ee8b91a777b7 {
|
|
|
673
713
|
|
|
674
714
|
|
|
675
715
|
|
|
716
|
+
function $4136916c4ceb2a50$var$formatAmount(value) {
|
|
717
|
+
if (typeof value === "string") return value;
|
|
718
|
+
return value.toFixed(8);
|
|
719
|
+
}
|
|
720
|
+
function $4136916c4ceb2a50$export$fccc4f737c7e9291(options) {
|
|
721
|
+
return {
|
|
722
|
+
kind: "asset_transfer",
|
|
723
|
+
assetName: options.assetName,
|
|
724
|
+
assetAmount: $4136916c4ceb2a50$var$formatAmount(options.assetAmount),
|
|
725
|
+
destinationAddress: options.destinationAddress,
|
|
726
|
+
destinationCount: options.destinationCount ?? 1,
|
|
727
|
+
changeAddress: options.changeAddress,
|
|
728
|
+
changeCount: options.changeCount ?? 0,
|
|
729
|
+
inputAddresses: options.inputAddresses ?? [],
|
|
730
|
+
feeAmount: options.feeAmount === undefined ? undefined : $4136916c4ceb2a50$var$formatAmount(options.feeAmount),
|
|
731
|
+
baseCurrency: options.baseCurrency ?? "XNA"
|
|
732
|
+
};
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
|
|
676
736
|
|
|
677
737
|
|
|
678
738
|
|
|
679
739
|
|
|
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};
|
|
740
|
+
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, $4136916c4ceb2a50$export$fccc4f737c7e9291 as buildAssetTransferDisplayMetadata, $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};
|
|
681
741
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -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;;GA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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"}
|
|
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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iB;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;;;;AI9RA,SAAS,mCAAa,KAAsB;IAC1C,IAAI,OAAO,UAAU,UACnB,OAAO;IAET,OAAO,MAAM,OAAO,CAAC;AACvB;AAEO,SAAS,0CACd,OAAkD;IAElD,OAAO;QACL,MAAM;QACN,WAAW,QAAQ,SAAS;QAC5B,aAAa,mCAAa,QAAQ,WAAW;QAC7C,oBAAoB,QAAQ,kBAAkB;QAC9C,kBAAkB,QAAQ,gBAAgB,IAAI;QAC9C,eAAe,QAAQ,aAAa;QACpC,aAAa,QAAQ,WAAW,IAAI;QACpC,gBAAgB,QAAQ,cAAc,IAAI,EAAE;QAC5C,WACE,QAAQ,SAAS,KAAK,YAAY,YAAY,mCAAa,QAAQ,SAAS;QAC9E,cAAc,QAAQ,YAAY,IAAI;IACxC;AACF;;","sources":["src/index.ts","src/NeuraiESP32.ts","src/serial.ts","src/psbt.ts","src/networks.ts","src/display.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// Display metadata helpers\nexport { buildAssetTransferDisplayMetadata } from \"./display.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 IBuildAssetTransferDisplayMetadataOptions,\n IPSBTInputMetadata,\n IAssetTransferDisplayMetadata,\n ISigningDisplayMetadata,\n IDeviceInfo,\n IAddressResponse,\n IBip32PubkeyResponse,\n ISignPsbtResponse,\n ISignMessageResponse,\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 ISigningDisplayMetadata,\n ISignMessageResponse,\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 * Sign a message to prove address ownership.\n * Requires user physical confirmation on the device (30s timeout).\n *\n * The signature is base64-encoded, compatible with Bitcoin/Neurai message\n * signing (recoverable ECDSA with \"Neurai Signed Message:\\n\" prefix).\n *\n * @param message - The message string to sign (max 1024 bytes)\n * @returns Signature (base64), address, and the original message\n */\n async signMessage(message: string): Promise<ISignMessageResponse> {\n const response = await this.serial.sendCommand(\n { action: \"sign_message\", message },\n 35000\n );\n\n this.assertSuccess(response);\n return response as ISignMessageResponse;\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(\n psbtBase64: string,\n display?: ISigningDisplayMetadata\n ): Promise<ISignPsbtResponse> {\n const response = await this.serial.sendCommandFinal(\n {\n action: \"sign_psbt\",\n psbt: psbtBase64,\n ...(display ? { display } : {}),\n },\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 display?: ISigningDisplayMetadata;\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, options.display);\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 console.debug(\"[NeuraiESP32 Serial] Sending command\", {\n action: command.action,\n payloadLength: json.length + 1,\n timeoutMs,\n });\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 console.debug(\"[NeuraiESP32 Serial] Sending command\", {\n action: command.action,\n payloadLength: json.length + 1,\n timeoutMs,\n });\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 console.debug(\"[NeuraiESP32 Serial] JSON line received\", data);\n this.responseQueue.push(data);\n } catch {\n console.debug(\"[NeuraiESP32 Serial] Invalid JSON line\", line);\n }\n } else {\n console.debug(\"[NeuraiESP32 Serial] Non-JSON serial line\", line);\n }\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 const response = this.responseQueue.shift()!;\n console.debug(\"[NeuraiESP32 Serial] Response dequeued\", {\n waitedMs: Date.now() - startTime,\n pendingResponses: this.responseQueue.length,\n status: response.status,\n });\n resolve(response);\n } else if (Date.now() - startTime > timeoutMs) {\n console.error(\"[NeuraiESP32 Serial] Response timeout\", {\n timeoutMs,\n queuedResponses: this.responseQueue.length,\n });\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 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","import type {\n IAssetTransferDisplayMetadata,\n IBuildAssetTransferDisplayMetadataOptions,\n} from \"./types.js\";\n\nfunction formatAmount(value: number | string): string {\n if (typeof value === \"string\") {\n return value;\n }\n return value.toFixed(8);\n}\n\nexport function buildAssetTransferDisplayMetadata(\n options: IBuildAssetTransferDisplayMetadataOptions\n): IAssetTransferDisplayMetadata {\n return {\n kind: \"asset_transfer\",\n assetName: options.assetName,\n assetAmount: formatAmount(options.assetAmount),\n destinationAddress: options.destinationAddress,\n destinationCount: options.destinationCount ?? 1,\n changeAddress: options.changeAddress,\n changeCount: options.changeCount ?? 0,\n inputAddresses: options.inputAddresses ?? [],\n feeAmount:\n options.feeAmount === undefined ? undefined : formatAmount(options.feeAmount),\n baseCurrency: options.baseCurrency ?? \"XNA\",\n };\n}\n"],"names":[],"version":3,"file":"index.mjs.map"}
|
package/package.json
CHANGED
|
@@ -1,12 +1,19 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@neuraiproject/neurai-sign-esp32",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "Create and sign PSBTs for Neurai via ESP32 hardware wallet",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"source": "src/index.ts",
|
|
7
7
|
"main": "dist/index.cjs",
|
|
8
8
|
"module": "dist/index.mjs",
|
|
9
9
|
"types": "dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"import": "./dist/index.mjs",
|
|
14
|
+
"require": "./dist/index.cjs"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
10
17
|
"files": [
|
|
11
18
|
"LICENSE",
|
|
12
19
|
"README.md",
|