@neuraiproject/neurai-scripts 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2471 @@
1
+ /**
2
+ * Minimal byte helpers. A subset of what `neurai-create-transaction` exposes,
3
+ * duplicated here to keep this package free of runtime coupling beyond its
4
+ * declared `dependencies` field. All sizes are little-endian, per Neurai.
5
+ */
6
+ function ensureHex(hex, label = 'hex') {
7
+ const normalized = String(hex || '').trim().toLowerCase();
8
+ if (!/^[0-9a-f]*$/.test(normalized) || normalized.length % 2 !== 0) {
9
+ throw new Error(`Invalid ${label}: expected even-length hex string`);
10
+ }
11
+ return normalized;
12
+ }
13
+ function hexToBytes(hex) {
14
+ const normalized = ensureHex(hex);
15
+ const bytes = new Uint8Array(normalized.length / 2);
16
+ for (let i = 0; i < normalized.length; i += 2) {
17
+ bytes[i / 2] = Number.parseInt(normalized.slice(i, i + 2), 16);
18
+ }
19
+ return bytes;
20
+ }
21
+ function bytesToHex(bytes) {
22
+ return Array.from(bytes, (value) => value.toString(16).padStart(2, '0')).join('');
23
+ }
24
+ function concatBytes(...parts) {
25
+ const total = parts.reduce((sum, part) => sum + part.length, 0);
26
+ const out = new Uint8Array(total);
27
+ let offset = 0;
28
+ for (const part of parts) {
29
+ out.set(part, offset);
30
+ offset += part.length;
31
+ }
32
+ return out;
33
+ }
34
+ function bytesEqual(a, b) {
35
+ if (a.length !== b.length)
36
+ return false;
37
+ for (let i = 0; i < a.length; i += 1) {
38
+ if (a[i] !== b[i])
39
+ return false;
40
+ }
41
+ return true;
42
+ }
43
+
44
+ /**
45
+ * Opcode constants for Neurai Script.
46
+ *
47
+ * Covers:
48
+ * - Classic Script opcodes used by covenants.
49
+ * - New opcodes activated in the `DePIN-Test` branch (BIP 119, BIP 347 and
50
+ * Neurai-specific introspection / asset / arithmetic additions).
51
+ *
52
+ * Authority: `src/script/script.h` (enum `opcodetype`) in the Neurai repo.
53
+ * Reference: `doc/new-opcodes-depin-branch.md`.
54
+ *
55
+ * Disabled in consensus and intentionally omitted: OP_SUBSTR, OP_LEFT,
56
+ * OP_RIGHT, OP_INVERT, OP_AND, OP_OR, OP_XOR, OP_2MUL, OP_2DIV, OP_LSHIFT,
57
+ * OP_RSHIFT. Also omitted: OP_VER / OP_VERIF / OP_VERNOTIF (reserved), the
58
+ * template-matching pseudo-opcodes (OP_SMALLINTEGER, OP_PUBKEYS,
59
+ * OP_PUBKEYHASH, OP_PUBKEY) and OP_INVALIDOPCODE.
60
+ */
61
+ // ---------- Push values ----------
62
+ const OP_0 = 0x00;
63
+ const OP_FALSE = OP_0;
64
+ const OP_PUSHDATA1 = 0x4c;
65
+ const OP_PUSHDATA2 = 0x4d;
66
+ const OP_PUSHDATA4 = 0x4e;
67
+ const OP_1NEGATE = 0x4f;
68
+ const OP_RESERVED = 0x50;
69
+ const OP_1 = 0x51;
70
+ const OP_TRUE = OP_1;
71
+ const OP_2 = 0x52;
72
+ const OP_3 = 0x53;
73
+ const OP_4 = 0x54;
74
+ const OP_5 = 0x55;
75
+ const OP_6 = 0x56;
76
+ const OP_7 = 0x57;
77
+ const OP_8 = 0x58;
78
+ const OP_9 = 0x59;
79
+ const OP_10 = 0x5a;
80
+ const OP_11 = 0x5b;
81
+ const OP_12 = 0x5c;
82
+ const OP_13 = 0x5d;
83
+ const OP_14 = 0x5e;
84
+ const OP_15 = 0x5f;
85
+ const OP_16 = 0x60;
86
+ // ---------- Control flow ----------
87
+ const OP_NOP = 0x61;
88
+ const OP_IF = 0x63;
89
+ const OP_NOTIF = 0x64;
90
+ const OP_ELSE = 0x67;
91
+ const OP_ENDIF = 0x68;
92
+ const OP_VERIFY = 0x69;
93
+ const OP_RETURN = 0x6a;
94
+ // ---------- Stack ----------
95
+ const OP_TOALTSTACK = 0x6b;
96
+ const OP_FROMALTSTACK = 0x6c;
97
+ const OP_2DROP = 0x6d;
98
+ const OP_2DUP = 0x6e;
99
+ const OP_3DUP = 0x6f;
100
+ const OP_2OVER = 0x70;
101
+ const OP_2ROT = 0x71;
102
+ const OP_2SWAP = 0x72;
103
+ const OP_IFDUP = 0x73;
104
+ const OP_DEPTH = 0x74;
105
+ const OP_DROP = 0x75;
106
+ const OP_DUP = 0x76;
107
+ const OP_NIP = 0x77;
108
+ const OP_OVER = 0x78;
109
+ const OP_PICK = 0x79;
110
+ const OP_ROLL = 0x7a;
111
+ const OP_ROT = 0x7b;
112
+ const OP_SWAP = 0x7c;
113
+ const OP_TUCK = 0x7d;
114
+ // ---------- Splice ----------
115
+ const OP_SIZE = 0x82;
116
+ // ---------- Bitwise / comparison ----------
117
+ const OP_EQUAL = 0x87;
118
+ const OP_EQUALVERIFY = 0x88;
119
+ // ---------- Unary numeric ----------
120
+ const OP_1ADD = 0x8b;
121
+ const OP_1SUB = 0x8c;
122
+ const OP_NEGATE = 0x8f;
123
+ const OP_ABS = 0x90;
124
+ const OP_NOT = 0x91;
125
+ const OP_0NOTEQUAL = 0x92;
126
+ // ---------- Arithmetic (64-bit after SCRIPT_VERIFY_64BIT_INTEGERS) ----------
127
+ const OP_ADD = 0x93;
128
+ const OP_SUB = 0x94;
129
+ const OP_MUL = 0x95;
130
+ const OP_DIV = 0x96;
131
+ const OP_MOD = 0x97;
132
+ // ---------- Boolean / numeric comparison ----------
133
+ const OP_BOOLAND = 0x9a;
134
+ const OP_BOOLOR = 0x9b;
135
+ const OP_NUMEQUAL = 0x9c;
136
+ const OP_NUMEQUALVERIFY = 0x9d;
137
+ const OP_NUMNOTEQUAL = 0x9e;
138
+ const OP_LESSTHAN = 0x9f;
139
+ const OP_GREATERTHAN = 0xa0;
140
+ const OP_LESSTHANOREQUAL = 0xa1;
141
+ const OP_GREATERTHANOREQUAL = 0xa2;
142
+ const OP_MIN = 0xa3;
143
+ const OP_MAX = 0xa4;
144
+ const OP_WITHIN = 0xa5;
145
+ // ---------- Crypto ----------
146
+ const OP_RIPEMD160 = 0xa6;
147
+ const OP_SHA1 = 0xa7;
148
+ const OP_SHA256 = 0xa8;
149
+ const OP_HASH160 = 0xa9;
150
+ const OP_HASH256 = 0xaa;
151
+ const OP_CODESEPARATOR = 0xab;
152
+ const OP_CHECKSIG = 0xac;
153
+ const OP_CHECKSIGVERIFY = 0xad;
154
+ const OP_CHECKMULTISIG = 0xae;
155
+ const OP_CHECKMULTISIGVERIFY = 0xaf;
156
+ // ---------- Expansion / NOPs ----------
157
+ // Only the NOPs not aliased by DePIN-Test opcodes are exported as NOPs.
158
+ // OP_NOP2 == OP_CHECKLOCKTIMEVERIFY (0xb1)
159
+ // OP_NOP3 == OP_CHECKSEQUENCEVERIFY (0xb2)
160
+ // OP_NOP4 == OP_CHECKTEMPLATEVERIFY (0xb3)
161
+ // OP_NOP5 == OP_CHECKSIGFROMSTACK (0xb4)
162
+ // OP_NOP6 == OP_TXHASH (0xb5)
163
+ // OP_NOP7 == OP_TXFIELD (0xb6)
164
+ // OP_NOP8 == OP_SPLIT (0xb7)
165
+ const OP_NOP1 = 0xb0;
166
+ const OP_NOP9 = 0xb8;
167
+ const OP_NOP10 = 0xb9;
168
+ // ---------- Locktime ----------
169
+ const OP_CHECKLOCKTIMEVERIFY = 0xb1;
170
+ const OP_CHECKSEQUENCEVERIFY = 0xb2;
171
+ // ---------- Covenants & templates (DePIN-Test) ----------
172
+ const OP_CHECKTEMPLATEVERIFY = 0xb3; // BIP 119
173
+ const OP_CHECKSIGFROMSTACK = 0xb4;
174
+ // ---------- Transaction introspection (DePIN-Test) ----------
175
+ const OP_TXHASH = 0xb5;
176
+ const OP_TXFIELD = 0xb6;
177
+ const OP_TXLOCKTIME = 0xc5;
178
+ const OP_OUTPUTVALUE = 0xcc;
179
+ const OP_OUTPUTSCRIPT = 0xcd;
180
+ const OP_INPUTCOUNT = 0xd0;
181
+ const OP_OUTPUTCOUNT = 0xd1;
182
+ // ---------- Asset introspection (DePIN-Test) ----------
183
+ const OP_OUTPUTASSETFIELD = 0xce;
184
+ const OP_INPUTASSETFIELD = 0xcf;
185
+ const OP_XNA_ASSET = 0xc0;
186
+ // ---------- Reference inputs (DePIN-Test, NIP-017) ----------
187
+ const OP_REFINPUTFIELD = 0xd2;
188
+ const OP_REFINPUTASSETFIELD = 0xd3;
189
+ const OP_REFINPUTCOUNT = 0xd4;
190
+ // ---------- Byte manipulation (DePIN-Test) ----------
191
+ const OP_CAT = 0x7e;
192
+ const OP_SPLIT = 0xb7;
193
+ const OP_REVERSEBYTES = 0xbc;
194
+ // ---------- Selectors for OP_TXFIELD / OP_REFINPUTFIELD ----------
195
+ // Both opcodes share the same selector table (OP_TXFIELD on the spent UTXO,
196
+ // OP_REFINPUTFIELD on an output referenced via vrefin). Valid: 0x01..0x03.
197
+ const TXFIELD_VALUE = 0x01;
198
+ const TXFIELD_AUTHSCRIPT_COMMITMENT = 0x02;
199
+ const TXFIELD_SCRIPTPUBKEY = 0x03;
200
+ // ---------- Bitmask selectors for OP_TXHASH ----------
201
+ // The selector is a single byte where each bit selects which transaction
202
+ // field to include in the double-SHA256. Selector 0x00 is invalid; any
203
+ // non-zero combination is valid. 0xff = all eight fields.
204
+ const TXHASH_VERSION = 0x01;
205
+ const TXHASH_LOCKTIME = 0x02;
206
+ const TXHASH_INPUT_PREVOUTS = 0x04;
207
+ const TXHASH_INPUT_SEQUENCES = 0x08;
208
+ const TXHASH_OUTPUTS = 0x10;
209
+ const TXHASH_CURRENT_PREVOUT = 0x20;
210
+ const TXHASH_CURRENT_SEQUENCE = 0x40;
211
+ const TXHASH_CURRENT_INDEX = 0x80;
212
+ const TXHASH_ALL = 0xff;
213
+ // ---------- Selectors for OP_OUTPUTASSETFIELD / OP_INPUTASSETFIELD / OP_REFINPUTASSETFIELD ----------
214
+ // All three opcodes share the same selector table. Valid range: 0x01..0x07.
215
+ // Selector 0x05 is the boolean "has IPFS" flag; 0x06 is the IPFS hash
216
+ // payload; 0x07 is the asset operation type. (This matches the asset-op
217
+ // encoding in `src/assets/assets.cpp` and the NIP spec §3.1.)
218
+ const ASSETFIELD_NAME = 0x01;
219
+ const ASSETFIELD_AMOUNT = 0x02;
220
+ const ASSETFIELD_UNITS = 0x03;
221
+ const ASSETFIELD_REISSUABLE = 0x04;
222
+ const ASSETFIELD_HAS_IPFS = 0x05;
223
+ const ASSETFIELD_IPFS_HASH = 0x06;
224
+ const ASSETFIELD_TYPE = 0x07;
225
+
226
+ var opcodes = /*#__PURE__*/Object.freeze({
227
+ __proto__: null,
228
+ ASSETFIELD_AMOUNT: ASSETFIELD_AMOUNT,
229
+ ASSETFIELD_HAS_IPFS: ASSETFIELD_HAS_IPFS,
230
+ ASSETFIELD_IPFS_HASH: ASSETFIELD_IPFS_HASH,
231
+ ASSETFIELD_NAME: ASSETFIELD_NAME,
232
+ ASSETFIELD_REISSUABLE: ASSETFIELD_REISSUABLE,
233
+ ASSETFIELD_TYPE: ASSETFIELD_TYPE,
234
+ ASSETFIELD_UNITS: ASSETFIELD_UNITS,
235
+ OP_0: OP_0,
236
+ OP_0NOTEQUAL: OP_0NOTEQUAL,
237
+ OP_1: OP_1,
238
+ OP_10: OP_10,
239
+ OP_11: OP_11,
240
+ OP_12: OP_12,
241
+ OP_13: OP_13,
242
+ OP_14: OP_14,
243
+ OP_15: OP_15,
244
+ OP_16: OP_16,
245
+ OP_1ADD: OP_1ADD,
246
+ OP_1NEGATE: OP_1NEGATE,
247
+ OP_1SUB: OP_1SUB,
248
+ OP_2: OP_2,
249
+ OP_2DROP: OP_2DROP,
250
+ OP_2DUP: OP_2DUP,
251
+ OP_2OVER: OP_2OVER,
252
+ OP_2ROT: OP_2ROT,
253
+ OP_2SWAP: OP_2SWAP,
254
+ OP_3: OP_3,
255
+ OP_3DUP: OP_3DUP,
256
+ OP_4: OP_4,
257
+ OP_5: OP_5,
258
+ OP_6: OP_6,
259
+ OP_7: OP_7,
260
+ OP_8: OP_8,
261
+ OP_9: OP_9,
262
+ OP_ABS: OP_ABS,
263
+ OP_ADD: OP_ADD,
264
+ OP_BOOLAND: OP_BOOLAND,
265
+ OP_BOOLOR: OP_BOOLOR,
266
+ OP_CAT: OP_CAT,
267
+ OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY,
268
+ OP_CHECKMULTISIG: OP_CHECKMULTISIG,
269
+ OP_CHECKMULTISIGVERIFY: OP_CHECKMULTISIGVERIFY,
270
+ OP_CHECKSEQUENCEVERIFY: OP_CHECKSEQUENCEVERIFY,
271
+ OP_CHECKSIG: OP_CHECKSIG,
272
+ OP_CHECKSIGFROMSTACK: OP_CHECKSIGFROMSTACK,
273
+ OP_CHECKSIGVERIFY: OP_CHECKSIGVERIFY,
274
+ OP_CHECKTEMPLATEVERIFY: OP_CHECKTEMPLATEVERIFY,
275
+ OP_CODESEPARATOR: OP_CODESEPARATOR,
276
+ OP_DEPTH: OP_DEPTH,
277
+ OP_DIV: OP_DIV,
278
+ OP_DROP: OP_DROP,
279
+ OP_DUP: OP_DUP,
280
+ OP_ELSE: OP_ELSE,
281
+ OP_ENDIF: OP_ENDIF,
282
+ OP_EQUAL: OP_EQUAL,
283
+ OP_EQUALVERIFY: OP_EQUALVERIFY,
284
+ OP_FALSE: OP_FALSE,
285
+ OP_FROMALTSTACK: OP_FROMALTSTACK,
286
+ OP_GREATERTHAN: OP_GREATERTHAN,
287
+ OP_GREATERTHANOREQUAL: OP_GREATERTHANOREQUAL,
288
+ OP_HASH160: OP_HASH160,
289
+ OP_HASH256: OP_HASH256,
290
+ OP_IF: OP_IF,
291
+ OP_IFDUP: OP_IFDUP,
292
+ OP_INPUTASSETFIELD: OP_INPUTASSETFIELD,
293
+ OP_INPUTCOUNT: OP_INPUTCOUNT,
294
+ OP_LESSTHAN: OP_LESSTHAN,
295
+ OP_LESSTHANOREQUAL: OP_LESSTHANOREQUAL,
296
+ OP_MAX: OP_MAX,
297
+ OP_MIN: OP_MIN,
298
+ OP_MOD: OP_MOD,
299
+ OP_MUL: OP_MUL,
300
+ OP_NEGATE: OP_NEGATE,
301
+ OP_NIP: OP_NIP,
302
+ OP_NOP: OP_NOP,
303
+ OP_NOP1: OP_NOP1,
304
+ OP_NOP10: OP_NOP10,
305
+ OP_NOP9: OP_NOP9,
306
+ OP_NOT: OP_NOT,
307
+ OP_NOTIF: OP_NOTIF,
308
+ OP_NUMEQUAL: OP_NUMEQUAL,
309
+ OP_NUMEQUALVERIFY: OP_NUMEQUALVERIFY,
310
+ OP_NUMNOTEQUAL: OP_NUMNOTEQUAL,
311
+ OP_OUTPUTASSETFIELD: OP_OUTPUTASSETFIELD,
312
+ OP_OUTPUTCOUNT: OP_OUTPUTCOUNT,
313
+ OP_OUTPUTSCRIPT: OP_OUTPUTSCRIPT,
314
+ OP_OUTPUTVALUE: OP_OUTPUTVALUE,
315
+ OP_OVER: OP_OVER,
316
+ OP_PICK: OP_PICK,
317
+ OP_PUSHDATA1: OP_PUSHDATA1,
318
+ OP_PUSHDATA2: OP_PUSHDATA2,
319
+ OP_PUSHDATA4: OP_PUSHDATA4,
320
+ OP_REFINPUTASSETFIELD: OP_REFINPUTASSETFIELD,
321
+ OP_REFINPUTCOUNT: OP_REFINPUTCOUNT,
322
+ OP_REFINPUTFIELD: OP_REFINPUTFIELD,
323
+ OP_RESERVED: OP_RESERVED,
324
+ OP_RETURN: OP_RETURN,
325
+ OP_REVERSEBYTES: OP_REVERSEBYTES,
326
+ OP_RIPEMD160: OP_RIPEMD160,
327
+ OP_ROLL: OP_ROLL,
328
+ OP_ROT: OP_ROT,
329
+ OP_SHA1: OP_SHA1,
330
+ OP_SHA256: OP_SHA256,
331
+ OP_SIZE: OP_SIZE,
332
+ OP_SPLIT: OP_SPLIT,
333
+ OP_SUB: OP_SUB,
334
+ OP_SWAP: OP_SWAP,
335
+ OP_TOALTSTACK: OP_TOALTSTACK,
336
+ OP_TRUE: OP_TRUE,
337
+ OP_TUCK: OP_TUCK,
338
+ OP_TXFIELD: OP_TXFIELD,
339
+ OP_TXHASH: OP_TXHASH,
340
+ OP_TXLOCKTIME: OP_TXLOCKTIME,
341
+ OP_VERIFY: OP_VERIFY,
342
+ OP_WITHIN: OP_WITHIN,
343
+ OP_XNA_ASSET: OP_XNA_ASSET,
344
+ TXFIELD_AUTHSCRIPT_COMMITMENT: TXFIELD_AUTHSCRIPT_COMMITMENT,
345
+ TXFIELD_SCRIPTPUBKEY: TXFIELD_SCRIPTPUBKEY,
346
+ TXFIELD_VALUE: TXFIELD_VALUE,
347
+ TXHASH_ALL: TXHASH_ALL,
348
+ TXHASH_CURRENT_INDEX: TXHASH_CURRENT_INDEX,
349
+ TXHASH_CURRENT_PREVOUT: TXHASH_CURRENT_PREVOUT,
350
+ TXHASH_CURRENT_SEQUENCE: TXHASH_CURRENT_SEQUENCE,
351
+ TXHASH_INPUT_PREVOUTS: TXHASH_INPUT_PREVOUTS,
352
+ TXHASH_INPUT_SEQUENCES: TXHASH_INPUT_SEQUENCES,
353
+ TXHASH_LOCKTIME: TXHASH_LOCKTIME,
354
+ TXHASH_OUTPUTS: TXHASH_OUTPUTS,
355
+ TXHASH_VERSION: TXHASH_VERSION
356
+ });
357
+
358
+ /**
359
+ * Low-level Script assembler. Emits the exact byte layout expected by the
360
+ * Neurai interpreter: pushdata prefixes follow the same rules as Bitcoin
361
+ * (direct push for 1..75 bytes, OP_PUSHDATA1/2/4 otherwise), and integers
362
+ * are minimally-encoded as CScriptNum.
363
+ */
364
+ /**
365
+ * Minimal CScriptNum encoding (Bitcoin consensus rules).
366
+ *
367
+ * - 0 → empty vector
368
+ * - 1..16 → single opcode OP_1..OP_16 (handled in `pushInt`, not here)
369
+ * - -1 → OP_1NEGATE (handled in `pushInt`)
370
+ * - otherwise: sign-magnitude little-endian, with a sign bit on the last byte
371
+ */
372
+ function encodeScriptNum(value) {
373
+ let n = typeof value === 'bigint' ? value : BigInt(value);
374
+ if (n === 0n)
375
+ return new Uint8Array();
376
+ const negative = n < 0n;
377
+ if (negative)
378
+ n = -n;
379
+ const result = [];
380
+ while (n > 0n) {
381
+ result.push(Number(n & 0xffn));
382
+ n >>= 8n;
383
+ }
384
+ // If the most-significant bit is set, add a padding byte so the sign bit
385
+ // is unambiguous. If negative, flip that sign bit instead.
386
+ if (result[result.length - 1] & 0x80) {
387
+ result.push(negative ? 0x80 : 0x00);
388
+ }
389
+ else if (negative) {
390
+ result[result.length - 1] |= 0x80;
391
+ }
392
+ return Uint8Array.from(result);
393
+ }
394
+ /**
395
+ * Emit a pushdata opcode followed by the payload. Chooses the shortest
396
+ * valid encoding.
397
+ *
398
+ * Neurai Script caps stack elements at `MAX_SCRIPT_ELEMENT_SIZE = 520`
399
+ * bytes by default, but NIP-18 raises the cap to
400
+ * `MAX_PQ_SCRIPT_ELEMENT_SIZE = 3072` whenever
401
+ * `SCRIPT_VERIFY_CHECKSIGFROMSTACK` is active (testnet today, mainnet once
402
+ * the CSFS fork lands). The builder here emits pushes up to 3072 bytes so
403
+ * it can target either regime; legacy scripts should stay under 520 bytes
404
+ * per push, and the node will reject anything larger if the CSFS flag is
405
+ * not set during evaluation.
406
+ */
407
+ function pushBytes(data) {
408
+ if (data.length === 0) {
409
+ return Uint8Array.of(OP_0);
410
+ }
411
+ if (data.length <= 75) {
412
+ return concatBytes(Uint8Array.of(data.length), data);
413
+ }
414
+ if (data.length <= 0xff) {
415
+ return concatBytes(Uint8Array.of(0x4c, data.length), data);
416
+ }
417
+ if (data.length <= 3072) {
418
+ return concatBytes(Uint8Array.of(0x4d, data.length & 0xff, (data.length >> 8) & 0xff), data);
419
+ }
420
+ throw new Error(`pushBytes: element of ${data.length} bytes exceeds MAX_PQ_SCRIPT_ELEMENT_SIZE (3072)`);
421
+ }
422
+ /**
423
+ * Emit a minimally-encoded integer push. Uses OP_1NEGATE, OP_0 and OP_1..OP_16
424
+ * when available to match how the node's own templates look on the wire.
425
+ */
426
+ function pushInt(value) {
427
+ const n = typeof value === 'bigint' ? value : BigInt(value);
428
+ if (n === -1n)
429
+ return Uint8Array.of(OP_1NEGATE);
430
+ if (n === 0n)
431
+ return Uint8Array.of(OP_0);
432
+ if (n >= 1n && n <= 16n) {
433
+ return Uint8Array.of(OP_1 + Number(n) - 1);
434
+ }
435
+ return pushBytes(encodeScriptNum(n));
436
+ }
437
+ function pushHex(hex) {
438
+ return pushBytes(hexToBytes(hex));
439
+ }
440
+ /** Fluent assembler for readable script definitions. */
441
+ class ScriptBuilder {
442
+ parts = [];
443
+ op(...opcodes) {
444
+ for (const op of opcodes) {
445
+ if (!Number.isInteger(op) || op < 0 || op > 0xff) {
446
+ throw new Error(`Invalid opcode byte: ${op}`);
447
+ }
448
+ this.parts.push(Uint8Array.of(op));
449
+ }
450
+ return this;
451
+ }
452
+ pushInt(value) {
453
+ this.parts.push(pushInt(value));
454
+ return this;
455
+ }
456
+ pushBytes(data) {
457
+ this.parts.push(pushBytes(data));
458
+ return this;
459
+ }
460
+ pushHex(hex) {
461
+ this.parts.push(pushHex(hex));
462
+ return this;
463
+ }
464
+ raw(bytes) {
465
+ this.parts.push(bytes);
466
+ return this;
467
+ }
468
+ build() {
469
+ return concatBytes(...this.parts);
470
+ }
471
+ buildHex() {
472
+ return bytesToHex(this.build());
473
+ }
474
+ }
475
+
476
+ /**
477
+ * Pay-to-Public-Key-Hash (P2PKH) scriptPubKey.
478
+ * Layout: OP_DUP OP_HASH160 0x14 <20-byte PKH> OP_EQUALVERIFY OP_CHECKSIG
479
+ */
480
+ function encodeP2PKHScriptPubKey(pubKeyHash) {
481
+ if (!(pubKeyHash instanceof Uint8Array) || pubKeyHash.length !== 20) {
482
+ throw new Error('P2PKH pubKeyHash must be a 20-byte Uint8Array');
483
+ }
484
+ return concatBytes(Uint8Array.of(OP_DUP, OP_HASH160, 0x14), pubKeyHash, Uint8Array.of(OP_EQUALVERIFY, OP_CHECKSIG));
485
+ }
486
+
487
+ /**
488
+ * Native segwit v0 Pay-to-Witness-Public-Key-Hash (P2WPKH) scriptPubKey.
489
+ * Layout: OP_0 0x14 <20-byte HASH160(pubKey)>
490
+ *
491
+ * Callers compute HASH160 externally (e.g. via neurai-key / their crypto
492
+ * stack). This helper only encodes the scriptPubKey once the hash is known.
493
+ */
494
+ function encodeP2WPKHScriptPubKey(pubKeyHash) {
495
+ if (!(pubKeyHash instanceof Uint8Array) || pubKeyHash.length !== 20) {
496
+ throw new Error('P2WPKH pubKeyHash must be a 20-byte Uint8Array');
497
+ }
498
+ return concatBytes(Uint8Array.of(OP_0, 0x14), pubKeyHash);
499
+ }
500
+
501
+ /**
502
+ * Native segwit v0 Pay-to-Witness-Script-Hash (P2WSH) scriptPubKey.
503
+ * Layout: OP_0 0x20 <32-byte SHA256(witnessScript)>
504
+ *
505
+ * This helper takes the SHA256 digest of the witness script directly. The
506
+ * SHA256 is computed externally by the caller's crypto stack (kept out of
507
+ * this library to avoid a hash dependency).
508
+ */
509
+ function encodeP2WSHScriptPubKey(witnessScriptSha256) {
510
+ if (!(witnessScriptSha256 instanceof Uint8Array) || witnessScriptSha256.length !== 32) {
511
+ throw new Error('P2WSH witnessScriptSha256 must be a 32-byte Uint8Array');
512
+ }
513
+ return concatBytes(Uint8Array.of(OP_0, 0x20), witnessScriptSha256);
514
+ }
515
+
516
+ /**
517
+ * AuthScript (witness v1) scriptPubKey + witness-stack builders.
518
+ *
519
+ * AuthScript outputs encode a 32-byte commitment in a witness v1 program:
520
+ * scriptPubKey = OP_1 0x20 <32-byte program>
521
+ *
522
+ * The program is `HASH160`/`SHA256` over a descriptor that depends on the
523
+ * `auth_type` byte carried as the first witness-stack element at spend time.
524
+ * This library only assembles the stack; computing the descriptor/commitment
525
+ * and producing the signature live in neurai-key / neurai-sign-transaction.
526
+ *
527
+ * Auth type values (authoritative: Neurai `src/script/interpreter.cpp`,
528
+ * cross-checked against `lib/neurai-key/src/shared/address.ts`):
529
+ *
530
+ * 0x00 NoAuth — no signature; spend gated only by witnessScript
531
+ * 0x01 PQ — ML-DSA-44 signature (post-quantum)
532
+ * 0x02 Legacy — secp256k1 ECDSA signature (classic)
533
+ * 0x03 RefScript — NIP-015 reference-script spend (future)
534
+ *
535
+ * Witness stack (exact order consumed by the interpreter):
536
+ * [ auth_type, sig, pubkey, arg0, ..., argN, witnessScript ]
537
+ *
538
+ * NoAuth and RefScript spends omit the `sig`/`pubkey` items.
539
+ */
540
+ const AUTHSCRIPT_NOAUTH = 0x00;
541
+ const AUTHSCRIPT_PQ = 0x01;
542
+ const AUTHSCRIPT_LEGACY = 0x02;
543
+ /** NIP-015: reference-script spend mode. Not yet activated in consensus. */
544
+ const AUTHSCRIPT_REF = 0x03;
545
+ /** Cap for PQ signature / pubkey pushes under NIP-018 (3072 B). */
546
+ const MAX_PQ_PUSH = 3072;
547
+ function encodeAuthScriptScriptPubKey(program) {
548
+ if (!(program instanceof Uint8Array) || program.length !== 32) {
549
+ throw new Error('AuthScript program must be a 32-byte Uint8Array');
550
+ }
551
+ return concatBytes(Uint8Array.of(OP_1, 0x20), program);
552
+ }
553
+ function assertWitnessScript(ws) {
554
+ if (!(ws instanceof Uint8Array) || ws.length === 0) {
555
+ throw new Error('witnessScript must be a non-empty Uint8Array');
556
+ }
557
+ }
558
+ function assertArgs(args) {
559
+ if (args == null)
560
+ return;
561
+ if (!Array.isArray(args)) {
562
+ throw new Error('args must be an array of Uint8Array');
563
+ }
564
+ for (let i = 0; i < args.length; i += 1) {
565
+ if (!(args[i] instanceof Uint8Array)) {
566
+ throw new Error(`args[${i}] must be a Uint8Array`);
567
+ }
568
+ }
569
+ }
570
+ /**
571
+ * Build the witness stack for a legacy ECDSA AuthScript spend.
572
+ *
573
+ * Returns an array of raw stack elements. Serialization of the witness
574
+ * (compact-size item count + per-item length-prefixes) is the caller's
575
+ * responsibility — neurai-create-transaction handles it at tx-assembly time.
576
+ */
577
+ function buildAuthScriptWitnessLegacy(input) {
578
+ if (!(input.signature instanceof Uint8Array) || input.signature.length === 0) {
579
+ throw new Error('signature must be a non-empty Uint8Array');
580
+ }
581
+ if (!(input.pubKey instanceof Uint8Array) ||
582
+ (input.pubKey.length !== 33 && input.pubKey.length !== 65)) {
583
+ throw new Error('pubKey must be a compressed (33B) or uncompressed (65B) secp256k1 key');
584
+ }
585
+ assertArgs(input.args);
586
+ assertWitnessScript(input.witnessScript);
587
+ return [
588
+ Uint8Array.of(AUTHSCRIPT_LEGACY),
589
+ input.signature,
590
+ input.pubKey,
591
+ ...(input.args ?? []),
592
+ input.witnessScript
593
+ ];
594
+ }
595
+ /**
596
+ * Build the witness stack for a PQ (ML-DSA-44) AuthScript spend.
597
+ * NIP-018 must be active: both signature and pubKey are pushed as single
598
+ * stack elements and may each be up to 3072 B.
599
+ */
600
+ function buildAuthScriptWitnessPQ(input) {
601
+ if (!(input.signature instanceof Uint8Array) || input.signature.length === 0) {
602
+ throw new Error('signature must be a non-empty Uint8Array');
603
+ }
604
+ if (input.signature.length > MAX_PQ_PUSH) {
605
+ throw new Error(`signature of ${input.signature.length} bytes exceeds MAX_PQ_SCRIPT_ELEMENT_SIZE (${MAX_PQ_PUSH})`);
606
+ }
607
+ if (!(input.pubKey instanceof Uint8Array) || input.pubKey.length === 0) {
608
+ throw new Error('pubKey must be a non-empty Uint8Array');
609
+ }
610
+ if (input.pubKey.length > MAX_PQ_PUSH) {
611
+ throw new Error(`pubKey of ${input.pubKey.length} bytes exceeds MAX_PQ_SCRIPT_ELEMENT_SIZE (${MAX_PQ_PUSH})`);
612
+ }
613
+ assertArgs(input.args);
614
+ assertWitnessScript(input.witnessScript);
615
+ return [
616
+ Uint8Array.of(AUTHSCRIPT_PQ),
617
+ input.signature,
618
+ input.pubKey,
619
+ ...(input.args ?? []),
620
+ input.witnessScript
621
+ ];
622
+ }
623
+ /**
624
+ * Build the witness stack for a NoAuth AuthScript spend. The spend is gated
625
+ * by the witnessScript alone (covenants, hash-locks, time-locks, ...); no
626
+ * signature or public key is carried.
627
+ */
628
+ function buildAuthScriptWitnessNoAuth(input) {
629
+ assertArgs(input.args);
630
+ assertWitnessScript(input.witnessScript);
631
+ return [
632
+ Uint8Array.of(AUTHSCRIPT_NOAUTH),
633
+ ...(input.args ?? []),
634
+ input.witnessScript
635
+ ];
636
+ }
637
+ /**
638
+ * Build the witness stack for a NIP-015 reference-script spend. The last
639
+ * item is the 4-byte little-endian index into `tx.vrefin` that locates the
640
+ * reference-script carrier output; the interpreter resolves the `refScript`
641
+ * from that carrier at validation time.
642
+ *
643
+ * NOTE: NIP-015 is not yet activated in consensus. This builder emits the
644
+ * spec-conformant witness for forward compatibility and testnet experiments.
645
+ */
646
+ function buildAuthScriptWitnessRef(input) {
647
+ if (!Number.isInteger(input.refIndex) || input.refIndex < 0 || input.refIndex > 0xffffffff) {
648
+ throw new Error('refIndex must be a uint32 (0 .. 2^32 - 1)');
649
+ }
650
+ assertArgs(input.args);
651
+ const refLocator = new Uint8Array(4);
652
+ const dv = new DataView(refLocator.buffer);
653
+ dv.setUint32(0, input.refIndex, /* little-endian */ true);
654
+ return [
655
+ Uint8Array.of(AUTHSCRIPT_REF),
656
+ ...(input.args ?? []),
657
+ refLocator
658
+ ];
659
+ }
660
+
661
+ /**
662
+ * Provably-unspendable OP_RETURN (null-data) output scripts.
663
+ * Layout: OP_RETURN <push> [<push> ...]
664
+ *
665
+ * Neurai inherits the Bitcoin Core standard policy cap of 80 bytes of
666
+ * payload for a relayed null-data output. Outputs over that cap are still
667
+ * consensus-valid but will not be relayed by default mempool policy; use
668
+ * the `allowNonStandard` option to opt in explicitly.
669
+ */
670
+ const NULLDATA_STANDARD_MAX_SIZE = 80;
671
+ function encodeNullDataScript(payload, options = {}) {
672
+ const payloads = payload instanceof Uint8Array ? [payload] : payload;
673
+ if (!Array.isArray(payloads) || payloads.length === 0) {
674
+ throw new Error('payload must be a Uint8Array or a non-empty array of Uint8Array');
675
+ }
676
+ let totalPayload = 0;
677
+ for (let i = 0; i < payloads.length; i += 1) {
678
+ const p = payloads[i];
679
+ if (!(p instanceof Uint8Array)) {
680
+ throw new Error(`payload[${i}] must be a Uint8Array`);
681
+ }
682
+ totalPayload += p.length;
683
+ }
684
+ if (!options.allowNonStandard && totalPayload > NULLDATA_STANDARD_MAX_SIZE) {
685
+ throw new Error(`nulldata payload of ${totalPayload} bytes exceeds standard cap ${NULLDATA_STANDARD_MAX_SIZE}; set allowNonStandard=true to override`);
686
+ }
687
+ const parts = [Uint8Array.of(OP_RETURN)];
688
+ for (const p of payloads)
689
+ parts.push(pushBytes(p));
690
+ return concatBytes(...parts);
691
+ }
692
+
693
+ /**
694
+ * Classic bare m-of-n multisig via OP_CHECKMULTISIG, plus the P2SH wrapper
695
+ * that is normally used in practice.
696
+ *
697
+ * redeemScript = <m> <pubkey_1> ... <pubkey_n> <n> OP_CHECKMULTISIG
698
+ * P2SH spk = OP_HASH160 0x14 <HASH160(redeemScript)> OP_EQUAL
699
+ *
700
+ * OP_CHECKMULTISIG caps n at 20 pubkeys (see `MAX_PUBKEYS_PER_MULTISIG` in
701
+ * the Neurai interpreter). Bare multisig outputs are still consensus-valid
702
+ * but non-standard for relay; the P2SH wrapping is what mempool accepts.
703
+ */
704
+ const MULTISIG_MAX_PUBKEYS = 20;
705
+ function assertPubKey(pk, idx) {
706
+ if (!(pk instanceof Uint8Array) || (pk.length !== 33 && pk.length !== 65)) {
707
+ throw new Error(`pubKey[${idx}] must be 33 or 65 bytes (got ${pk?.length})`);
708
+ }
709
+ }
710
+ function encodeMultisigRedeemScript({ m, pubKeys }) {
711
+ if (!Array.isArray(pubKeys) || pubKeys.length === 0) {
712
+ throw new Error('pubKeys must be a non-empty array');
713
+ }
714
+ if (pubKeys.length > MULTISIG_MAX_PUBKEYS) {
715
+ throw new Error(`pubKeys length ${pubKeys.length} exceeds OP_CHECKMULTISIG cap (${MULTISIG_MAX_PUBKEYS})`);
716
+ }
717
+ if (!Number.isInteger(m) || m < 1 || m > pubKeys.length) {
718
+ throw new Error(`m must be an integer in [1, ${pubKeys.length}] (got ${m})`);
719
+ }
720
+ for (let i = 0; i < pubKeys.length; i += 1)
721
+ assertPubKey(pubKeys[i], i);
722
+ const parts = [pushInt(m)];
723
+ for (const pk of pubKeys)
724
+ parts.push(pushBytes(pk));
725
+ parts.push(pushInt(pubKeys.length));
726
+ parts.push(Uint8Array.of(OP_CHECKMULTISIG));
727
+ return concatBytes(...parts);
728
+ }
729
+ function encodeMultisigRedeemScriptHex(params) {
730
+ return bytesToHex(encodeMultisigRedeemScript(params));
731
+ }
732
+ /**
733
+ * P2SH scriptPubKey wrapping any redeem script. Pass the 20-byte HASH160 of
734
+ * the redeem script (RIPEMD160(SHA256(redeemScript))) — compute it
735
+ * externally via the caller's crypto stack.
736
+ */
737
+ function encodeP2SHScriptPubKey(redeemScriptHash160) {
738
+ if (!(redeemScriptHash160 instanceof Uint8Array) || redeemScriptHash160.length !== 20) {
739
+ throw new Error('redeemScriptHash160 must be a 20-byte Uint8Array');
740
+ }
741
+ return concatBytes(Uint8Array.of(OP_HASH160, 0x14), redeemScriptHash160, Uint8Array.of(OP_EQUAL));
742
+ }
743
+
744
+ // base-x encoding / decoding
745
+ // Copyright (c) 2018 base-x contributors
746
+ // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
747
+ // Distributed under the MIT software license, see the accompanying
748
+ // file LICENSE or http://www.opensource.org/licenses/mit-license.php.
749
+ function base (ALPHABET) {
750
+ if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }
751
+ const BASE_MAP = new Uint8Array(256);
752
+ for (let j = 0; j < BASE_MAP.length; j++) {
753
+ BASE_MAP[j] = 255;
754
+ }
755
+ for (let i = 0; i < ALPHABET.length; i++) {
756
+ const x = ALPHABET.charAt(i);
757
+ const xc = x.charCodeAt(0);
758
+ if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }
759
+ BASE_MAP[xc] = i;
760
+ }
761
+ const BASE = ALPHABET.length;
762
+ const LEADER = ALPHABET.charAt(0);
763
+ const FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
764
+ const iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
765
+ function encode (source) {
766
+ // eslint-disable-next-line no-empty
767
+ if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {
768
+ source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
769
+ } else if (Array.isArray(source)) {
770
+ source = Uint8Array.from(source);
771
+ }
772
+ if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }
773
+ if (source.length === 0) { return '' }
774
+ // Skip & count leading zeroes.
775
+ let zeroes = 0;
776
+ let length = 0;
777
+ let pbegin = 0;
778
+ const pend = source.length;
779
+ while (pbegin !== pend && source[pbegin] === 0) {
780
+ pbegin++;
781
+ zeroes++;
782
+ }
783
+ // Allocate enough space in big-endian base58 representation.
784
+ const size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
785
+ const b58 = new Uint8Array(size);
786
+ // Process the bytes.
787
+ while (pbegin !== pend) {
788
+ let carry = source[pbegin];
789
+ // Apply "b58 = b58 * 256 + ch".
790
+ let i = 0;
791
+ for (let it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
792
+ carry += (256 * b58[it1]) >>> 0;
793
+ b58[it1] = (carry % BASE) >>> 0;
794
+ carry = (carry / BASE) >>> 0;
795
+ }
796
+ if (carry !== 0) { throw new Error('Non-zero carry') }
797
+ length = i;
798
+ pbegin++;
799
+ }
800
+ // Skip leading zeroes in base58 result.
801
+ let it2 = size - length;
802
+ while (it2 !== size && b58[it2] === 0) {
803
+ it2++;
804
+ }
805
+ // Translate the result into a string.
806
+ let str = LEADER.repeat(zeroes);
807
+ for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }
808
+ return str
809
+ }
810
+ function decodeUnsafe (source) {
811
+ if (typeof source !== 'string') { throw new TypeError('Expected String') }
812
+ if (source.length === 0) { return new Uint8Array() }
813
+ let psz = 0;
814
+ // Skip and count leading '1's.
815
+ let zeroes = 0;
816
+ let length = 0;
817
+ while (source[psz] === LEADER) {
818
+ zeroes++;
819
+ psz++;
820
+ }
821
+ // Allocate enough space in big-endian base256 representation.
822
+ const size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
823
+ const b256 = new Uint8Array(size);
824
+ // Process the characters.
825
+ while (psz < source.length) {
826
+ // Find code of next character
827
+ const charCode = source.charCodeAt(psz);
828
+ // Base map can not be indexed using char code
829
+ if (charCode > 255) { return }
830
+ // Decode character
831
+ let carry = BASE_MAP[charCode];
832
+ // Invalid character
833
+ if (carry === 255) { return }
834
+ let i = 0;
835
+ for (let it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
836
+ carry += (BASE * b256[it3]) >>> 0;
837
+ b256[it3] = (carry % 256) >>> 0;
838
+ carry = (carry / 256) >>> 0;
839
+ }
840
+ if (carry !== 0) { throw new Error('Non-zero carry') }
841
+ length = i;
842
+ psz++;
843
+ }
844
+ // Skip leading zeroes in b256.
845
+ let it4 = size - length;
846
+ while (it4 !== size && b256[it4] === 0) {
847
+ it4++;
848
+ }
849
+ const vch = new Uint8Array(zeroes + (size - it4));
850
+ let j = zeroes;
851
+ while (it4 !== size) {
852
+ vch[j++] = b256[it4++];
853
+ }
854
+ return vch
855
+ }
856
+ function decode (string) {
857
+ const buffer = decodeUnsafe(string);
858
+ if (buffer) { return buffer }
859
+ throw new Error('Non-base' + BASE + ' character')
860
+ }
861
+ return {
862
+ encode,
863
+ decodeUnsafe,
864
+ decode
865
+ }
866
+ }
867
+
868
+ var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
869
+ var base58 = base(ALPHABET);
870
+
871
+ var dist = {};
872
+
873
+ var hasRequiredDist;
874
+
875
+ function requireDist () {
876
+ if (hasRequiredDist) return dist;
877
+ hasRequiredDist = 1;
878
+ Object.defineProperty(dist, "__esModule", { value: true });
879
+ dist.bech32m = dist.bech32 = void 0;
880
+ const ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';
881
+ const ALPHABET_MAP = {};
882
+ for (let z = 0; z < ALPHABET.length; z++) {
883
+ const x = ALPHABET.charAt(z);
884
+ ALPHABET_MAP[x] = z;
885
+ }
886
+ function polymodStep(pre) {
887
+ const b = pre >> 25;
888
+ return (((pre & 0x1ffffff) << 5) ^
889
+ (-((b >> 0) & 1) & 0x3b6a57b2) ^
890
+ (-((b >> 1) & 1) & 0x26508e6d) ^
891
+ (-((b >> 2) & 1) & 0x1ea119fa) ^
892
+ (-((b >> 3) & 1) & 0x3d4233dd) ^
893
+ (-((b >> 4) & 1) & 0x2a1462b3));
894
+ }
895
+ function prefixChk(prefix) {
896
+ let chk = 1;
897
+ for (let i = 0; i < prefix.length; ++i) {
898
+ const c = prefix.charCodeAt(i);
899
+ if (c < 33 || c > 126)
900
+ return 'Invalid prefix (' + prefix + ')';
901
+ chk = polymodStep(chk) ^ (c >> 5);
902
+ }
903
+ chk = polymodStep(chk);
904
+ for (let i = 0; i < prefix.length; ++i) {
905
+ const v = prefix.charCodeAt(i);
906
+ chk = polymodStep(chk) ^ (v & 0x1f);
907
+ }
908
+ return chk;
909
+ }
910
+ function convert(data, inBits, outBits, pad) {
911
+ let value = 0;
912
+ let bits = 0;
913
+ const maxV = (1 << outBits) - 1;
914
+ const result = [];
915
+ for (let i = 0; i < data.length; ++i) {
916
+ value = (value << inBits) | data[i];
917
+ bits += inBits;
918
+ while (bits >= outBits) {
919
+ bits -= outBits;
920
+ result.push((value >> bits) & maxV);
921
+ }
922
+ }
923
+ if (pad) {
924
+ if (bits > 0) {
925
+ result.push((value << (outBits - bits)) & maxV);
926
+ }
927
+ }
928
+ else {
929
+ if (bits >= inBits)
930
+ return 'Excess padding';
931
+ if ((value << (outBits - bits)) & maxV)
932
+ return 'Non-zero padding';
933
+ }
934
+ return result;
935
+ }
936
+ function toWords(bytes) {
937
+ return convert(bytes, 8, 5, true);
938
+ }
939
+ function fromWordsUnsafe(words) {
940
+ const res = convert(words, 5, 8, false);
941
+ if (Array.isArray(res))
942
+ return res;
943
+ }
944
+ function fromWords(words) {
945
+ const res = convert(words, 5, 8, false);
946
+ if (Array.isArray(res))
947
+ return res;
948
+ throw new Error(res);
949
+ }
950
+ function getLibraryFromEncoding(encoding) {
951
+ let ENCODING_CONST;
952
+ if (encoding === 'bech32') {
953
+ ENCODING_CONST = 1;
954
+ }
955
+ else {
956
+ ENCODING_CONST = 0x2bc830a3;
957
+ }
958
+ function encode(prefix, words, LIMIT) {
959
+ LIMIT = LIMIT || 90;
960
+ if (prefix.length + 7 + words.length > LIMIT)
961
+ throw new TypeError('Exceeds length limit');
962
+ prefix = prefix.toLowerCase();
963
+ // determine chk mod
964
+ let chk = prefixChk(prefix);
965
+ if (typeof chk === 'string')
966
+ throw new Error(chk);
967
+ let result = prefix + '1';
968
+ for (let i = 0; i < words.length; ++i) {
969
+ const x = words[i];
970
+ if (x >> 5 !== 0)
971
+ throw new Error('Non 5-bit word');
972
+ chk = polymodStep(chk) ^ x;
973
+ result += ALPHABET.charAt(x);
974
+ }
975
+ for (let i = 0; i < 6; ++i) {
976
+ chk = polymodStep(chk);
977
+ }
978
+ chk ^= ENCODING_CONST;
979
+ for (let i = 0; i < 6; ++i) {
980
+ const v = (chk >> ((5 - i) * 5)) & 0x1f;
981
+ result += ALPHABET.charAt(v);
982
+ }
983
+ return result;
984
+ }
985
+ function __decode(str, LIMIT) {
986
+ LIMIT = LIMIT || 90;
987
+ if (str.length < 8)
988
+ return str + ' too short';
989
+ if (str.length > LIMIT)
990
+ return 'Exceeds length limit';
991
+ // don't allow mixed case
992
+ const lowered = str.toLowerCase();
993
+ const uppered = str.toUpperCase();
994
+ if (str !== lowered && str !== uppered)
995
+ return 'Mixed-case string ' + str;
996
+ str = lowered;
997
+ const split = str.lastIndexOf('1');
998
+ if (split === -1)
999
+ return 'No separator character for ' + str;
1000
+ if (split === 0)
1001
+ return 'Missing prefix for ' + str;
1002
+ const prefix = str.slice(0, split);
1003
+ const wordChars = str.slice(split + 1);
1004
+ if (wordChars.length < 6)
1005
+ return 'Data too short';
1006
+ let chk = prefixChk(prefix);
1007
+ if (typeof chk === 'string')
1008
+ return chk;
1009
+ const words = [];
1010
+ for (let i = 0; i < wordChars.length; ++i) {
1011
+ const c = wordChars.charAt(i);
1012
+ const v = ALPHABET_MAP[c];
1013
+ if (v === undefined)
1014
+ return 'Unknown character ' + c;
1015
+ chk = polymodStep(chk) ^ v;
1016
+ // not in the checksum?
1017
+ if (i + 6 >= wordChars.length)
1018
+ continue;
1019
+ words.push(v);
1020
+ }
1021
+ if (chk !== ENCODING_CONST)
1022
+ return 'Invalid checksum for ' + str;
1023
+ return { prefix, words };
1024
+ }
1025
+ function decodeUnsafe(str, LIMIT) {
1026
+ const res = __decode(str, LIMIT);
1027
+ if (typeof res === 'object')
1028
+ return res;
1029
+ }
1030
+ function decode(str, LIMIT) {
1031
+ const res = __decode(str, LIMIT);
1032
+ if (typeof res === 'object')
1033
+ return res;
1034
+ throw new Error(res);
1035
+ }
1036
+ return {
1037
+ decodeUnsafe,
1038
+ decode,
1039
+ encode,
1040
+ toWords,
1041
+ fromWordsUnsafe,
1042
+ fromWords,
1043
+ };
1044
+ }
1045
+ dist.bech32 = getLibraryFromEncoding('bech32');
1046
+ dist.bech32m = getLibraryFromEncoding('bech32m');
1047
+ return dist;
1048
+ }
1049
+
1050
+ var distExports = requireDist();
1051
+
1052
+ /**
1053
+ * Utilities for hex, bytes, CSPRNG.
1054
+ * @module
1055
+ */
1056
+ /*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
1057
+ // We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
1058
+ // node.js versions earlier than v19 don't declare it in global scope.
1059
+ // For node.js, package.json#exports field mapping rewrites import
1060
+ // from `crypto` to `cryptoNode`, which imports native module.
1061
+ // Makes the utils un-importable in browsers without a bundler.
1062
+ // Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
1063
+ /** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
1064
+ function isBytes(a) {
1065
+ return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
1066
+ }
1067
+ /** Asserts something is Uint8Array. */
1068
+ function abytes(b, ...lengths) {
1069
+ if (!isBytes(b))
1070
+ throw new Error('Uint8Array expected');
1071
+ if (lengths.length > 0 && !lengths.includes(b.length))
1072
+ throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
1073
+ }
1074
+ /** Asserts a hash instance has not been destroyed / finished */
1075
+ function aexists(instance, checkFinished = true) {
1076
+ if (instance.destroyed)
1077
+ throw new Error('Hash instance has been destroyed');
1078
+ if (checkFinished && instance.finished)
1079
+ throw new Error('Hash#digest() has already been called');
1080
+ }
1081
+ /** Asserts output is properly-sized byte array */
1082
+ function aoutput(out, instance) {
1083
+ abytes(out);
1084
+ const min = instance.outputLen;
1085
+ if (out.length < min) {
1086
+ throw new Error('digestInto() expects output buffer of length at least ' + min);
1087
+ }
1088
+ }
1089
+ /** Zeroize a byte array. Warning: JS provides no guarantees. */
1090
+ function clean(...arrays) {
1091
+ for (let i = 0; i < arrays.length; i++) {
1092
+ arrays[i].fill(0);
1093
+ }
1094
+ }
1095
+ /** Create DataView of an array for easy byte-level manipulation. */
1096
+ function createView(arr) {
1097
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
1098
+ }
1099
+ /** The rotate right (circular right shift) operation for uint32 */
1100
+ function rotr(word, shift) {
1101
+ return (word << (32 - shift)) | (word >>> shift);
1102
+ }
1103
+ /**
1104
+ * Converts string to bytes using UTF8 encoding.
1105
+ * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
1106
+ */
1107
+ function utf8ToBytes(str) {
1108
+ if (typeof str !== 'string')
1109
+ throw new Error('string expected');
1110
+ return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
1111
+ }
1112
+ /**
1113
+ * Normalizes (non-hex) string or Uint8Array to Uint8Array.
1114
+ * Warning: when Uint8Array is passed, it would NOT get copied.
1115
+ * Keep in mind for future mutable operations.
1116
+ */
1117
+ function toBytes(data) {
1118
+ if (typeof data === 'string')
1119
+ data = utf8ToBytes(data);
1120
+ abytes(data);
1121
+ return data;
1122
+ }
1123
+ /** For runtime check if class implements interface */
1124
+ class Hash {
1125
+ }
1126
+ /** Wraps hash function, creating an interface on top of it */
1127
+ function createHasher(hashCons) {
1128
+ const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
1129
+ const tmp = hashCons();
1130
+ hashC.outputLen = tmp.outputLen;
1131
+ hashC.blockLen = tmp.blockLen;
1132
+ hashC.create = () => hashCons();
1133
+ return hashC;
1134
+ }
1135
+
1136
+ /**
1137
+ * Internal Merkle-Damgard hash utils.
1138
+ * @module
1139
+ */
1140
+ /** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
1141
+ function setBigUint64(view, byteOffset, value, isLE) {
1142
+ if (typeof view.setBigUint64 === 'function')
1143
+ return view.setBigUint64(byteOffset, value, isLE);
1144
+ const _32n = BigInt(32);
1145
+ const _u32_max = BigInt(0xffffffff);
1146
+ const wh = Number((value >> _32n) & _u32_max);
1147
+ const wl = Number(value & _u32_max);
1148
+ const h = isLE ? 4 : 0;
1149
+ const l = isLE ? 0 : 4;
1150
+ view.setUint32(byteOffset + h, wh, isLE);
1151
+ view.setUint32(byteOffset + l, wl, isLE);
1152
+ }
1153
+ /** Choice: a ? b : c */
1154
+ function Chi(a, b, c) {
1155
+ return (a & b) ^ (~a & c);
1156
+ }
1157
+ /** Majority function, true if any two inputs is true. */
1158
+ function Maj(a, b, c) {
1159
+ return (a & b) ^ (a & c) ^ (b & c);
1160
+ }
1161
+ /**
1162
+ * Merkle-Damgard hash construction base class.
1163
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
1164
+ */
1165
+ class HashMD extends Hash {
1166
+ constructor(blockLen, outputLen, padOffset, isLE) {
1167
+ super();
1168
+ this.finished = false;
1169
+ this.length = 0;
1170
+ this.pos = 0;
1171
+ this.destroyed = false;
1172
+ this.blockLen = blockLen;
1173
+ this.outputLen = outputLen;
1174
+ this.padOffset = padOffset;
1175
+ this.isLE = isLE;
1176
+ this.buffer = new Uint8Array(blockLen);
1177
+ this.view = createView(this.buffer);
1178
+ }
1179
+ update(data) {
1180
+ aexists(this);
1181
+ data = toBytes(data);
1182
+ abytes(data);
1183
+ const { view, buffer, blockLen } = this;
1184
+ const len = data.length;
1185
+ for (let pos = 0; pos < len;) {
1186
+ const take = Math.min(blockLen - this.pos, len - pos);
1187
+ // Fast path: we have at least one block in input, cast it to view and process
1188
+ if (take === blockLen) {
1189
+ const dataView = createView(data);
1190
+ for (; blockLen <= len - pos; pos += blockLen)
1191
+ this.process(dataView, pos);
1192
+ continue;
1193
+ }
1194
+ buffer.set(data.subarray(pos, pos + take), this.pos);
1195
+ this.pos += take;
1196
+ pos += take;
1197
+ if (this.pos === blockLen) {
1198
+ this.process(view, 0);
1199
+ this.pos = 0;
1200
+ }
1201
+ }
1202
+ this.length += data.length;
1203
+ this.roundClean();
1204
+ return this;
1205
+ }
1206
+ digestInto(out) {
1207
+ aexists(this);
1208
+ aoutput(out, this);
1209
+ this.finished = true;
1210
+ // Padding
1211
+ // We can avoid allocation of buffer for padding completely if it
1212
+ // was previously not allocated here. But it won't change performance.
1213
+ const { buffer, view, blockLen, isLE } = this;
1214
+ let { pos } = this;
1215
+ // append the bit '1' to the message
1216
+ buffer[pos++] = 0b10000000;
1217
+ clean(this.buffer.subarray(pos));
1218
+ // we have less than padOffset left in buffer, so we cannot put length in
1219
+ // current block, need process it and pad again
1220
+ if (this.padOffset > blockLen - pos) {
1221
+ this.process(view, 0);
1222
+ pos = 0;
1223
+ }
1224
+ // Pad until full block byte with zeros
1225
+ for (let i = pos; i < blockLen; i++)
1226
+ buffer[i] = 0;
1227
+ // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
1228
+ // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
1229
+ // So we just write lowest 64 bits of that value.
1230
+ setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
1231
+ this.process(view, 0);
1232
+ const oview = createView(out);
1233
+ const len = this.outputLen;
1234
+ // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
1235
+ if (len % 4)
1236
+ throw new Error('_sha2: outputLen should be aligned to 32bit');
1237
+ const outLen = len / 4;
1238
+ const state = this.get();
1239
+ if (outLen > state.length)
1240
+ throw new Error('_sha2: outputLen bigger than state');
1241
+ for (let i = 0; i < outLen; i++)
1242
+ oview.setUint32(4 * i, state[i], isLE);
1243
+ }
1244
+ digest() {
1245
+ const { buffer, outputLen } = this;
1246
+ this.digestInto(buffer);
1247
+ const res = buffer.slice(0, outputLen);
1248
+ this.destroy();
1249
+ return res;
1250
+ }
1251
+ _cloneInto(to) {
1252
+ to || (to = new this.constructor());
1253
+ to.set(...this.get());
1254
+ const { blockLen, buffer, length, finished, destroyed, pos } = this;
1255
+ to.destroyed = destroyed;
1256
+ to.finished = finished;
1257
+ to.length = length;
1258
+ to.pos = pos;
1259
+ if (length % blockLen)
1260
+ to.buffer.set(buffer);
1261
+ return to;
1262
+ }
1263
+ clone() {
1264
+ return this._cloneInto();
1265
+ }
1266
+ }
1267
+ /**
1268
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
1269
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
1270
+ */
1271
+ /** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
1272
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
1273
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
1274
+ ]);
1275
+
1276
+ /**
1277
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
1278
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
1279
+ * Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
1280
+ * [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
1281
+ * @module
1282
+ */
1283
+ /**
1284
+ * Round constants:
1285
+ * First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
1286
+ */
1287
+ // prettier-ignore
1288
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
1289
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
1290
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
1291
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
1292
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
1293
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
1294
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
1295
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
1296
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
1297
+ ]);
1298
+ /** Reusable temporary buffer. "W" comes straight from spec. */
1299
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
1300
+ class SHA256 extends HashMD {
1301
+ constructor(outputLen = 32) {
1302
+ super(64, outputLen, 8, false);
1303
+ // We cannot use array here since array allows indexing by variable
1304
+ // which means optimizer/compiler cannot use registers.
1305
+ this.A = SHA256_IV[0] | 0;
1306
+ this.B = SHA256_IV[1] | 0;
1307
+ this.C = SHA256_IV[2] | 0;
1308
+ this.D = SHA256_IV[3] | 0;
1309
+ this.E = SHA256_IV[4] | 0;
1310
+ this.F = SHA256_IV[5] | 0;
1311
+ this.G = SHA256_IV[6] | 0;
1312
+ this.H = SHA256_IV[7] | 0;
1313
+ }
1314
+ get() {
1315
+ const { A, B, C, D, E, F, G, H } = this;
1316
+ return [A, B, C, D, E, F, G, H];
1317
+ }
1318
+ // prettier-ignore
1319
+ set(A, B, C, D, E, F, G, H) {
1320
+ this.A = A | 0;
1321
+ this.B = B | 0;
1322
+ this.C = C | 0;
1323
+ this.D = D | 0;
1324
+ this.E = E | 0;
1325
+ this.F = F | 0;
1326
+ this.G = G | 0;
1327
+ this.H = H | 0;
1328
+ }
1329
+ process(view, offset) {
1330
+ // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
1331
+ for (let i = 0; i < 16; i++, offset += 4)
1332
+ SHA256_W[i] = view.getUint32(offset, false);
1333
+ for (let i = 16; i < 64; i++) {
1334
+ const W15 = SHA256_W[i - 15];
1335
+ const W2 = SHA256_W[i - 2];
1336
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
1337
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
1338
+ SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
1339
+ }
1340
+ // Compression function main loop, 64 rounds
1341
+ let { A, B, C, D, E, F, G, H } = this;
1342
+ for (let i = 0; i < 64; i++) {
1343
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
1344
+ const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
1345
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
1346
+ const T2 = (sigma0 + Maj(A, B, C)) | 0;
1347
+ H = G;
1348
+ G = F;
1349
+ F = E;
1350
+ E = (D + T1) | 0;
1351
+ D = C;
1352
+ C = B;
1353
+ B = A;
1354
+ A = (T1 + T2) | 0;
1355
+ }
1356
+ // Add the compressed chunk to the current hash value
1357
+ A = (A + this.A) | 0;
1358
+ B = (B + this.B) | 0;
1359
+ C = (C + this.C) | 0;
1360
+ D = (D + this.D) | 0;
1361
+ E = (E + this.E) | 0;
1362
+ F = (F + this.F) | 0;
1363
+ G = (G + this.G) | 0;
1364
+ H = (H + this.H) | 0;
1365
+ this.set(A, B, C, D, E, F, G, H);
1366
+ }
1367
+ roundClean() {
1368
+ clean(SHA256_W);
1369
+ }
1370
+ destroy() {
1371
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
1372
+ clean(this.buffer);
1373
+ }
1374
+ }
1375
+ /**
1376
+ * SHA2-256 hash function from RFC 4634.
1377
+ *
1378
+ * It is the fastest JS hash, even faster than Blake3.
1379
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
1380
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
1381
+ */
1382
+ const sha256$1 = /* @__PURE__ */ createHasher(() => new SHA256());
1383
+
1384
+ /**
1385
+ * SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.
1386
+ *
1387
+ * To break sha256 using birthday attack, attackers need to try 2^128 hashes.
1388
+ * BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
1389
+ *
1390
+ * Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
1391
+ * @module
1392
+ * @deprecated
1393
+ */
1394
+ /** @deprecated Use import from `noble/hashes/sha2` module */
1395
+ const sha256 = sha256$1;
1396
+
1397
+ function bs58checkBase (checksumFn) {
1398
+ // Encode a buffer as a base58-check encoded string
1399
+ function encode(payload) {
1400
+ var payloadU8 = Uint8Array.from(payload);
1401
+ var checksum = checksumFn(payloadU8);
1402
+ var length = payloadU8.length + 4;
1403
+ var both = new Uint8Array(length);
1404
+ both.set(payloadU8, 0);
1405
+ both.set(checksum.subarray(0, 4), payloadU8.length);
1406
+ return base58.encode(both);
1407
+ }
1408
+ function decodeRaw(buffer) {
1409
+ var payload = buffer.slice(0, -4);
1410
+ var checksum = buffer.slice(-4);
1411
+ var newChecksum = checksumFn(payload);
1412
+ // eslint-disable-next-line
1413
+ if (checksum[0] ^ newChecksum[0] |
1414
+ checksum[1] ^ newChecksum[1] |
1415
+ checksum[2] ^ newChecksum[2] |
1416
+ checksum[3] ^ newChecksum[3])
1417
+ return;
1418
+ return payload;
1419
+ }
1420
+ // Decode a base58-check encoded string to a buffer, no result if checksum is wrong
1421
+ function decodeUnsafe(str) {
1422
+ var buffer = base58.decodeUnsafe(str);
1423
+ if (buffer == null)
1424
+ return;
1425
+ return decodeRaw(buffer);
1426
+ }
1427
+ function decode(str) {
1428
+ var buffer = base58.decode(str);
1429
+ var payload = decodeRaw(buffer);
1430
+ if (payload == null)
1431
+ throw new Error('Invalid checksum');
1432
+ return payload;
1433
+ }
1434
+ return {
1435
+ encode: encode,
1436
+ decode: decode,
1437
+ decodeUnsafe: decodeUnsafe
1438
+ };
1439
+ }
1440
+
1441
+ // SHA256(SHA256(buffer))
1442
+ function sha256x2(buffer) {
1443
+ return sha256(sha256(buffer));
1444
+ }
1445
+ var bs58check = bs58checkBase(sha256x2);
1446
+
1447
+ function resolveAddressInput(address) {
1448
+ if (typeof address === 'string') {
1449
+ return String(address).trim();
1450
+ }
1451
+ if (address && typeof address.address === 'string') {
1452
+ return String(address.address).trim();
1453
+ }
1454
+ throw new Error('Address must be a string or an object with an address field');
1455
+ }
1456
+
1457
+ const LEGACY_MAINNET_PREFIX = 53;
1458
+ const LEGACY_TESTNET_PREFIX = 127;
1459
+ const PQ_MAINNET_HRP = 'nq';
1460
+ const PQ_TESTNET_HRP = 'tnq';
1461
+ function inferNetworkFromAddress(address) {
1462
+ const normalized = resolveAddressInput(address).toLowerCase();
1463
+ if (normalized.startsWith(PQ_MAINNET_HRP + '1'))
1464
+ return 'xna-pq';
1465
+ if (normalized.startsWith(PQ_TESTNET_HRP + '1'))
1466
+ return 'xna-pq-test';
1467
+ if (normalized.startsWith('n'))
1468
+ return 'xna';
1469
+ if (normalized.startsWith('t'))
1470
+ return 'xna-test';
1471
+ throw new Error(`Unsupported Neurai address: ${address}`);
1472
+ }
1473
+
1474
+ function decodeAddress(address) {
1475
+ const normalized = resolveAddressInput(address);
1476
+ const lowered = normalized.toLowerCase();
1477
+ if (!normalized)
1478
+ throw new Error('Address is required');
1479
+ if (lowered.startsWith(PQ_MAINNET_HRP + '1') || lowered.startsWith(PQ_TESTNET_HRP + '1')) {
1480
+ const decoded = distExports.bech32m.decode(normalized);
1481
+ const version = decoded.words[0];
1482
+ const program = Uint8Array.from(distExports.bech32m.fromWords(decoded.words.slice(1)));
1483
+ if (version !== 1 || program.length !== 32) {
1484
+ throw new Error(`Unsupported AuthScript address program for ${address}`);
1485
+ }
1486
+ const network = lowered.startsWith(PQ_TESTNET_HRP + '1') ? 'xna-pq-test' : 'xna-pq';
1487
+ return { address: normalized, type: 'authscript', network, program, commitment: program };
1488
+ }
1489
+ const payload = Uint8Array.from(bs58check.decode(normalized));
1490
+ if (payload.length !== 21) {
1491
+ throw new Error(`Unsupported legacy address payload length for ${address}`);
1492
+ }
1493
+ const prefix = payload[0];
1494
+ if (prefix !== LEGACY_MAINNET_PREFIX && prefix !== LEGACY_TESTNET_PREFIX) {
1495
+ throw new Error(`Unsupported legacy address prefix ${prefix} for ${address}`);
1496
+ }
1497
+ return {
1498
+ address: normalized,
1499
+ type: 'p2pkh',
1500
+ network: inferNetworkFromAddress(normalized),
1501
+ program: payload.slice(1),
1502
+ hash: payload.slice(1)
1503
+ };
1504
+ }
1505
+
1506
+ /**
1507
+ * Address helpers. Wraps `decodeAddress` from
1508
+ * `@neuraiproject/neurai-create-transaction` to produce the exact
1509
+ * scriptPubKey bytes a covenant needs to hardcode. The actual
1510
+ * scriptPubKey encoders live in `./standard/*`; this module delegates.
1511
+ *
1512
+ * Two destination types are supported for the payment output (output[0]):
1513
+ * - Legacy P2PKH (base58check)
1514
+ * - AuthScript witness v1 (bech32m)
1515
+ */
1516
+ /**
1517
+ * Resolve any accepted seller address string into its scriptPubKey.
1518
+ * The returned bytes are what the covenant will hardcode and later verify
1519
+ * via `OP_OUTPUTSCRIPT == <bytes>`.
1520
+ */
1521
+ function encodeSellerScriptPubKey(address) {
1522
+ const decoded = decodeAddress(address);
1523
+ if (decoded.type === 'p2pkh') {
1524
+ const hash = Uint8Array.from(decoded.hash);
1525
+ return {
1526
+ kind: 'p2pkh',
1527
+ bytes: encodeP2PKHScriptPubKey(hash),
1528
+ hash
1529
+ };
1530
+ }
1531
+ if (decoded.type === 'authscript') {
1532
+ const program = Uint8Array.from(decoded.program);
1533
+ return {
1534
+ kind: 'authscript',
1535
+ bytes: encodeAuthScriptScriptPubKey(program),
1536
+ hash: program
1537
+ };
1538
+ }
1539
+ throw new Error(`Unsupported seller address type for "${address}"`);
1540
+ }
1541
+
1542
+ /**
1543
+ * Asset-transfer wrapper split helper.
1544
+ *
1545
+ * Neurai asset UTXOs have a scriptPubKey of the form
1546
+ *
1547
+ * <prefix scriptPubKey bytes> OP_XNA_ASSET <pushdata(payload)> OP_DROP
1548
+ *
1549
+ * where `prefix` is the recipient's standard script (typically a P2PKH, an
1550
+ * AuthScript witness v1, or a bare covenant such as the partial-fill sell
1551
+ * order), and `payload` serializes a `CAssetTransfer`:
1552
+ *
1553
+ * payload = rvn_prefix (0x72 0x76 0x6e) || type_marker (0x74 transfer)
1554
+ * || VarStr(assetName)
1555
+ * || int64LE(amountRaw)
1556
+ * [ || messageRef (optional) || int64LE(expireTime) (optional) ]
1557
+ *
1558
+ * This helper separates the two halves so consumers can validate the prefix
1559
+ * (e.g. feed it to `parsePartialFillScript`) while independently reading the
1560
+ * asset data displayed to the user. The optional payload tail
1561
+ * (`message` + `expireTime`) is tolerated but not exposed — the first
1562
+ * version only needs `assetName` and `amountRaw`.
1563
+ *
1564
+ * Bare (non-wrapped) scriptPubKeys round-trip through this helper by
1565
+ * returning `prefixHex === input` and `assetTransfer === null`.
1566
+ */
1567
+ const RVN_MAGIC = Uint8Array.from([0x72, 0x76, 0x6e]); // "rvn"
1568
+ const TRANSFER_TYPE = 0x74;
1569
+ /**
1570
+ * Walk the script one opcode at a time, skipping pushdata payload bytes,
1571
+ * until either OP_XNA_ASSET is reached at top level or the end of the
1572
+ * script. Returns the byte offset of OP_XNA_ASSET, or -1 if not found.
1573
+ * Throws on truncated pushdata.
1574
+ */
1575
+ function findTopLevelAssetOpcode(bytes) {
1576
+ let i = 0;
1577
+ while (i < bytes.length) {
1578
+ const op = bytes[i];
1579
+ if (op === OP_XNA_ASSET)
1580
+ return i;
1581
+ // Short direct push: 0x01..0x4b
1582
+ if (op >= 0x01 && op <= 0x4b) {
1583
+ const len = op;
1584
+ const next = i + 1 + len;
1585
+ if (next > bytes.length) {
1586
+ throw new Error(`splitAssetWrappedScriptPubKey: short push of ${len} bytes at offset ${i} exceeds script length`);
1587
+ }
1588
+ i = next;
1589
+ continue;
1590
+ }
1591
+ if (op === OP_PUSHDATA1) {
1592
+ if (i + 1 >= bytes.length) {
1593
+ throw new Error(`splitAssetWrappedScriptPubKey: truncated PUSHDATA1 length at offset ${i}`);
1594
+ }
1595
+ const len = bytes[i + 1];
1596
+ const next = i + 2 + len;
1597
+ if (next > bytes.length) {
1598
+ throw new Error(`splitAssetWrappedScriptPubKey: PUSHDATA1 of ${len} bytes at offset ${i} exceeds script length`);
1599
+ }
1600
+ i = next;
1601
+ continue;
1602
+ }
1603
+ if (op === OP_PUSHDATA2) {
1604
+ if (i + 2 >= bytes.length) {
1605
+ throw new Error(`splitAssetWrappedScriptPubKey: truncated PUSHDATA2 length at offset ${i}`);
1606
+ }
1607
+ const len = bytes[i + 1] | (bytes[i + 2] << 8);
1608
+ const next = i + 3 + len;
1609
+ if (next > bytes.length) {
1610
+ throw new Error(`splitAssetWrappedScriptPubKey: PUSHDATA2 of ${len} bytes at offset ${i} exceeds script length`);
1611
+ }
1612
+ i = next;
1613
+ continue;
1614
+ }
1615
+ if (op === OP_PUSHDATA4) {
1616
+ if (i + 4 >= bytes.length) {
1617
+ throw new Error(`splitAssetWrappedScriptPubKey: truncated PUSHDATA4 length at offset ${i}`);
1618
+ }
1619
+ const len = (bytes[i + 1] |
1620
+ (bytes[i + 2] << 8) |
1621
+ (bytes[i + 3] << 16) |
1622
+ (bytes[i + 4] << 24)) >>>
1623
+ 0;
1624
+ const next = i + 5 + len;
1625
+ if (next > bytes.length) {
1626
+ throw new Error(`splitAssetWrappedScriptPubKey: PUSHDATA4 of ${len} bytes at offset ${i} exceeds script length`);
1627
+ }
1628
+ i = next;
1629
+ continue;
1630
+ }
1631
+ // Any other opcode (including OP_1..OP_16, OP_DUP, OP_HASH160, etc.) is
1632
+ // one byte wide in Neurai Script. Advance.
1633
+ i += 1;
1634
+ }
1635
+ return -1;
1636
+ }
1637
+ /**
1638
+ * Read the pushdata element that sits immediately after OP_XNA_ASSET and
1639
+ * return its payload bytes together with the cursor position after the
1640
+ * element. Only direct pushes (1..75) and PUSHDATA1 are accepted — a
1641
+ * well-formed asset transfer payload fits within 75 bytes for the common
1642
+ * case and comfortably within 255 bytes even with long names and tails.
1643
+ * PUSHDATA2 and PUSHDATA4 would signal a malformed or adversarial wrapper.
1644
+ */
1645
+ function readPayloadPush(bytes, start) {
1646
+ if (start >= bytes.length) {
1647
+ throw new Error('splitAssetWrappedScriptPubKey: truncated wrapper — missing payload push');
1648
+ }
1649
+ const op = bytes[start];
1650
+ if (op >= 0x01 && op <= 0x4b) {
1651
+ const len = op;
1652
+ const dataStart = start + 1;
1653
+ const dataEnd = dataStart + len;
1654
+ if (dataEnd > bytes.length) {
1655
+ throw new Error(`splitAssetWrappedScriptPubKey: asset payload short push of ${len} bytes exceeds script length`);
1656
+ }
1657
+ return { payload: bytes.slice(dataStart, dataEnd), after: dataEnd };
1658
+ }
1659
+ if (op === OP_PUSHDATA1) {
1660
+ if (start + 1 >= bytes.length) {
1661
+ throw new Error('splitAssetWrappedScriptPubKey: truncated PUSHDATA1 in asset payload');
1662
+ }
1663
+ const len = bytes[start + 1];
1664
+ const dataStart = start + 2;
1665
+ const dataEnd = dataStart + len;
1666
+ if (dataEnd > bytes.length) {
1667
+ throw new Error(`splitAssetWrappedScriptPubKey: asset payload PUSHDATA1 of ${len} bytes exceeds script length`);
1668
+ }
1669
+ return { payload: bytes.slice(dataStart, dataEnd), after: dataEnd };
1670
+ }
1671
+ throw new Error(`splitAssetWrappedScriptPubKey: asset payload push opcode 0x${op.toString(16)} not accepted (expected 0x01..0x4b or PUSHDATA1)`);
1672
+ }
1673
+ function parseAssetTransferPayload(payload) {
1674
+ if (payload.length < 4 + 1 + 8) {
1675
+ // 4 magic+type, 1 varstr length, 8 int64LE amount
1676
+ throw new Error(`splitAssetWrappedScriptPubKey: asset payload of ${payload.length} bytes is too short`);
1677
+ }
1678
+ for (let i = 0; i < 3; i += 1) {
1679
+ if (payload[i] !== RVN_MAGIC[i]) {
1680
+ throw new Error(`splitAssetWrappedScriptPubKey: asset payload magic mismatch — expected "rvn" got 0x${payload[0].toString(16)} 0x${payload[1].toString(16)} 0x${payload[2].toString(16)}`);
1681
+ }
1682
+ }
1683
+ if (payload[3] !== TRANSFER_TYPE) {
1684
+ throw new Error(`splitAssetWrappedScriptPubKey: asset payload type marker 0x${payload[3].toString(16)} is not a transfer (0x74)`);
1685
+ }
1686
+ const nameLen = payload[4];
1687
+ const nameStart = 5;
1688
+ const nameEnd = nameStart + nameLen;
1689
+ if (nameEnd + 8 > payload.length) {
1690
+ throw new Error(`splitAssetWrappedScriptPubKey: asset payload truncated — name length ${nameLen} does not leave room for amount`);
1691
+ }
1692
+ let assetName = '';
1693
+ for (let i = nameStart; i < nameEnd; i += 1) {
1694
+ assetName += String.fromCharCode(payload[i]);
1695
+ }
1696
+ let amountRaw = 0n;
1697
+ for (let i = 0; i < 8; i += 1) {
1698
+ amountRaw |= BigInt(payload[nameEnd + i]) << BigInt(8 * i);
1699
+ }
1700
+ // Any bytes after nameEnd + 8 form the optional tail (message +
1701
+ // expireTime). We intentionally ignore them in this first version; the
1702
+ // raw payload remains available via `payloadHex` if a consumer later
1703
+ // needs to inspect them.
1704
+ return { assetName, amountRaw };
1705
+ }
1706
+ /**
1707
+ * Parse an asset-transfer-wrapped scriptPubKey. Accepts both wrapped and
1708
+ * bare forms. Throws on structural malformation (truncated pushdata,
1709
+ * missing OP_DROP after payload, bad magic, unsupported pushdata width).
1710
+ */
1711
+ function splitAssetWrappedScriptPubKey(spkHex) {
1712
+ const normalized = ensureHex(spkHex, 'scriptPubKey');
1713
+ const bytes = hexToBytes(normalized);
1714
+ const assetOpAt = findTopLevelAssetOpcode(bytes);
1715
+ if (assetOpAt < 0) {
1716
+ return { prefixHex: normalized, assetTransfer: null };
1717
+ }
1718
+ const prefix = bytes.slice(0, assetOpAt);
1719
+ const { payload, after } = readPayloadPush(bytes, assetOpAt + 1);
1720
+ if (after >= bytes.length) {
1721
+ throw new Error('splitAssetWrappedScriptPubKey: asset wrapper missing trailing OP_DROP');
1722
+ }
1723
+ if (bytes[after] !== OP_DROP) {
1724
+ throw new Error(`splitAssetWrappedScriptPubKey: expected OP_DROP at offset ${after}, got 0x${bytes[after].toString(16)}`);
1725
+ }
1726
+ if (after + 1 !== bytes.length) {
1727
+ throw new Error(`splitAssetWrappedScriptPubKey: ${bytes.length - after - 1} trailing bytes after OP_DROP`);
1728
+ }
1729
+ const { assetName, amountRaw } = parseAssetTransferPayload(payload);
1730
+ return {
1731
+ prefixHex: bytesToHex(prefix),
1732
+ assetTransfer: {
1733
+ assetName,
1734
+ amountRaw,
1735
+ payloadHex: bytesToHex(payload),
1736
+ },
1737
+ };
1738
+ }
1739
+
1740
+ /**
1741
+ * Partial-Fill Sell Order covenant script.
1742
+ *
1743
+ * The covenant has two branches selected by the top of the unlock stack:
1744
+ *
1745
+ * OP_IF (unlock pushed 1) → Cancel: seller signs, recovers remainder.
1746
+ * OP_ELSE (unlock pushed 0) → Public partial fill: buyer provides the
1747
+ * fill amount `N` and the tx layout is
1748
+ * validated byte by byte.
1749
+ *
1750
+ * The partial-fill branch enforces a fixed output layout so that the script
1751
+ * stays compact and parseable:
1752
+ *
1753
+ * output[0] = XNA payment to seller (value >= N * unitPriceSats)
1754
+ * output[1] = asset to buyer (tokenId, amount == N)
1755
+ * output[2] = covenant remainder (same scriptPubKey, amount == in - N)
1756
+ * output[3+] = optional buyer change (not constrained by the covenant)
1757
+ *
1758
+ * The remainder UTXO reuses the spent scriptPubKey via
1759
+ * `OP_OUTPUTSCRIPT == OP_TXFIELD 0x03`, so the covenant is self-replicating
1760
+ * without hardcoding its own hash.
1761
+ *
1762
+ * The cancel branch uses classical ECDSA (`OP_HASH160 + OP_CHECKSIG`) and
1763
+ * commits to a 20-byte PKH. As a consequence this variant only accepts
1764
+ * legacy P2PKH addresses as the seller destination. For AuthScript bech32m
1765
+ * destinations and post-quantum signing, use `buildPartialFillScriptPQ`.
1766
+ */
1767
+ const ASSET_NAME_MAX$1 = 32;
1768
+ function decodeSellerAddress(sellerAddress) {
1769
+ if (typeof sellerAddress !== 'string' || sellerAddress.length === 0) {
1770
+ throw new Error('sellerAddress is required');
1771
+ }
1772
+ const decoded = decodeAddress(sellerAddress);
1773
+ if (decoded.type !== 'p2pkh') {
1774
+ throw new Error(`sellerAddress must be a legacy P2PKH address (the legacy partial-fill covenant uses OP_HASH160 + OP_CHECKSIG); ` +
1775
+ `got ${decoded.type}. Use buildPartialFillScriptPQ for AuthScript destinations.`);
1776
+ }
1777
+ const pkh = Uint8Array.from(decoded.hash);
1778
+ if (pkh.length !== 20) {
1779
+ throw new Error(`decoded sellerAddress produced a ${pkh.length}-byte hash, expected 20`);
1780
+ }
1781
+ return pkh;
1782
+ }
1783
+ function assertTokenId$1(tokenId) {
1784
+ if (typeof tokenId !== 'string' || tokenId.length === 0) {
1785
+ throw new Error('tokenId is required');
1786
+ }
1787
+ if (!/^[A-Z0-9._]+$/.test(tokenId)) {
1788
+ throw new Error(`tokenId "${tokenId}" is not a valid Neurai asset name`);
1789
+ }
1790
+ if (tokenId.length > ASSET_NAME_MAX$1) {
1791
+ throw new Error(`tokenId exceeds ${ASSET_NAME_MAX$1} bytes`);
1792
+ }
1793
+ }
1794
+ function assertPrice$1(priceSats) {
1795
+ if (typeof priceSats !== 'bigint') {
1796
+ throw new Error('unitPriceSats must be a bigint (satoshis per indivisible unit)');
1797
+ }
1798
+ if (priceSats <= 0n) {
1799
+ throw new Error('unitPriceSats must be > 0');
1800
+ }
1801
+ // 8-byte signed int ceiling: values beyond this cannot be produced by OP_MUL
1802
+ // inside the covenant without overflow (CScriptNum is int64).
1803
+ if (priceSats > 0x7fffffffffffffffn) {
1804
+ throw new Error('unitPriceSats exceeds int64 range');
1805
+ }
1806
+ }
1807
+ /**
1808
+ * Build the `scriptPubKey` of a Partial-Fill Sell Order covenant UTXO.
1809
+ * Returns raw bytes; wrap with `bytesToHex` for wire format.
1810
+ */
1811
+ function buildPartialFillScript(params) {
1812
+ const { sellerAddress, tokenId, unitPriceSats } = params;
1813
+ const sellerPubKeyHash = decodeSellerAddress(sellerAddress);
1814
+ assertTokenId$1(tokenId);
1815
+ assertPrice$1(unitPriceSats);
1816
+ const sellerScriptPubKey = encodeP2PKHScriptPubKey(sellerPubKeyHash);
1817
+ const tokenIdBytes = new TextEncoder().encode(tokenId);
1818
+ const b = new ScriptBuilder();
1819
+ // ───────── Cancel branch (IF) ─────────
1820
+ // scriptSig expected: <sig> <pubkey> OP_1
1821
+ b.op(OP_IF)
1822
+ .op(OP_DUP, OP_HASH160)
1823
+ .pushBytes(sellerPubKeyHash)
1824
+ .op(OP_EQUALVERIFY, OP_CHECKSIG)
1825
+ .op(OP_ELSE);
1826
+ // ───────── Partial-fill branch (ELSE) ─────────
1827
+ // scriptSig expected: <N> OP_0
1828
+ //
1829
+ // Stack invariant entering the ELSE branch: [ N ]
1830
+ // 1. Payment value to seller (output 0)
1831
+ // require outputValue(0) >= N * unitPriceSats
1832
+ b.op(OP_DUP) // [ N, N ]
1833
+ .pushInt(unitPriceSats) // [ N, N, price ]
1834
+ .op(OP_MUL) // [ N, N*price ]
1835
+ .pushInt(0) // [ N, N*price, 0 ]
1836
+ .op(OP_OUTPUTVALUE) // [ N, N*price, value ]
1837
+ .op(OP_SWAP) // [ N, value, N*price ]
1838
+ .op(OP_GREATERTHANOREQUAL)
1839
+ .op(OP_VERIFY); // [ N ]
1840
+ // 2. Payment scriptPubKey must equal Alice's (output 0)
1841
+ b.pushInt(0)
1842
+ .op(OP_OUTPUTSCRIPT) // [ N, scriptPubKey_out0 ]
1843
+ .pushBytes(sellerScriptPubKey)
1844
+ .op(OP_EQUALVERIFY); // [ N ]
1845
+ // 3. Asset delivered to buyer (output 1): amount == N
1846
+ b.op(OP_DUP) // [ N, N ]
1847
+ .pushInt(1) // [ N, N, 1 ]
1848
+ .pushInt(ASSETFIELD_AMOUNT)
1849
+ .op(OP_OUTPUTASSETFIELD) // [ N, N, amount_out1 ]
1850
+ .op(OP_EQUALVERIFY); // [ N ]
1851
+ // 4. Asset delivered to buyer (output 1): name == tokenId
1852
+ b.pushInt(1)
1853
+ .pushInt(ASSETFIELD_NAME)
1854
+ .op(OP_OUTPUTASSETFIELD) // [ N, name_out1 ]
1855
+ .pushBytes(tokenIdBytes)
1856
+ .op(OP_EQUALVERIFY); // [ N ]
1857
+ // 5. Remainder covenant continuity (output 2): same scriptPubKey as spent
1858
+ b.pushInt(2)
1859
+ .op(OP_OUTPUTSCRIPT) // [ N, spk_out2 ]
1860
+ .pushInt(TXFIELD_SCRIPTPUBKEY)
1861
+ .op(OP_TXFIELD) // [ N, spk_out2, spent_spk ]
1862
+ .op(OP_EQUALVERIFY); // [ N ]
1863
+ // 6. Remainder output: same tokenId
1864
+ b.pushInt(2)
1865
+ .pushInt(ASSETFIELD_NAME)
1866
+ .op(OP_OUTPUTASSETFIELD) // [ N, name_out2 ]
1867
+ .pushBytes(tokenIdBytes)
1868
+ .op(OP_EQUALVERIFY); // [ N ]
1869
+ // 7. Remainder output: amount == inputAssetAmount - N
1870
+ b.pushInt(2)
1871
+ .pushInt(ASSETFIELD_AMOUNT)
1872
+ .op(OP_OUTPUTASSETFIELD) // [ N, rem_amount ]
1873
+ .op(OP_OVER) // [ N, rem_amount, N ] -- copy N under top
1874
+ .pushInt(0) // [ N, rem_amount, N, 0 ]
1875
+ .pushInt(ASSETFIELD_AMOUNT)
1876
+ .op(OP_INPUTASSETFIELD) // [ N, rem_amount, N, in_amount ]
1877
+ .op(OP_SWAP) // [ N, rem_amount, in_amount, N ]
1878
+ .op(OP_SUB) // [ N, rem_amount, in_amount - N ]
1879
+ .op(OP_EQUALVERIFY); // [ N ]
1880
+ // Drop N, leave TRUE on the stack so the ELSE branch evaluates as success.
1881
+ b.op(OP_DROP).pushInt(1);
1882
+ b.op(OP_ENDIF);
1883
+ return b.build();
1884
+ }
1885
+ /** Hex convenience wrapper for `buildPartialFillScript`. */
1886
+ function buildPartialFillScriptHex(params) {
1887
+ return bytesToHex(buildPartialFillScript(params));
1888
+ }
1889
+
1890
+ /**
1891
+ * PQ (post-quantum) variant of the Partial-Fill Sell Order covenant.
1892
+ *
1893
+ * Identical partial-fill branch to the legacy covenant, but the **cancel**
1894
+ * branch accepts an ML-DSA-44 signature instead of an ECDSA one. This
1895
+ * requires:
1896
+ * - `SCRIPT_VERIFY_CHECKSIGFROMSTACK` (for OP_CSFS) active
1897
+ * - `SCRIPT_VERIFY_TXHASH` (for OP_TXHASH) active
1898
+ * - NIP-18 (`MAX_PQ_SCRIPT_ELEMENT_SIZE = 3072`) active, so the ~2.4 KB
1899
+ * signature and ~1.3 KB pubkey can be pushed to the script stack
1900
+ *
1901
+ * All three are active on DePIN-Test testnet.
1902
+ *
1903
+ * Cancel-branch flow (scriptSig pushes `<sig> <pubkey> OP_1`):
1904
+ *
1905
+ * 1. OP_DUP OP_SHA256 <commitment> OP_EQUALVERIFY → pubkey matches
1906
+ * 2. <selector> OP_TXHASH → message = H(tx)
1907
+ * 3. OP_SWAP OP_CHECKSIGFROMSTACK → CSFS verifies sig
1908
+ *
1909
+ * The message that gets signed is **SHA256(OP_TXHASH(selector))** — CSFS
1910
+ * single-SHA256s its message argument before verification, and OP_TXHASH
1911
+ * produces its own 32-byte hash, so the seller computes:
1912
+ * `sign(pqSeckey, SHA256(doubleSHA256(selected_tx_fields)))`
1913
+ */
1914
+ const ASSET_NAME_MAX = 32;
1915
+ const DEFAULT_PQ_TXHASH_SELECTOR = 0xff;
1916
+ function assertCommitment(commitment) {
1917
+ if (!(commitment instanceof Uint8Array) || commitment.length !== 32) {
1918
+ throw new Error('pubKeyCommitment must be a 32-byte Uint8Array (SHA256 of pubKey)');
1919
+ }
1920
+ }
1921
+ function assertTokenId(tokenId) {
1922
+ if (typeof tokenId !== 'string' || tokenId.length === 0) {
1923
+ throw new Error('tokenId is required');
1924
+ }
1925
+ if (!/^[A-Z0-9._]+$/.test(tokenId)) {
1926
+ throw new Error(`tokenId "${tokenId}" is not a valid Neurai asset name`);
1927
+ }
1928
+ if (tokenId.length > ASSET_NAME_MAX) {
1929
+ throw new Error(`tokenId exceeds ${ASSET_NAME_MAX} bytes`);
1930
+ }
1931
+ }
1932
+ function assertPrice(priceSats) {
1933
+ if (typeof priceSats !== 'bigint') {
1934
+ throw new Error('unitPriceSats must be a bigint');
1935
+ }
1936
+ if (priceSats <= 0n) {
1937
+ throw new Error('unitPriceSats must be > 0');
1938
+ }
1939
+ if (priceSats > 0x7fffffffffffffffn) {
1940
+ throw new Error('unitPriceSats exceeds int64 range');
1941
+ }
1942
+ }
1943
+ function assertSelector(selector) {
1944
+ if (!Number.isInteger(selector) || selector < 0 || selector > 0xff) {
1945
+ throw new Error('txHashSelector must be a single byte (0x00..0xff)');
1946
+ }
1947
+ if (selector === 0) {
1948
+ throw new Error('txHashSelector 0x00 is rejected by OP_TXHASH');
1949
+ }
1950
+ }
1951
+ /**
1952
+ * Build the scriptPubKey of a PQ Partial-Fill Sell Order covenant UTXO.
1953
+ */
1954
+ function buildPartialFillScriptPQ(params) {
1955
+ const { paymentAddress, pubKeyCommitment, tokenId, unitPriceSats, txHashSelector = DEFAULT_PQ_TXHASH_SELECTOR } = params;
1956
+ assertCommitment(pubKeyCommitment);
1957
+ assertTokenId(tokenId);
1958
+ assertPrice(unitPriceSats);
1959
+ assertSelector(txHashSelector);
1960
+ const payment = encodeSellerScriptPubKey(paymentAddress);
1961
+ const tokenIdBytes = new TextEncoder().encode(tokenId);
1962
+ const b = new ScriptBuilder();
1963
+ // ───────── Cancel branch (PQ via OP_CHECKSIGFROMSTACK) ─────────
1964
+ // scriptSig expected: <sigPQ> <pubKeyPQ> OP_1
1965
+ // After OP_IF consumes the flag: [ sig, pubKey ]
1966
+ b.op(OP_IF)
1967
+ .op(OP_DUP) // [ sig, pubKey, pubKey ]
1968
+ .op(OP_SHA256) // [ sig, pubKey, H(pubKey) ]
1969
+ .pushBytes(pubKeyCommitment) // [ sig, pubKey, H(pubKey), commitment ]
1970
+ .op(OP_EQUALVERIFY) // [ sig, pubKey ]
1971
+ .pushInt(txHashSelector) // [ sig, pubKey, selector ]
1972
+ .op(OP_TXHASH) // [ sig, pubKey, txHash ]
1973
+ .op(OP_SWAP) // [ sig, txHash, pubKey ]
1974
+ .op(OP_CHECKSIGFROMSTACK) // [ 1 | 0 ]
1975
+ .op(OP_ELSE);
1976
+ // ───────── Partial-fill branch (identical layout to legacy) ─────────
1977
+ // scriptSig expected: <N> OP_0
1978
+ // Stack entering ELSE: [ N ]
1979
+ // 1. Payment value (output 0) >= N * unitPriceSats
1980
+ b.op(OP_DUP)
1981
+ .pushInt(unitPriceSats)
1982
+ .op(OP_MUL)
1983
+ .pushInt(0)
1984
+ .op(OP_OUTPUTVALUE)
1985
+ .op(OP_SWAP)
1986
+ .op(OP_GREATERTHANOREQUAL)
1987
+ .op(OP_VERIFY);
1988
+ // 2. Payment scriptPubKey (output 0) == payment.bytes
1989
+ b.pushInt(0)
1990
+ .op(OP_OUTPUTSCRIPT)
1991
+ .pushBytes(payment.bytes)
1992
+ .op(OP_EQUALVERIFY);
1993
+ // 3. Asset to buyer (output 1) amount == N
1994
+ b.op(OP_DUP)
1995
+ .pushInt(1)
1996
+ .pushInt(ASSETFIELD_AMOUNT)
1997
+ .op(OP_OUTPUTASSETFIELD)
1998
+ .op(OP_EQUALVERIFY);
1999
+ // 4. Asset to buyer (output 1) name == tokenId
2000
+ b.pushInt(1)
2001
+ .pushInt(ASSETFIELD_NAME)
2002
+ .op(OP_OUTPUTASSETFIELD)
2003
+ .pushBytes(tokenIdBytes)
2004
+ .op(OP_EQUALVERIFY);
2005
+ // 5. Remainder continuity (output 2) — same scriptPubKey as spent
2006
+ b.pushInt(2)
2007
+ .op(OP_OUTPUTSCRIPT)
2008
+ .pushInt(TXFIELD_SCRIPTPUBKEY)
2009
+ .op(OP_TXFIELD)
2010
+ .op(OP_EQUALVERIFY);
2011
+ // 6. Remainder tokenId
2012
+ b.pushInt(2)
2013
+ .pushInt(ASSETFIELD_NAME)
2014
+ .op(OP_OUTPUTASSETFIELD)
2015
+ .pushBytes(tokenIdBytes)
2016
+ .op(OP_EQUALVERIFY);
2017
+ // 7. Remainder amount == inputAssetAmount - N
2018
+ b.pushInt(2)
2019
+ .pushInt(ASSETFIELD_AMOUNT)
2020
+ .op(OP_OUTPUTASSETFIELD)
2021
+ .op(OP_OVER)
2022
+ .pushInt(0)
2023
+ .pushInt(ASSETFIELD_AMOUNT)
2024
+ .op(OP_INPUTASSETFIELD)
2025
+ .op(OP_SWAP)
2026
+ .op(OP_SUB)
2027
+ .op(OP_EQUALVERIFY);
2028
+ b.op(OP_DROP).pushInt(1);
2029
+ b.op(OP_ENDIF);
2030
+ return b.build();
2031
+ }
2032
+ function buildPartialFillScriptPQHex(params) {
2033
+ return bytesToHex(buildPartialFillScriptPQ(params));
2034
+ }
2035
+
2036
+ /**
2037
+ * scriptSig builders for the Partial-Fill Sell Order covenant.
2038
+ *
2039
+ * These return the raw scriptSig bytes that unlock the covenant UTXO. The
2040
+ * surrounding transaction (inputs, outputs, fees, signatures on the buyer's
2041
+ * own inputs, etc.) is the caller's responsibility — stitch them together
2042
+ * with `@neuraiproject/neurai-create-transaction`.
2043
+ */
2044
+ /**
2045
+ * Unlock the covenant via the public partial-fill branch.
2046
+ *
2047
+ * Layout on the stack before OP_IF executes (top → bottom):
2048
+ * 0 ← selects the OP_ELSE (fill) branch
2049
+ * N ← amount of asset the buyer is taking from this order
2050
+ *
2051
+ * so the scriptSig pushes `<N>` then `<0>`.
2052
+ *
2053
+ * @param amount units of the asset the buyer is taking. Must be > 0 and
2054
+ * strictly less than the amount locked in the order UTXO
2055
+ * (equal would leave a zero-asset remainder, which isn't a
2056
+ * valid Neurai transfer output).
2057
+ */
2058
+ function buildFillScriptSig(amount) {
2059
+ if (typeof amount !== 'bigint') {
2060
+ throw new Error('amount must be a bigint');
2061
+ }
2062
+ if (amount <= 0n) {
2063
+ throw new Error('fill amount must be > 0');
2064
+ }
2065
+ return new ScriptBuilder()
2066
+ .pushInt(amount)
2067
+ .pushInt(0)
2068
+ .build();
2069
+ }
2070
+ function buildFillScriptSigHex(amount) {
2071
+ return bytesToHex(buildFillScriptSig(amount));
2072
+ }
2073
+ /**
2074
+ * Unlock the covenant via the seller's cancel branch.
2075
+ *
2076
+ * Stack before OP_IF (top → bottom):
2077
+ * 1 ← selects the OP_IF branch
2078
+ * pubkey ← consumed by OP_DUP OP_HASH160 … OP_EQUALVERIFY
2079
+ * sig ← consumed by OP_CHECKSIG
2080
+ *
2081
+ * so the scriptSig pushes `<sig> <pubkey> <1>`.
2082
+ *
2083
+ * The signature is on whatever sighash the caller picked; this builder does
2084
+ * not hash or sign, it only assembles the unlock script once a signature is
2085
+ * available.
2086
+ */
2087
+ function buildCancelScriptSig(signatureDer, pubKey) {
2088
+ if (!(signatureDer instanceof Uint8Array) || signatureDer.length === 0) {
2089
+ throw new Error('signatureDer must be a non-empty Uint8Array');
2090
+ }
2091
+ if (!(pubKey instanceof Uint8Array) || (pubKey.length !== 33 && pubKey.length !== 65)) {
2092
+ throw new Error('pubKey must be a compressed (33B) or uncompressed (65B) secp256k1 key');
2093
+ }
2094
+ return new ScriptBuilder()
2095
+ .pushBytes(signatureDer)
2096
+ .pushBytes(pubKey)
2097
+ .pushInt(1)
2098
+ .build();
2099
+ }
2100
+ function buildCancelScriptSigHex(signatureDer, pubKey) {
2101
+ return bytesToHex(buildCancelScriptSig(signatureDer, pubKey));
2102
+ }
2103
+
2104
+ /**
2105
+ * scriptSig builders for the PQ Partial-Fill Sell Order covenant.
2106
+ *
2107
+ * The fill branch is identical to the legacy variant (just pushes `<N> <0>`),
2108
+ * so callers reuse `buildFillScriptSig` from `./spend.ts`. Only the cancel
2109
+ * branch is different: it carries a full PQ pubkey (~1313 B) and signature
2110
+ * (~2421 B), which requires NIP-18's expanded element-size cap.
2111
+ */
2112
+ /**
2113
+ * Build the scriptSig that unlocks the PQ cancel branch.
2114
+ *
2115
+ * Stack ordering pushed (bottom → top): `sig, pubkey, 1`.
2116
+ *
2117
+ * @param sigPQ ML-DSA-44 signature over `SHA256(OP_TXHASH(selector))`,
2118
+ * **with trailing sighash byte appended** (same convention as
2119
+ * OP_CHECKSIG — CSFS strips it before verification). Expected
2120
+ * length 2421 bytes for ML-DSA-44.
2121
+ * @param pubKey Versioned PQ public key bytes, 1313 bytes (1-byte prefix
2122
+ * + 1312-byte ML-DSA-44 key). Must hash (via SHA256) to the
2123
+ * `pubKeyCommitment` embedded in the covenant scriptPubKey.
2124
+ */
2125
+ function buildCancelScriptSigPQ(sigPQ, pubKey) {
2126
+ if (!(sigPQ instanceof Uint8Array) || sigPQ.length === 0) {
2127
+ throw new Error('sigPQ must be a non-empty Uint8Array');
2128
+ }
2129
+ if (sigPQ.length > 3072) {
2130
+ throw new Error(`sigPQ of ${sigPQ.length} bytes exceeds MAX_PQ_SCRIPT_ELEMENT_SIZE (3072)`);
2131
+ }
2132
+ if (!(pubKey instanceof Uint8Array) || pubKey.length === 0) {
2133
+ throw new Error('pubKey must be a non-empty Uint8Array');
2134
+ }
2135
+ if (pubKey.length > 3072) {
2136
+ throw new Error(`pubKey of ${pubKey.length} bytes exceeds MAX_PQ_SCRIPT_ELEMENT_SIZE (3072)`);
2137
+ }
2138
+ return new ScriptBuilder()
2139
+ .pushBytes(sigPQ)
2140
+ .pushBytes(pubKey)
2141
+ .pushInt(1)
2142
+ .build();
2143
+ }
2144
+ function buildCancelScriptSigPQHex(sigPQ, pubKey) {
2145
+ return bytesToHex(buildCancelScriptSigPQ(sigPQ, pubKey));
2146
+ }
2147
+
2148
+ /**
2149
+ * Shared parsing primitives for strict covenant parsers. Each covenant
2150
+ * parser walks the exact byte layout emitted by its builder and fails on
2151
+ * any deviation; the primitives here centralize the cursor arithmetic,
2152
+ * pushdata decoding, and CScriptNum decoding so the legacy and PQ parsers
2153
+ * (and future covenant parsers) cannot drift in rigor.
2154
+ */
2155
+ function makeCursor(bytes) {
2156
+ return { bytes, pos: 0 };
2157
+ }
2158
+ /** Consume one byte and verify it equals `expected`. */
2159
+ function expectByte(c, expected, label) {
2160
+ if (c.pos >= c.bytes.length) {
2161
+ throw new Error(`parse: unexpected end of script while reading ${label}`);
2162
+ }
2163
+ const got = c.bytes[c.pos];
2164
+ if (got !== expected) {
2165
+ throw new Error(`parse: expected ${label} = 0x${expected.toString(16)} at offset ${c.pos}, got 0x${got.toString(16)}`);
2166
+ }
2167
+ c.pos += 1;
2168
+ }
2169
+ /** Fail if the cursor has not consumed every byte of the script. */
2170
+ function assertTrailing(c) {
2171
+ if (c.pos !== c.bytes.length) {
2172
+ throw new Error(`parse: ${c.bytes.length - c.pos} trailing bytes after end of script`);
2173
+ }
2174
+ }
2175
+ /**
2176
+ * Read one pushdata element from the cursor. Supports direct pushes
2177
+ * (1..75 bytes), `OP_PUSHDATA1` and `OP_PUSHDATA2`. `OP_PUSHDATA4` is not
2178
+ * supported by any current covenant script and would overflow the
2179
+ * per-element cap anyway. Truncation is checked for all length fields
2180
+ * and payload ranges.
2181
+ */
2182
+ function readPush(c, label) {
2183
+ if (c.pos >= c.bytes.length) {
2184
+ throw new Error(`parse: unexpected end of script while reading push for ${label}`);
2185
+ }
2186
+ const opcode = c.bytes[c.pos];
2187
+ c.pos += 1;
2188
+ // Short direct push: 1..75 bytes
2189
+ if (opcode >= 0x01 && opcode <= 0x4b) {
2190
+ const len = opcode;
2191
+ if (c.pos + len > c.bytes.length) {
2192
+ throw new Error(`parse: short push of ${len} bytes exceeds script length at ${label}`);
2193
+ }
2194
+ const data = c.bytes.slice(c.pos, c.pos + len);
2195
+ c.pos += len;
2196
+ return data;
2197
+ }
2198
+ // OP_PUSHDATA1
2199
+ if (opcode === 0x4c) {
2200
+ if (c.pos >= c.bytes.length) {
2201
+ throw new Error(`parse: truncated PUSHDATA1 length at ${label}`);
2202
+ }
2203
+ const len = c.bytes[c.pos];
2204
+ c.pos += 1;
2205
+ if (c.pos + len > c.bytes.length) {
2206
+ throw new Error(`parse: PUSHDATA1 of ${len} bytes exceeds script length at ${label}`);
2207
+ }
2208
+ const data = c.bytes.slice(c.pos, c.pos + len);
2209
+ c.pos += len;
2210
+ return data;
2211
+ }
2212
+ // OP_PUSHDATA2
2213
+ if (opcode === 0x4d) {
2214
+ if (c.pos + 2 > c.bytes.length) {
2215
+ throw new Error(`parse: truncated PUSHDATA2 length at ${label}`);
2216
+ }
2217
+ const len = c.bytes[c.pos] | (c.bytes[c.pos + 1] << 8);
2218
+ c.pos += 2;
2219
+ if (c.pos + len > c.bytes.length) {
2220
+ throw new Error(`parse: PUSHDATA2 of ${len} bytes exceeds script length at ${label}`);
2221
+ }
2222
+ const data = c.bytes.slice(c.pos, c.pos + len);
2223
+ c.pos += len;
2224
+ return data;
2225
+ }
2226
+ throw new Error(`parse: expected a pushdata opcode at ${label}, got 0x${opcode.toString(16)} at offset ${c.pos - 1}`);
2227
+ }
2228
+ /**
2229
+ * Decode a `CScriptNum` byte vector (little-endian sign-magnitude, up to
2230
+ * 8 bytes) into a BigInt. Empty vector encodes 0.
2231
+ */
2232
+ function decodeScriptNum(data, label) {
2233
+ if (data.length === 0)
2234
+ return 0n;
2235
+ if (data.length > 8) {
2236
+ throw new Error(`parse: CScriptNum at ${label} exceeds 8 bytes`);
2237
+ }
2238
+ let n = 0n;
2239
+ for (let i = 0; i < data.length - 1; i += 1) {
2240
+ n |= BigInt(data[i]) << BigInt(8 * i);
2241
+ }
2242
+ const last = data[data.length - 1];
2243
+ n |= BigInt(last & 0x7f) << BigInt(8 * (data.length - 1));
2244
+ if (last & 0x80) {
2245
+ n = -n;
2246
+ }
2247
+ return n;
2248
+ }
2249
+ /**
2250
+ * Read a push as a non-negative CScriptNum. Recognises OP_1..OP_16
2251
+ * shorthand. `OP_0` is not accepted because the covenant callers use this
2252
+ * only for values that are strictly positive (prices, selectors, indices).
2253
+ */
2254
+ function readPushPositiveInt(c, label) {
2255
+ if (c.pos >= c.bytes.length) {
2256
+ throw new Error(`parse: end of script at ${label}`);
2257
+ }
2258
+ const opcode = c.bytes[c.pos];
2259
+ if (opcode >= OP_1 && opcode <= 0x60) {
2260
+ c.pos += 1;
2261
+ return BigInt(opcode - OP_1 + 1);
2262
+ }
2263
+ const data = readPush(c, label);
2264
+ return decodeScriptNum(data, label);
2265
+ }
2266
+
2267
+ /**
2268
+ * Parser for the Partial-Fill Sell Order covenant.
2269
+ *
2270
+ * Extracts `(sellerPubKeyHash, unitPriceSats, tokenId)` from a scriptPubKey
2271
+ * that was produced by `buildPartialFillScript`. The parser walks the exact
2272
+ * byte layout emitted by the builder and fails on any deviation — this is
2273
+ * deliberate, so a downstream indexer can unambiguously classify a UTXO as
2274
+ * "partial-fill order" or "unknown script" with no false positives.
2275
+ */
2276
+ /**
2277
+ * Parse a covenant scriptPubKey and extract its parameters. Throws with a
2278
+ * descriptive message if the bytes don't match the partial-fill template.
2279
+ */
2280
+ function parsePartialFillScript(script, network = 'xna-test') {
2281
+ const bytes = typeof script === 'string' ? hexToBytes(script) : script;
2282
+ const c = makeCursor(bytes);
2283
+ // ───── Cancel branch prefix ─────
2284
+ expectByte(c, OP_IF, 'OP_IF');
2285
+ expectByte(c, OP_DUP, 'OP_DUP (cancel)');
2286
+ expectByte(c, OP_HASH160, 'OP_HASH160');
2287
+ const sellerPubKeyHash = readPush(c, 'sellerPubKeyHash');
2288
+ if (sellerPubKeyHash.length !== 20) {
2289
+ throw new Error(`parse: sellerPubKeyHash is ${sellerPubKeyHash.length} bytes, expected 20`);
2290
+ }
2291
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (cancel)');
2292
+ expectByte(c, OP_CHECKSIG, 'OP_CHECKSIG (cancel)');
2293
+ expectByte(c, OP_ELSE, 'OP_ELSE');
2294
+ // ───── Payment value check ─────
2295
+ expectByte(c, OP_DUP, 'OP_DUP (price)');
2296
+ const unitPriceSats = readPushPositiveInt(c, 'unitPriceSats');
2297
+ expectByte(c, OP_MUL, 'OP_MUL');
2298
+ expectByte(c, OP_0, 'OP_0 (payment idx)');
2299
+ expectByte(c, OP_OUTPUTVALUE, 'OP_OUTPUTVALUE');
2300
+ expectByte(c, OP_SWAP, 'OP_SWAP');
2301
+ expectByte(c, OP_GREATERTHANOREQUAL, 'OP_GREATERTHANOREQUAL');
2302
+ expectByte(c, OP_VERIFY, 'OP_VERIFY (payment)');
2303
+ // ───── Payment scriptPubKey check ─────
2304
+ expectByte(c, OP_0, 'OP_0 (spk idx)');
2305
+ expectByte(c, OP_OUTPUTSCRIPT, 'OP_OUTPUTSCRIPT (payment)');
2306
+ const sellerSpk = readPush(c, 'sellerScriptPubKey');
2307
+ // Must be P2PKH with our PKH.
2308
+ const expectedSpk = new Uint8Array([
2309
+ OP_DUP, OP_HASH160, 0x14, ...sellerPubKeyHash, OP_EQUALVERIFY, OP_CHECKSIG
2310
+ ]);
2311
+ if (!bytesEqual(sellerSpk, expectedSpk)) {
2312
+ throw new Error('parse: embedded seller scriptPubKey does not match the cancel PKH');
2313
+ }
2314
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (payment spk)');
2315
+ // ───── Buyer asset amount check (output 1) ─────
2316
+ expectByte(c, OP_DUP, 'OP_DUP (buyer amount)');
2317
+ expectByte(c, OP_1, 'OP_1 (buyer idx)');
2318
+ expectByte(c, OP_2, 'OP_2 (AMOUNT selector)');
2319
+ expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer amount)');
2320
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer amount)');
2321
+ // ───── Buyer asset name check (output 1) ─────
2322
+ expectByte(c, OP_1, 'OP_1 (buyer idx)');
2323
+ expectByte(c, OP_1, 'OP_1 (NAME selector)');
2324
+ expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer name)');
2325
+ const tokenIdBytes1 = readPush(c, 'tokenId #1');
2326
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer name)');
2327
+ // ───── Remainder continuity: same scriptPubKey ─────
2328
+ expectByte(c, OP_2, 'OP_2 (remainder idx)');
2329
+ expectByte(c, OP_OUTPUTSCRIPT, 'OP_OUTPUTSCRIPT (remainder)');
2330
+ expectByte(c, OP_3, 'OP_3 (TXFIELD selector)');
2331
+ expectByte(c, OP_TXFIELD, 'OP_TXFIELD');
2332
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder spk)');
2333
+ // ───── Remainder tokenId check ─────
2334
+ expectByte(c, OP_2, 'OP_2 (remainder idx)');
2335
+ expectByte(c, OP_1, 'OP_1 (NAME selector)');
2336
+ expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder name)');
2337
+ const tokenIdBytes2 = readPush(c, 'tokenId #2');
2338
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder name)');
2339
+ // ───── Remainder amount == input amount - N ─────
2340
+ expectByte(c, OP_2, 'OP_2 (remainder idx)');
2341
+ expectByte(c, OP_2, 'OP_2 (AMOUNT selector)');
2342
+ expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder amount)');
2343
+ expectByte(c, OP_OVER, 'OP_OVER');
2344
+ expectByte(c, OP_0, 'OP_0 (input idx)');
2345
+ expectByte(c, OP_2, 'OP_2 (AMOUNT selector)');
2346
+ expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD');
2347
+ expectByte(c, OP_SWAP, 'OP_SWAP');
2348
+ expectByte(c, OP_SUB, 'OP_SUB');
2349
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder amount)');
2350
+ // ───── Tail ─────
2351
+ expectByte(c, OP_DROP, 'OP_DROP');
2352
+ expectByte(c, OP_1, 'OP_1 (true)');
2353
+ expectByte(c, OP_ENDIF, 'OP_ENDIF');
2354
+ assertTrailing(c);
2355
+ if (!bytesEqual(tokenIdBytes1, tokenIdBytes2)) {
2356
+ throw new Error('parse: tokenId bytes differ between buyer and remainder checks');
2357
+ }
2358
+ const tokenId = new TextDecoder('utf-8', { fatal: true }).decode(tokenIdBytes1);
2359
+ return {
2360
+ network,
2361
+ sellerPubKeyHash,
2362
+ unitPriceSats,
2363
+ tokenId,
2364
+ scriptHex: bytesToHex(bytes)
2365
+ };
2366
+ }
2367
+
2368
+ /**
2369
+ * Parser for the PQ Partial-Fill Sell Order covenant. Returns the same
2370
+ * economic parameters as the legacy parser, plus the payment scriptPubKey
2371
+ * bytes (which may be P2PKH or AuthScript) and the configured TXHASH
2372
+ * selector.
2373
+ */
2374
+ /** Quick discriminator without throwing — useful for indexers. */
2375
+ function isPartialFillScriptPQ(script) {
2376
+ const bytes = typeof script === 'string' ? hexToBytes(script) : script;
2377
+ // PQ cancel starts with: OP_IF OP_DUP OP_SHA256
2378
+ return (bytes.length > 3 &&
2379
+ bytes[0] === OP_IF &&
2380
+ bytes[1] === OP_DUP &&
2381
+ bytes[2] === OP_SHA256);
2382
+ }
2383
+ /**
2384
+ * Parse a PQ partial-fill covenant. Throws if the bytes do not match the
2385
+ * exact layout produced by `buildPartialFillScriptPQ`.
2386
+ */
2387
+ function parsePartialFillScriptPQ(script, network = 'xna-test') {
2388
+ const bytes = typeof script === 'string' ? hexToBytes(script) : script;
2389
+ const c = makeCursor(bytes);
2390
+ // ───── Cancel branch (PQ) ─────
2391
+ expectByte(c, OP_IF, 'OP_IF');
2392
+ expectByte(c, OP_DUP, 'OP_DUP (cancel)');
2393
+ expectByte(c, OP_SHA256, 'OP_SHA256');
2394
+ const pubKeyCommitment = readPush(c, 'pubKeyCommitment');
2395
+ if (pubKeyCommitment.length !== 32) {
2396
+ throw new Error(`parse-pq: pubKeyCommitment must be 32 bytes, got ${pubKeyCommitment.length}`);
2397
+ }
2398
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (cancel)');
2399
+ const txHashSelectorBig = readPushPositiveInt(c, 'txHashSelector');
2400
+ if (txHashSelectorBig < 1n || txHashSelectorBig > 0xffn) {
2401
+ throw new Error(`parse-pq: txHashSelector out of range (${txHashSelectorBig})`);
2402
+ }
2403
+ const txHashSelector = Number(txHashSelectorBig);
2404
+ expectByte(c, OP_TXHASH, 'OP_TXHASH');
2405
+ expectByte(c, OP_SWAP, 'OP_SWAP');
2406
+ expectByte(c, OP_CHECKSIGFROMSTACK, 'OP_CHECKSIGFROMSTACK');
2407
+ expectByte(c, OP_ELSE, 'OP_ELSE');
2408
+ // ───── Fill branch ─────
2409
+ expectByte(c, OP_DUP, 'OP_DUP (price)');
2410
+ const unitPriceSats = readPushPositiveInt(c, 'unitPriceSats');
2411
+ expectByte(c, OP_MUL, 'OP_MUL');
2412
+ expectByte(c, OP_0, 'OP_0 (payment idx)');
2413
+ expectByte(c, OP_OUTPUTVALUE, 'OP_OUTPUTVALUE');
2414
+ expectByte(c, OP_SWAP, 'OP_SWAP');
2415
+ expectByte(c, OP_GREATERTHANOREQUAL, 'OP_GE');
2416
+ expectByte(c, OP_VERIFY, 'OP_VERIFY');
2417
+ expectByte(c, OP_0, 'OP_0 (payment spk idx)');
2418
+ expectByte(c, OP_OUTPUTSCRIPT, 'OP_OUTPUTSCRIPT (payment)');
2419
+ const paymentScriptPubKey = readPush(c, 'paymentScriptPubKey');
2420
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (payment)');
2421
+ expectByte(c, OP_DUP, 'OP_DUP (buyer amount)');
2422
+ expectByte(c, OP_1, 'OP_1 (buyer idx)');
2423
+ expectByte(c, OP_2, 'OP_2 (AMOUNT selector)');
2424
+ expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer amount)');
2425
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer amount)');
2426
+ expectByte(c, OP_1, 'OP_1 (buyer idx)');
2427
+ expectByte(c, OP_1, 'OP_1 (NAME selector)');
2428
+ expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer name)');
2429
+ const tokenIdBytes1 = readPush(c, 'tokenId #1');
2430
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer name)');
2431
+ expectByte(c, OP_2, 'OP_2 (remainder idx)');
2432
+ expectByte(c, OP_OUTPUTSCRIPT, 'OP_OUTPUTSCRIPT (remainder)');
2433
+ expectByte(c, OP_3, 'OP_3 (TXFIELD selector)');
2434
+ expectByte(c, OP_TXFIELD, 'OP_TXFIELD');
2435
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder spk)');
2436
+ expectByte(c, OP_2, 'OP_2 (remainder idx)');
2437
+ expectByte(c, OP_1, 'OP_1 (NAME selector)');
2438
+ expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder name)');
2439
+ const tokenIdBytes2 = readPush(c, 'tokenId #2');
2440
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder name)');
2441
+ expectByte(c, OP_2, 'OP_2 (remainder idx)');
2442
+ expectByte(c, OP_2, 'OP_2 (AMOUNT selector)');
2443
+ expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder amount)');
2444
+ expectByte(c, OP_OVER, 'OP_OVER');
2445
+ expectByte(c, OP_0, 'OP_0 (input idx)');
2446
+ expectByte(c, OP_2, 'OP_2 (AMOUNT selector)');
2447
+ expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD');
2448
+ expectByte(c, OP_SWAP, 'OP_SWAP');
2449
+ expectByte(c, OP_SUB, 'OP_SUB');
2450
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder amount)');
2451
+ expectByte(c, OP_DROP, 'OP_DROP');
2452
+ expectByte(c, OP_1, 'OP_1 (true)');
2453
+ expectByte(c, OP_ENDIF, 'OP_ENDIF');
2454
+ assertTrailing(c);
2455
+ if (!bytesEqual(tokenIdBytes1, tokenIdBytes2)) {
2456
+ throw new Error('parse-pq: tokenId differs between buyer and remainder checks');
2457
+ }
2458
+ const tokenId = new TextDecoder('utf-8', { fatal: true }).decode(tokenIdBytes1);
2459
+ return {
2460
+ network,
2461
+ pubKeyCommitment,
2462
+ tokenId,
2463
+ unitPriceSats,
2464
+ txHashSelector,
2465
+ paymentScriptPubKey,
2466
+ scriptHex: bytesToHex(bytes)
2467
+ };
2468
+ }
2469
+
2470
+ export { AUTHSCRIPT_LEGACY, AUTHSCRIPT_NOAUTH, AUTHSCRIPT_PQ, AUTHSCRIPT_REF, DEFAULT_PQ_TXHASH_SELECTOR, MULTISIG_MAX_PUBKEYS, NULLDATA_STANDARD_MAX_SIZE, ScriptBuilder, buildAuthScriptWitnessLegacy, buildAuthScriptWitnessNoAuth, buildAuthScriptWitnessPQ, buildAuthScriptWitnessRef, buildCancelScriptSig, buildCancelScriptSigHex, buildCancelScriptSigPQ, buildCancelScriptSigPQHex, buildFillScriptSig, buildFillScriptSigHex, buildPartialFillScript, buildPartialFillScriptHex, buildPartialFillScriptPQ, buildPartialFillScriptPQHex, bytesEqual, bytesToHex, concatBytes, encodeAuthScriptScriptPubKey, encodeMultisigRedeemScript, encodeMultisigRedeemScriptHex, encodeNullDataScript, encodeP2PKHScriptPubKey, encodeP2SHScriptPubKey, encodeP2WPKHScriptPubKey, encodeP2WSHScriptPubKey, encodeScriptNum, encodeSellerScriptPubKey, ensureHex, hexToBytes, isPartialFillScriptPQ, opcodes, parsePartialFillScript, parsePartialFillScriptPQ, pushBytes, pushHex, pushInt, splitAssetWrappedScriptPubKey };
2471
+ //# sourceMappingURL=browser.js.map