@neuraiproject/neurai-scripts 0.9.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/browser.js CHANGED
@@ -241,20 +241,27 @@ const CHAINCONTEXT_CHAIN_ID = 0x03;
241
241
  // Native Merkle inclusion verifier. Consumes (leaf, scheme_id, proof,
242
242
  // root) and pushes a boolean. Flag off → bad-opcode.
243
243
  const OP_CHECKMERKLEINCLUSION = 0xc1;
244
+ // NIP-041: (outputIndex -- witnessVersion || 32-byte program).
245
+ const OP_OUTPUTAUTHDEST = 0xc2;
246
+ // NIP-018: verifies an AuthScript proof and returns a boolean.
247
+ const OP_ZKVERIFY = 0xc3;
248
+ // NIP-043: spent-input field introspection, distinct from reference inputs.
249
+ const OP_INPUTFIELD = 0xc4;
244
250
  // ---------- Byte manipulation (DePIN-Test) ----------
245
251
  const OP_CAT = 0x7e;
246
252
  const OP_SPLIT = 0xb7;
247
253
  const OP_REVERSEBYTES = 0xbc;
248
254
  // ---------- Selectors for OP_TXFIELD / OP_REFINPUTFIELD ----------
249
- // Both opcodes share the same selector table (OP_TXFIELD on the spent UTXO,
250
- // OP_REFINPUTFIELD on an output referenced via vrefin). Valid: 0x01..0x03.
255
+ // OP_TXFIELD, OP_INPUTFIELD and OP_REFINPUTFIELD share selectors 0x01..0x03.
256
+ // NIP-041 adds 0x04 for a strict 33-byte AuthScript destination.
251
257
  const TXFIELD_VALUE = 0x01;
252
258
  const TXFIELD_AUTHSCRIPT_COMMITMENT = 0x02;
253
259
  const TXFIELD_SCRIPTPUBKEY = 0x03;
260
+ const TXFIELD_AUTHDEST = 0x04;
254
261
  // ---------- Bitmask selectors for OP_TXHASH ----------
255
- // The selector is a single byte where each bit selects which transaction
256
- // field to include in the double-SHA256. Selector 0x00 is invalid; any
257
- // non-zero combination is valid. 0xff = all eight fields.
262
+ // NIP-042 requires a two-byte little-endian selector, even for low masks.
263
+ // Bits 0..8 select fields for the tagged NeuraiTxHash digest. Valid masks
264
+ // are 0x001..0x1ff; zero and all higher bits are rejected by consensus.
258
265
  const TXHASH_VERSION = 0x01;
259
266
  const TXHASH_LOCKTIME = 0x02;
260
267
  const TXHASH_INPUT_PREVOUTS = 0x04;
@@ -263,12 +270,11 @@ const TXHASH_OUTPUTS = 0x10;
263
270
  const TXHASH_CURRENT_PREVOUT = 0x20;
264
271
  const TXHASH_CURRENT_SEQUENCE = 0x40;
265
272
  const TXHASH_CURRENT_INDEX = 0x80;
266
- const TXHASH_ALL = 0xff;
273
+ const TXHASH_REFINPUTS = 0x100;
274
+ const TXHASH_ALL = 0x1ff;
267
275
  // ---------- Selectors for OP_OUTPUTASSETFIELD / OP_INPUTASSETFIELD / OP_REFINPUTASSETFIELD ----------
268
- // All three opcodes share the same selector table. Valid range: 0x01..0x07.
269
- // Selector 0x05 is the boolean "has IPFS" flag; 0x06 is the IPFS hash
270
- // payload; 0x07 is the asset operation type. (This matches the asset-op
271
- // encoding in `src/assets/assets.cpp` and the NIP spec §3.1.)
276
+ // All three opcodes share this selector table. 0x08 is gated by NIP-043
277
+ // and extracts the optional transfer message from a strict asset wrapper.
272
278
  const ASSETFIELD_NAME = 0x01;
273
279
  const ASSETFIELD_AMOUNT = 0x02;
274
280
  const ASSETFIELD_UNITS = 0x03;
@@ -276,12 +282,20 @@ const ASSETFIELD_REISSUABLE = 0x04;
276
282
  const ASSETFIELD_HAS_IPFS = 0x05;
277
283
  const ASSETFIELD_IPFS_HASH = 0x06;
278
284
  const ASSETFIELD_TYPE = 0x07;
285
+ const ASSETFIELD_MESSAGE = 0x08;
286
+ // NIP-031/043 Merkle inclusion scheme identifiers.
287
+ const MERKLE_SCHEME_BITCOIN_NEURAI = 0x01;
288
+ const MERKLE_SCHEME_SHA256_PLAIN = 0x02;
289
+ const MERKLE_SCHEME_KECCAK256_PLAIN = 0x03;
290
+ const MERKLE_SCHEME_BLAKE2B_PLAIN = 0x04;
291
+ const MERKLE_SCHEME_POSEIDON_BN254 = 0x05;
279
292
 
280
293
  var opcodes = /*#__PURE__*/Object.freeze({
281
294
  __proto__: null,
282
295
  ASSETFIELD_AMOUNT: ASSETFIELD_AMOUNT,
283
296
  ASSETFIELD_HAS_IPFS: ASSETFIELD_HAS_IPFS,
284
297
  ASSETFIELD_IPFS_HASH: ASSETFIELD_IPFS_HASH,
298
+ ASSETFIELD_MESSAGE: ASSETFIELD_MESSAGE,
285
299
  ASSETFIELD_NAME: ASSETFIELD_NAME,
286
300
  ASSETFIELD_REISSUABLE: ASSETFIELD_REISSUABLE,
287
301
  ASSETFIELD_TYPE: ASSETFIELD_TYPE,
@@ -289,6 +303,11 @@ var opcodes = /*#__PURE__*/Object.freeze({
289
303
  CHAINCONTEXT_CHAIN_ID: CHAINCONTEXT_CHAIN_ID,
290
304
  CHAINCONTEXT_HEIGHT: CHAINCONTEXT_HEIGHT,
291
305
  CHAINCONTEXT_MTP: CHAINCONTEXT_MTP,
306
+ MERKLE_SCHEME_BITCOIN_NEURAI: MERKLE_SCHEME_BITCOIN_NEURAI,
307
+ MERKLE_SCHEME_BLAKE2B_PLAIN: MERKLE_SCHEME_BLAKE2B_PLAIN,
308
+ MERKLE_SCHEME_KECCAK256_PLAIN: MERKLE_SCHEME_KECCAK256_PLAIN,
309
+ MERKLE_SCHEME_POSEIDON_BN254: MERKLE_SCHEME_POSEIDON_BN254,
310
+ MERKLE_SCHEME_SHA256_PLAIN: MERKLE_SCHEME_SHA256_PLAIN,
292
311
  OP_0: OP_0,
293
312
  OP_0NOTEQUAL: OP_0NOTEQUAL,
294
313
  OP_1: OP_1,
@@ -354,6 +373,7 @@ var opcodes = /*#__PURE__*/Object.freeze({
354
373
  OP_IFDUP: OP_IFDUP,
355
374
  OP_INPUTASSETFIELD: OP_INPUTASSETFIELD,
356
375
  OP_INPUTCOUNT: OP_INPUTCOUNT,
376
+ OP_INPUTFIELD: OP_INPUTFIELD,
357
377
  OP_INPUTVALUE: OP_INPUTVALUE,
358
378
  OP_KECCAK256: OP_KECCAK256,
359
379
  OP_LESSTHAN: OP_LESSTHAN,
@@ -375,6 +395,7 @@ var opcodes = /*#__PURE__*/Object.freeze({
375
395
  OP_NUMNOTEQUAL: OP_NUMNOTEQUAL,
376
396
  OP_OUTPUTASSETFIELD: OP_OUTPUTASSETFIELD,
377
397
  OP_OUTPUTAUTHCOMMITMENT: OP_OUTPUTAUTHCOMMITMENT,
398
+ OP_OUTPUTAUTHDEST: OP_OUTPUTAUTHDEST,
378
399
  OP_OUTPUTCOUNT: OP_OUTPUTCOUNT,
379
400
  OP_OUTPUTSCRIPT: OP_OUTPUTSCRIPT,
380
401
  OP_OUTPUTVALUE: OP_OUTPUTVALUE,
@@ -410,6 +431,8 @@ var opcodes = /*#__PURE__*/Object.freeze({
410
431
  OP_VERIFY: OP_VERIFY,
411
432
  OP_WITHIN: OP_WITHIN,
412
433
  OP_XNA_ASSET: OP_XNA_ASSET,
434
+ OP_ZKVERIFY: OP_ZKVERIFY,
435
+ TXFIELD_AUTHDEST: TXFIELD_AUTHDEST,
413
436
  TXFIELD_AUTHSCRIPT_COMMITMENT: TXFIELD_AUTHSCRIPT_COMMITMENT,
414
437
  TXFIELD_SCRIPTPUBKEY: TXFIELD_SCRIPTPUBKEY,
415
438
  TXFIELD_VALUE: TXFIELD_VALUE,
@@ -421,6 +444,7 @@ var opcodes = /*#__PURE__*/Object.freeze({
421
444
  TXHASH_INPUT_SEQUENCES: TXHASH_INPUT_SEQUENCES,
422
445
  TXHASH_LOCKTIME: TXHASH_LOCKTIME,
423
446
  TXHASH_OUTPUTS: TXHASH_OUTPUTS,
447
+ TXHASH_REFINPUTS: TXHASH_REFINPUTS,
424
448
  TXHASH_VERSION: TXHASH_VERSION
425
449
  });
426
450
 
@@ -2096,16 +2120,9 @@ function readPushPositiveInt(c, label) {
2096
2120
  return decodeScriptNum(data, label);
2097
2121
  }
2098
2122
  /**
2099
- * Read a 1-byte selector as an UNSIGNED 8-bit integer (0..255). Accepts
2100
- * two on-wire encodings, because old vs new covenant builders differ:
2101
- * - `OP_1..OP_16` shorthand (single opcode) → values 1..16.
2102
- * - `0x01 <byte>` raw 1-byte push → any value 1..255.
2103
- *
2104
- * Values 0x80..0xff MUST use the raw-push form; the CScriptNum encoding
2105
- * would need a 0x00 padding byte and become 2 bytes on-stack, which
2106
- * consensus `OP_TXHASH` rejects. The builder in `script-pq.ts` emits the
2107
- * raw-push form unconditionally; the parser stays lenient so covenants
2108
- * built by older tools (using OP_N for small values) still round-trip.
2123
+ * Read a one-byte unsigned selector. This accepts OP_1..OP_16 shorthand
2124
+ * and a raw one-byte push for scripts that permit either form. NIP-042
2125
+ * TXHASH masks use a separate strict two-byte parser.
2109
2126
  */
2110
2127
  function readPushUint8(c, label) {
2111
2128
  if (c.pos >= c.bytes.length) {
@@ -2192,7 +2209,224 @@ function assertSameExpiration(a, b, label) {
2192
2209
  }
2193
2210
 
2194
2211
  /**
2195
- * Partial-Fill Sell Order covenant script (three-branch).
2212
+ * Buyer fill branches shared by both Partial-Fill Sell Order variants
2213
+ * (ECDSA cancel in `./script.ts`, ML-DSA-44 cancel in `./script-pq.ts`).
2214
+ * The variants only differ in their cancel branch; everything after the
2215
+ * outer `OP_ELSE` is emitted and parsed here.
2216
+ *
2217
+ * Input-0 binding. The fill branches read the order's asset amount with
2218
+ * `<0> OP_INPUTASSETFIELD` and constrain outputs 0..2 by fixed index. Input
2219
+ * indices are absolute and Script cannot ask for the index of the input
2220
+ * being evaluated, so without a binding a buyer could:
2221
+ * - put a foreign asset UTXO at input 0 and the order at input 1: the
2222
+ * order then prices the fill by the foreign amount and the rest of the
2223
+ * order leaves through an unconstrained output;
2224
+ * - spend several identical orders together, every one of them satisfied
2225
+ * by the same payment output.
2226
+ * The fill block therefore opens with
2227
+ *
2228
+ * <0x80 0x00> OP_TXHASH <INPUT_ZERO_TXHASH> OP_EQUALVERIFY
2229
+ *
2230
+ * NIP-042 mask 0x0080 commits only to the index of the input being
2231
+ * evaluated, so the digest equals the constant exactly when this covenant
2232
+ * is spent as input 0. At most one order per transaction can take a fill
2233
+ * branch; the seller's cancel branch is not bound.
2234
+ *
2235
+ * Layout (after the variant's `OP_IF <cancel> OP_ELSE`):
2236
+ *
2237
+ * <0x80 0x00> OP_TXHASH <INPUT_ZERO_TXHASH> OP_EQUALVERIFY
2238
+ * OP_IF ← full fill, unlock <1> <0>
2239
+ * [expiration gate]
2240
+ * <0> <2> OP_INPUTASSETFIELD (N = order amount)
2241
+ * DUP <price> MUL <0> OUTPUTVALUE SWAP GE VERIFY (payment value)
2242
+ * <0> OUTPUTSCRIPT <paymentSpk> EQUALVERIFY (payment destination)
2243
+ * DUP <1> <2> OUTPUTASSETFIELD EQUALVERIFY (buyer amount == N)
2244
+ * <1> <1> OUTPUTASSETFIELD <tokenId> EQUALVERIFY (buyer asset name)
2245
+ * DROP <1>
2246
+ * OP_ELSE ← partial fill, unlock <N> <0> <0>
2247
+ * [expiration gate]
2248
+ * payment value, payment destination, buyer amount, buyer name (as above)
2249
+ * <2> OUTPUTAUTHCOMMITMENT <2> TXFIELD EQUALVERIFY (continuation, NIP-023)
2250
+ * <2> <1> OUTPUTASSETFIELD <tokenId> EQUALVERIFY (continuation name)
2251
+ * <2> <2> OUTPUTASSETFIELD OVER <0> <2> INPUTASSETFIELD SWAP SUB EQUALVERIFY
2252
+ * DROP <1>
2253
+ * OP_ENDIF
2254
+ */
2255
+ /** NIP-042 mask (two bytes, little-endian) selecting only the current input index. */
2256
+ const INPUT_INDEX_TXHASH_SELECTOR = Uint8Array.of(TXHASH_CURRENT_INDEX, 0x00);
2257
+ /**
2258
+ * `OP_TXHASH(0x0080)` evaluated at input 0:
2259
+ * `SHA256(tag || tag || 80 00 || 00 00 00 00)` with `tag = SHA256("NeuraiTxHash")`.
2260
+ */
2261
+ const INPUT_ZERO_TXHASH = hexToBytes('419632cabaf8bb70b96a8c92c4601a9c2ba11e96841daebc9d98f4835eeb0e36');
2262
+ function appendPaymentAndBuyerChecks(b, p) {
2263
+ // output[0].value >= N * unitPriceSats [ N ]
2264
+ b.op(OP_DUP)
2265
+ .pushInt(p.unitPriceSats)
2266
+ .op(OP_MUL)
2267
+ .pushInt(0)
2268
+ .op(OP_OUTPUTVALUE)
2269
+ .op(OP_SWAP)
2270
+ .op(OP_GREATERTHANOREQUAL)
2271
+ .op(OP_VERIFY);
2272
+ // output[0].scriptPubKey == paymentScriptPubKey [ N ]
2273
+ b.pushInt(0)
2274
+ .op(OP_OUTPUTSCRIPT)
2275
+ .pushBytes(p.paymentScriptPubKey)
2276
+ .op(OP_EQUALVERIFY);
2277
+ // output[1].asset.amount == N [ N ]
2278
+ b.op(OP_DUP)
2279
+ .pushInt(1)
2280
+ .pushInt(ASSETFIELD_AMOUNT)
2281
+ .op(OP_OUTPUTASSETFIELD)
2282
+ .op(OP_EQUALVERIFY);
2283
+ // output[1].asset.name == tokenId [ N ]
2284
+ b.pushInt(1)
2285
+ .pushInt(ASSETFIELD_NAME)
2286
+ .op(OP_OUTPUTASSETFIELD)
2287
+ .pushBytes(p.tokenIdBytes)
2288
+ .op(OP_EQUALVERIFY);
2289
+ }
2290
+ /** Emit the input-0 binding and both fill branches, ending with the inner `OP_ENDIF`. */
2291
+ function appendFillBranches(b, p) {
2292
+ b.pushBytes(INPUT_INDEX_TXHASH_SELECTOR)
2293
+ .op(OP_TXHASH)
2294
+ .pushBytes(INPUT_ZERO_TXHASH)
2295
+ .op(OP_EQUALVERIFY);
2296
+ // ──────── Full fill: N is the whole order, no continuation ────────
2297
+ b.op(OP_IF);
2298
+ appendExpirationGate(b, p.expiration);
2299
+ b.pushInt(0)
2300
+ .pushInt(ASSETFIELD_AMOUNT)
2301
+ .op(OP_INPUTASSETFIELD); // [ N ]
2302
+ appendPaymentAndBuyerChecks(b, p);
2303
+ b.op(OP_DROP).pushInt(1);
2304
+ // ──────── Partial fill: buyer pushes N, remainder continues at output 2 ────────
2305
+ b.op(OP_ELSE);
2306
+ appendExpirationGate(b, p.expiration);
2307
+ appendPaymentAndBuyerChecks(b, p);
2308
+ // Continuation keeps the spent order's AuthScript commitment (NIP-023).
2309
+ b.pushInt(2)
2310
+ .op(OP_OUTPUTAUTHCOMMITMENT)
2311
+ .pushInt(TXFIELD_AUTHSCRIPT_COMMITMENT)
2312
+ .op(OP_TXFIELD)
2313
+ .op(OP_EQUALVERIFY);
2314
+ b.pushInt(2)
2315
+ .pushInt(ASSETFIELD_NAME)
2316
+ .op(OP_OUTPUTASSETFIELD)
2317
+ .pushBytes(p.tokenIdBytes)
2318
+ .op(OP_EQUALVERIFY);
2319
+ // output[2].asset.amount == orderAmount - N
2320
+ b.pushInt(2)
2321
+ .pushInt(ASSETFIELD_AMOUNT)
2322
+ .op(OP_OUTPUTASSETFIELD) // [ N, rem ]
2323
+ .op(OP_OVER) // [ N, rem, N ]
2324
+ .pushInt(0)
2325
+ .pushInt(ASSETFIELD_AMOUNT)
2326
+ .op(OP_INPUTASSETFIELD) // [ N, rem, N, in ]
2327
+ .op(OP_SWAP) // [ N, rem, in, N ]
2328
+ .op(OP_SUB) // [ N, rem, in - N ]
2329
+ .op(OP_EQUALVERIFY);
2330
+ b.op(OP_DROP).pushInt(1);
2331
+ b.op(OP_ENDIF);
2332
+ }
2333
+ function readPaymentAndBuyerChecks(c, label) {
2334
+ expectByte(c, OP_DUP, `OP_DUP (price, ${label})`);
2335
+ const unitPriceSats = readPushPositiveInt(c, `unitPriceSats (${label})`);
2336
+ expectByte(c, OP_MUL, `OP_MUL (${label})`);
2337
+ expectByte(c, OP_0, `OP_0 (payment idx, ${label})`);
2338
+ expectByte(c, OP_OUTPUTVALUE, `OP_OUTPUTVALUE (${label})`);
2339
+ expectByte(c, OP_SWAP, `OP_SWAP (${label})`);
2340
+ expectByte(c, OP_GREATERTHANOREQUAL, `OP_GREATERTHANOREQUAL (${label})`);
2341
+ expectByte(c, OP_VERIFY, `OP_VERIFY (payment, ${label})`);
2342
+ expectByte(c, OP_0, `OP_0 (spk idx, ${label})`);
2343
+ expectByte(c, OP_OUTPUTSCRIPT, `OP_OUTPUTSCRIPT (${label})`);
2344
+ const paymentScriptPubKey = readPush(c, `paymentScriptPubKey (${label})`);
2345
+ expectByte(c, OP_EQUALVERIFY, `OP_EQUALVERIFY (payment spk, ${label})`);
2346
+ expectByte(c, OP_DUP, `OP_DUP (buyer amount, ${label})`);
2347
+ expectByte(c, OP_1, `OP_1 (buyer idx, ${label})`);
2348
+ expectByte(c, OP_2, `OP_2 (AMOUNT sel, ${label})`);
2349
+ expectByte(c, OP_OUTPUTASSETFIELD, `OP_OUTPUTASSETFIELD (buyer amount, ${label})`);
2350
+ expectByte(c, OP_EQUALVERIFY, `OP_EQUALVERIFY (buyer amount, ${label})`);
2351
+ expectByte(c, OP_1, `OP_1 (buyer idx, ${label})`);
2352
+ expectByte(c, OP_1, `OP_1 (NAME sel, ${label})`);
2353
+ expectByte(c, OP_OUTPUTASSETFIELD, `OP_OUTPUTASSETFIELD (buyer name, ${label})`);
2354
+ const tokenId = readPush(c, `tokenId (${label})`);
2355
+ expectByte(c, OP_EQUALVERIFY, `OP_EQUALVERIFY (buyer name, ${label})`);
2356
+ return { unitPriceSats, paymentScriptPubKey, tokenId };
2357
+ }
2358
+ /**
2359
+ * Parse what `appendFillBranches` emits. Both branches must agree on price,
2360
+ * payment destination, tokenId and expiration; any deviation throws.
2361
+ */
2362
+ function readFillBranches(c) {
2363
+ const selector = readPush(c, 'input-0 binding selector');
2364
+ if (!bytesEqual(selector, INPUT_INDEX_TXHASH_SELECTOR)) {
2365
+ throw new Error('parse: fill branches must open with the input-0 binding <0x8000> OP_TXHASH (covenants without it ' +
2366
+ 'can be drained through a foreign input 0 and are not supported)');
2367
+ }
2368
+ expectByte(c, OP_TXHASH, 'OP_TXHASH (input-0 binding)');
2369
+ const digest = readPush(c, 'input-0 binding digest');
2370
+ if (!bytesEqual(digest, INPUT_ZERO_TXHASH)) {
2371
+ throw new Error('parse: input-0 binding digest is not OP_TXHASH(0x0080) at input 0');
2372
+ }
2373
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (input-0 binding)');
2374
+ // ═════ Full fill ═════
2375
+ expectByte(c, OP_IF, 'OP_IF (full fill)');
2376
+ const expirationFull = readOptionalExpirationGate(c, OP_0, 'full');
2377
+ expectByte(c, OP_0, 'OP_0 (input idx, full)');
2378
+ expectByte(c, OP_2, 'OP_2 (AMOUNT sel, full)');
2379
+ expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD (full)');
2380
+ const full = readPaymentAndBuyerChecks(c, 'full');
2381
+ expectByte(c, OP_DROP, 'OP_DROP (full)');
2382
+ expectByte(c, OP_1, 'OP_1 (true, full)');
2383
+ // ═════ Partial fill ═════
2384
+ expectByte(c, OP_ELSE, 'OP_ELSE (partial fill)');
2385
+ const expirationPartial = readOptionalExpirationGate(c, OP_DUP, 'partial');
2386
+ const partial = readPaymentAndBuyerChecks(c, 'partial');
2387
+ expectByte(c, OP_2, 'OP_2 (remainder idx)');
2388
+ expectByte(c, OP_OUTPUTAUTHCOMMITMENT, 'OP_OUTPUTAUTHCOMMITMENT (remainder)');
2389
+ expectByte(c, OP_2, 'OP_2 (TXFIELD sel: AUTHSCRIPT_COMMITMENT)');
2390
+ expectByte(c, OP_TXFIELD, 'OP_TXFIELD');
2391
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder auth)');
2392
+ expectByte(c, OP_2, 'OP_2 (remainder idx)');
2393
+ expectByte(c, OP_1, 'OP_1 (NAME sel)');
2394
+ expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder name)');
2395
+ const remainderTokenId = readPush(c, 'tokenId (remainder)');
2396
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder name)');
2397
+ expectByte(c, OP_2, 'OP_2 (remainder idx)');
2398
+ expectByte(c, OP_2, 'OP_2 (AMOUNT sel)');
2399
+ expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder amount)');
2400
+ expectByte(c, OP_OVER, 'OP_OVER');
2401
+ expectByte(c, OP_0, 'OP_0 (input idx)');
2402
+ expectByte(c, OP_2, 'OP_2 (AMOUNT sel)');
2403
+ expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD');
2404
+ expectByte(c, OP_SWAP, 'OP_SWAP');
2405
+ expectByte(c, OP_SUB, 'OP_SUB');
2406
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder amount)');
2407
+ expectByte(c, OP_DROP, 'OP_DROP (partial)');
2408
+ expectByte(c, OP_1, 'OP_1 (true, partial)');
2409
+ expectByte(c, OP_ENDIF, 'OP_ENDIF (fill branches)');
2410
+ if (!bytesEqual(full.tokenId, partial.tokenId) || !bytesEqual(partial.tokenId, remainderTokenId)) {
2411
+ throw new Error('parse: tokenId differs between the fill checks');
2412
+ }
2413
+ if (full.unitPriceSats !== partial.unitPriceSats) {
2414
+ throw new Error('parse: unitPriceSats differs between full-fill and partial-fill branches');
2415
+ }
2416
+ if (!bytesEqual(full.paymentScriptPubKey, partial.paymentScriptPubKey)) {
2417
+ throw new Error('parse: payment scriptPubKey differs between full-fill and partial-fill branches');
2418
+ }
2419
+ assertSameExpiration(expirationFull, expirationPartial, 'full-fill and partial-fill branches');
2420
+ return {
2421
+ paymentScriptPubKey: full.paymentScriptPubKey,
2422
+ tokenId: new TextDecoder('utf-8', { fatal: true }).decode(full.tokenId),
2423
+ unitPriceSats: full.unitPriceSats,
2424
+ expiration: expirationFull
2425
+ };
2426
+ }
2427
+
2428
+ /**
2429
+ * Partial-Fill Sell Order covenant script (three-branch), ECDSA cancel.
2196
2430
  *
2197
2431
  * The covenant has three branches selected by the top of the unlock stack:
2198
2432
  *
@@ -2212,11 +2446,8 @@ function assertSameExpiration(a, b, label) {
2212
2446
  * amount == inputAmount - N)
2213
2447
  * output[3+] = optional buyer change (not constrained by the covenant)
2214
2448
  *
2215
- * Continuity — the remainder UTXO reuses the spent covenant's AuthScript v1
2216
- * commitment via `OP_OUTPUTAUTHCOMMITMENT(2) == OP_TXFIELD(0x02)` (NIP-023).
2217
- * Comparing commitments rather than full scriptPubKeys is mandatory because
2218
- * the remainder's asset wrapper carries a different `amountRaw` than the
2219
- * spent UTXO's wrapper.
2449
+ * The order must be input 0 for either fill branch to succeed: see the
2450
+ * input-0 binding in `./fill-branches.ts`.
2220
2451
  *
2221
2452
  * Unlock stack shapes (scriptSig pushes, top → bottom):
2222
2453
  *
@@ -2224,10 +2455,12 @@ function assertSameExpiration(a, b, label) {
2224
2455
  * Full fill: <1> <0> (full-flag=1, cancel-flag=0)
2225
2456
  * Partial fill: <N> <0> <0> (N, full-flag=0, cancel-flag=0)
2226
2457
  *
2227
- * The cancel branch uses classical ECDSA (`OP_HASH160 + OP_CHECKSIG`) and
2228
- * commits to a 20-byte PKH — this variant only accepts legacy P2PKH
2229
- * addresses as the seller destination. For AuthScript bech32m destinations
2230
- * and post-quantum signing, use `buildPartialFillScriptPQ`.
2458
+ * The cancel branch uses classical ECDSA (`OP_HASH160 + OP_CHECKSIG`)
2459
+ * against a 20-byte key hash. The payment destination is independent of
2460
+ * that key: a legacy P2PKH seller passes `sellerAddress` (both at once),
2461
+ * any other seller with a secp256k1 key — typically a strict ECDSA v3
2462
+ * `nq1r…` wallet — passes `paymentAddress` and `sellerPubKeyHash`. For
2463
+ * post-quantum cancellation use `buildPartialFillScriptPQ`.
2231
2464
  */
2232
2465
  const ASSET_NAME_MAX$1 = 32;
2233
2466
  function decodeSellerAddress(sellerAddress) {
@@ -2236,8 +2469,8 @@ function decodeSellerAddress(sellerAddress) {
2236
2469
  }
2237
2470
  const decoded = decodeAddress(sellerAddress);
2238
2471
  if (decoded.type !== 'p2pkh') {
2239
- throw new Error(`sellerAddress must be a legacy P2PKH address (the legacy partial-fill covenant uses OP_HASH160 + OP_CHECKSIG); ` +
2240
- `got ${decoded.type}. Use buildPartialFillScriptPQ for AuthScript destinations.`);
2472
+ throw new Error(`sellerAddress must be a legacy P2PKH address; got ${decoded.type}. A seller with another address ` +
2473
+ `type passes paymentAddress and sellerPubKeyHash, or uses buildPartialFillScriptPQ for a PQ key.`);
2241
2474
  }
2242
2475
  const pkh = Uint8Array.from(decoded.hash);
2243
2476
  if (pkh.length !== 20) {
@@ -2245,6 +2478,27 @@ function decodeSellerAddress(sellerAddress) {
2245
2478
  }
2246
2479
  return pkh;
2247
2480
  }
2481
+ /** Cancel key hash and payment scriptPubKey from either form of seller params. */
2482
+ function resolveSeller(params) {
2483
+ const { sellerAddress, paymentAddress, sellerPubKeyHash } = params;
2484
+ if (sellerAddress !== undefined) {
2485
+ if (paymentAddress !== undefined || sellerPubKeyHash !== undefined) {
2486
+ throw new Error('pass either sellerAddress, or paymentAddress with sellerPubKeyHash, not both');
2487
+ }
2488
+ const pkh = decodeSellerAddress(sellerAddress);
2489
+ return { sellerPubKeyHash: pkh, paymentScriptPubKey: encodeP2PKHScriptPubKey(pkh) };
2490
+ }
2491
+ if (paymentAddress === undefined || sellerPubKeyHash === undefined) {
2492
+ throw new Error('sellerAddress, or paymentAddress with sellerPubKeyHash, is required');
2493
+ }
2494
+ if (!(sellerPubKeyHash instanceof Uint8Array) || sellerPubKeyHash.length !== 20) {
2495
+ throw new Error('sellerPubKeyHash must be a 20-byte Uint8Array (HASH160 of the compressed public key)');
2496
+ }
2497
+ return {
2498
+ sellerPubKeyHash: Uint8Array.from(sellerPubKeyHash),
2499
+ paymentScriptPubKey: encodeSellerScriptPubKey(paymentAddress).bytes
2500
+ };
2501
+ }
2248
2502
  function assertTokenId$1(tokenId) {
2249
2503
  if (typeof tokenId !== 'string' || tokenId.length === 0) {
2250
2504
  throw new Error('tokenId is required');
@@ -2272,13 +2526,11 @@ function assertPrice$1(priceSats) {
2272
2526
  * Returns raw bytes; wrap with `bytesToHex` for wire format.
2273
2527
  */
2274
2528
  function buildPartialFillScript(params) {
2275
- const { sellerAddress, tokenId, unitPriceSats } = params;
2276
- const sellerPubKeyHash = decodeSellerAddress(sellerAddress);
2529
+ const { tokenId, unitPriceSats } = params;
2530
+ const { sellerPubKeyHash, paymentScriptPubKey } = resolveSeller(params);
2277
2531
  assertTokenId$1(tokenId);
2278
2532
  assertPrice$1(unitPriceSats);
2279
2533
  const expiration = assertExpiration(params.expiration);
2280
- const sellerScriptPubKey = encodeP2PKHScriptPubKey(sellerPubKeyHash);
2281
- const tokenIdBytes = new TextEncoder().encode(tokenId);
2282
2534
  const b = new ScriptBuilder();
2283
2535
  // ════════ Cancel branch (outer IF) ════════
2284
2536
  // scriptSig: <sig> <pubkey> <1>
@@ -2287,107 +2539,13 @@ function buildPartialFillScript(params) {
2287
2539
  .pushBytes(sellerPubKeyHash)
2288
2540
  .op(OP_EQUALVERIFY, OP_CHECKSIG)
2289
2541
  .op(OP_ELSE);
2290
- // ════════ Fill branches (outer ELSE: inner IF/ELSE) ════════
2291
- b.op(OP_IF);
2292
- // ──────── Full-fill branch (inner IF) ────────
2293
- // scriptSig: <1> <0> ( full-flag=1, cancel-flag=0 )
2294
- // Stack entering: [ ]
2295
- //
2296
- // N is derived from the spent UTXO's asset amount, so the buyer does not
2297
- // push N. The entire covenant is drained to vout[1]; no vout[2] is
2298
- // constrained and none is required (consensus forbids zero-amount asset
2299
- // transfers, so the partial-fill continuity check is simply skipped).
2300
- appendExpirationGate(b, expiration);
2301
- // 1. N = inputAmount
2302
- b.pushInt(0)
2303
- .pushInt(ASSETFIELD_AMOUNT)
2304
- .op(OP_INPUTASSETFIELD); // [ N ]
2305
- // 2. output[0].value >= N * unitPriceSats
2306
- b.op(OP_DUP) // [ N, N ]
2307
- .pushInt(unitPriceSats) // [ N, N, price ]
2308
- .op(OP_MUL) // [ N, N*price ]
2309
- .pushInt(0) // [ N, N*price, 0 ]
2310
- .op(OP_OUTPUTVALUE) // [ N, N*price, value ]
2311
- .op(OP_SWAP) // [ N, value, N*price ]
2312
- .op(OP_GREATERTHANOREQUAL)
2313
- .op(OP_VERIFY); // [ N ]
2314
- // 3. output[0].scriptPubKey == sellerScriptPubKey
2315
- b.pushInt(0)
2316
- .op(OP_OUTPUTSCRIPT) // [ N, spk_out0 ]
2317
- .pushBytes(sellerScriptPubKey)
2318
- .op(OP_EQUALVERIFY); // [ N ]
2319
- // 4. output[1].asset.amount == N
2320
- b.op(OP_DUP) // [ N, N ]
2321
- .pushInt(1)
2322
- .pushInt(ASSETFIELD_AMOUNT)
2323
- .op(OP_OUTPUTASSETFIELD) // [ N, N, amount_out1 ]
2324
- .op(OP_EQUALVERIFY); // [ N ]
2325
- // 5. output[1].asset.name == tokenId
2326
- b.pushInt(1)
2327
- .pushInt(ASSETFIELD_NAME)
2328
- .op(OP_OUTPUTASSETFIELD) // [ N, name_out1 ]
2329
- .pushBytes(tokenIdBytes)
2330
- .op(OP_EQUALVERIFY); // [ N ]
2331
- // 6. Drop N, leave TRUE on the stack.
2332
- b.op(OP_DROP).pushInt(1);
2333
- // ──────── Partial-fill branch (inner ELSE) ────────
2334
- // scriptSig: <N> <0> <0> ( N, full-flag=0, cancel-flag=0 )
2335
- // Stack entering: [ N ]
2336
- b.op(OP_ELSE);
2337
- appendExpirationGate(b, expiration);
2338
- // 1. Payment value (output 0) >= N * unitPriceSats
2339
- b.op(OP_DUP) // [ N, N ]
2340
- .pushInt(unitPriceSats) // [ N, N, price ]
2341
- .op(OP_MUL) // [ N, N*price ]
2342
- .pushInt(0) // [ N, N*price, 0 ]
2343
- .op(OP_OUTPUTVALUE) // [ N, N*price, value ]
2344
- .op(OP_SWAP) // [ N, value, N*price ]
2345
- .op(OP_GREATERTHANOREQUAL)
2346
- .op(OP_VERIFY); // [ N ]
2347
- // 2. Payment scriptPubKey (output 0)
2348
- b.pushInt(0)
2349
- .op(OP_OUTPUTSCRIPT) // [ N, spk_out0 ]
2350
- .pushBytes(sellerScriptPubKey)
2351
- .op(OP_EQUALVERIFY); // [ N ]
2352
- // 3. Asset to buyer (output 1) amount == N
2353
- b.op(OP_DUP) // [ N, N ]
2354
- .pushInt(1)
2355
- .pushInt(ASSETFIELD_AMOUNT)
2356
- .op(OP_OUTPUTASSETFIELD)
2357
- .op(OP_EQUALVERIFY); // [ N ]
2358
- // 4. Asset to buyer (output 1) name == tokenId
2359
- b.pushInt(1)
2360
- .pushInt(ASSETFIELD_NAME)
2361
- .op(OP_OUTPUTASSETFIELD)
2362
- .pushBytes(tokenIdBytes)
2363
- .op(OP_EQUALVERIFY); // [ N ]
2364
- // 5. Continuation (output 2): same AuthScript commitment as spent UTXO
2365
- // (NIP-023 — see file-level comment).
2366
- b.pushInt(2)
2367
- .op(OP_OUTPUTAUTHCOMMITMENT)
2368
- .pushInt(TXFIELD_AUTHSCRIPT_COMMITMENT)
2369
- .op(OP_TXFIELD)
2370
- .op(OP_EQUALVERIFY); // [ N ]
2371
- // 6. Continuation name == tokenId
2372
- b.pushInt(2)
2373
- .pushInt(ASSETFIELD_NAME)
2374
- .op(OP_OUTPUTASSETFIELD)
2375
- .pushBytes(tokenIdBytes)
2376
- .op(OP_EQUALVERIFY); // [ N ]
2377
- // 7. Continuation amount == inputAmount - N
2378
- b.pushInt(2)
2379
- .pushInt(ASSETFIELD_AMOUNT)
2380
- .op(OP_OUTPUTASSETFIELD) // [ N, rem_amount ]
2381
- .op(OP_OVER) // [ N, rem_amount, N ]
2382
- .pushInt(0) // [ N, rem_amount, N, 0 ]
2383
- .pushInt(ASSETFIELD_AMOUNT)
2384
- .op(OP_INPUTASSETFIELD) // [ N, rem_amount, N, in_amount ]
2385
- .op(OP_SWAP) // [ N, rem_amount, in_amount, N ]
2386
- .op(OP_SUB) // [ N, rem_amount, in_amount - N ]
2387
- .op(OP_EQUALVERIFY); // [ N ]
2388
- // 8. Drop N, leave TRUE on the stack.
2389
- b.op(OP_DROP).pushInt(1);
2390
- b.op(OP_ENDIF); // closes full/partial inner IF
2542
+ // ════════ Fill branches (outer ELSE) ════════
2543
+ appendFillBranches(b, {
2544
+ paymentScriptPubKey,
2545
+ tokenIdBytes: new TextEncoder().encode(tokenId),
2546
+ unitPriceSats,
2547
+ expiration
2548
+ });
2391
2549
  b.op(OP_ENDIF); // closes outer cancel/fill IF
2392
2550
  return b.build();
2393
2551
  }
@@ -2417,14 +2575,14 @@ function buildPartialFillScriptHex(params) {
2417
2575
  *
2418
2576
  * The message that gets signed is **SHA256(OP_TXHASH(selector))** — CSFS
2419
2577
  * single-SHA256s its message argument before verification, and OP_TXHASH
2420
- * produces its own 32-byte hash, so the seller computes:
2421
- * `sign(pqSeckey, SHA256(doubleSHA256(selected_tx_fields)))`
2578
+ * produces its own 32-byte NIP-042 tagged hash, so the seller computes:
2579
+ * `sign(pqSeckey, SHA256(TaggedHash("NeuraiTxHash", mask || selected_tx_fields)))`
2422
2580
  *
2423
- * Fill branches are identical in structure to the legacy variant — see
2424
- * `./script.ts` for the three-branch layout description.
2581
+ * The fill branches, including the input-0 binding, are shared with the
2582
+ * ECDSA variant — see `./fill-branches.ts`.
2425
2583
  */
2426
2584
  const ASSET_NAME_MAX = 32;
2427
- const DEFAULT_PQ_TXHASH_SELECTOR = 0xff;
2585
+ const DEFAULT_PQ_TXHASH_SELECTOR = 0x1ff;
2428
2586
  function assertCommitment(commitment) {
2429
2587
  if (!(commitment instanceof Uint8Array) || commitment.length !== 32) {
2430
2588
  throw new Error('pubKeyCommitment must be a 32-byte Uint8Array (SHA256 of pubKey)');
@@ -2453,11 +2611,11 @@ function assertPrice(priceSats) {
2453
2611
  }
2454
2612
  }
2455
2613
  function assertSelector(selector) {
2456
- if (!Number.isInteger(selector) || selector < 0 || selector > 0xff) {
2457
- throw new Error('txHashSelector must be a single byte (0x00..0xff)');
2614
+ if (!Number.isInteger(selector) || selector < 0 || selector > 0x1ff) {
2615
+ throw new Error('txHashSelector must be in the NIP-042 range (0x001..0x1ff)');
2458
2616
  }
2459
2617
  if (selector === 0) {
2460
- throw new Error('txHashSelector 0x00 is rejected by OP_TXHASH');
2618
+ throw new Error('txHashSelector 0x000 is rejected by OP_TXHASH');
2461
2619
  }
2462
2620
  }
2463
2621
  /**
@@ -2477,113 +2635,25 @@ function buildPartialFillScriptPQ(params) {
2477
2635
  // scriptSig: <sigPQ> <pubKeyPQ> <1>
2478
2636
  // After OP_IF consumes the flag: [ sig, pubKey ]
2479
2637
  //
2480
- // The selector MUST be pushed as a raw 1-byte element — consensus rejects
2481
- // any stack item of size ≠ 1. Using `pushInt(selector)` would work for
2482
- // 1..127 but emit a 2-byte CScriptNum for 0x80..0xff (sign-disambiguation
2483
- // pad), which makes OP_TXHASH fail with SCRIPT_ERR_TXHASH.
2638
+ // NIP-042 consumes exactly two raw little-endian bytes. CScriptNum and
2639
+ // OP_N encodings are invalid even when they represent the same mask.
2484
2640
  b.op(OP_IF)
2485
2641
  .op(OP_DUP) // [ sig, pubKey, pubKey ]
2486
2642
  .op(OP_SHA256) // [ sig, pubKey, H(pubKey) ]
2487
2643
  .pushBytes(pubKeyCommitment) // [ sig, pubKey, H(pubKey), commitment ]
2488
2644
  .op(OP_EQUALVERIFY) // [ sig, pubKey ]
2489
- .pushBytes(Uint8Array.of(txHashSelector)) // [ sig, pubKey, selector ]
2645
+ .pushBytes(Uint8Array.of(txHashSelector & 0xff, txHashSelector >> 8)) // [ sig, pubKey, selector ]
2490
2646
  .op(OP_TXHASH) // [ sig, pubKey, txHash ]
2491
2647
  .op(OP_SWAP) // [ sig, txHash, pubKey ]
2492
2648
  .op(OP_CHECKSIGFROMSTACK) // [ 1 | 0 ]
2493
2649
  .op(OP_ELSE);
2494
- // ════════ Fill branches (inner IF: full / ELSE: partial) ════════
2495
- b.op(OP_IF);
2496
- // ──────── Full-fill branch ────────
2497
- // scriptSig: <1> <0>
2498
- // Stack entering: [ ]
2499
- // 1. N = inputAmount
2500
- appendExpirationGate(b, expiration);
2501
- b.pushInt(0)
2502
- .pushInt(ASSETFIELD_AMOUNT)
2503
- .op(OP_INPUTASSETFIELD);
2504
- // 2. Payment value (output 0) >= N * unitPriceSats
2505
- b.op(OP_DUP)
2506
- .pushInt(unitPriceSats)
2507
- .op(OP_MUL)
2508
- .pushInt(0)
2509
- .op(OP_OUTPUTVALUE)
2510
- .op(OP_SWAP)
2511
- .op(OP_GREATERTHANOREQUAL)
2512
- .op(OP_VERIFY);
2513
- // 3. Payment scriptPubKey (output 0)
2514
- b.pushInt(0)
2515
- .op(OP_OUTPUTSCRIPT)
2516
- .pushBytes(payment.bytes)
2517
- .op(OP_EQUALVERIFY);
2518
- // 4. Asset to buyer (output 1) amount == N
2519
- b.op(OP_DUP)
2520
- .pushInt(1)
2521
- .pushInt(ASSETFIELD_AMOUNT)
2522
- .op(OP_OUTPUTASSETFIELD)
2523
- .op(OP_EQUALVERIFY);
2524
- // 5. Asset to buyer (output 1) name == tokenId
2525
- b.pushInt(1)
2526
- .pushInt(ASSETFIELD_NAME)
2527
- .op(OP_OUTPUTASSETFIELD)
2528
- .pushBytes(tokenIdBytes)
2529
- .op(OP_EQUALVERIFY);
2530
- b.op(OP_DROP).pushInt(1);
2531
- // ──────── Partial-fill branch ────────
2532
- // scriptSig: <N> <0> <0>
2533
- // Stack entering: [ N ]
2534
- b.op(OP_ELSE);
2535
- appendExpirationGate(b, expiration);
2536
- // 1. Payment value (output 0) >= N * unitPriceSats
2537
- b.op(OP_DUP)
2538
- .pushInt(unitPriceSats)
2539
- .op(OP_MUL)
2540
- .pushInt(0)
2541
- .op(OP_OUTPUTVALUE)
2542
- .op(OP_SWAP)
2543
- .op(OP_GREATERTHANOREQUAL)
2544
- .op(OP_VERIFY);
2545
- // 2. Payment scriptPubKey (output 0)
2546
- b.pushInt(0)
2547
- .op(OP_OUTPUTSCRIPT)
2548
- .pushBytes(payment.bytes)
2549
- .op(OP_EQUALVERIFY);
2550
- // 3. Asset to buyer (output 1) amount == N
2551
- b.op(OP_DUP)
2552
- .pushInt(1)
2553
- .pushInt(ASSETFIELD_AMOUNT)
2554
- .op(OP_OUTPUTASSETFIELD)
2555
- .op(OP_EQUALVERIFY);
2556
- // 4. Asset to buyer (output 1) name == tokenId
2557
- b.pushInt(1)
2558
- .pushInt(ASSETFIELD_NAME)
2559
- .op(OP_OUTPUTASSETFIELD)
2560
- .pushBytes(tokenIdBytes)
2561
- .op(OP_EQUALVERIFY);
2562
- // 5. Continuation (output 2): same AuthScript commitment as spent (NIP-023)
2563
- b.pushInt(2)
2564
- .op(OP_OUTPUTAUTHCOMMITMENT)
2565
- .pushInt(TXFIELD_AUTHSCRIPT_COMMITMENT)
2566
- .op(OP_TXFIELD)
2567
- .op(OP_EQUALVERIFY);
2568
- // 6. Continuation name == tokenId
2569
- b.pushInt(2)
2570
- .pushInt(ASSETFIELD_NAME)
2571
- .op(OP_OUTPUTASSETFIELD)
2572
- .pushBytes(tokenIdBytes)
2573
- .op(OP_EQUALVERIFY);
2574
- // 7. Continuation amount == inputAmount - N
2575
- b.pushInt(2)
2576
- .pushInt(ASSETFIELD_AMOUNT)
2577
- .op(OP_OUTPUTASSETFIELD)
2578
- .op(OP_OVER)
2579
- .pushInt(0)
2580
- .pushInt(ASSETFIELD_AMOUNT)
2581
- .op(OP_INPUTASSETFIELD)
2582
- .op(OP_SWAP)
2583
- .op(OP_SUB)
2584
- .op(OP_EQUALVERIFY);
2585
- b.op(OP_DROP).pushInt(1);
2586
- b.op(OP_ENDIF); // full / partial
2650
+ // ════════ Fill branches (outer ELSE) ════════
2651
+ appendFillBranches(b, {
2652
+ paymentScriptPubKey: payment.bytes,
2653
+ tokenIdBytes,
2654
+ unitPriceSats,
2655
+ expiration
2656
+ });
2587
2657
  b.op(OP_ENDIF); // cancel / fill
2588
2658
  return b.build();
2589
2659
  }
@@ -2806,17 +2876,15 @@ function buildCancelWitnessStackPQ(sigPQ, pubKey) {
2806
2876
  }
2807
2877
 
2808
2878
  /**
2809
- * Parser for the Partial-Fill Sell Order covenant (three-branch).
2810
- *
2811
- * Extracts `(sellerPubKeyHash, unitPriceSats, tokenId)` from a scriptPubKey
2812
- * that was produced by `buildPartialFillScript`. Walks the exact byte
2813
- * layout emitted by the builder and fails on any deviation — this is
2814
- * deliberate, so a downstream indexer can unambiguously classify a UTXO as
2815
- * "partial-fill order" or "unknown script" with no false positives.
2816
- *
2817
- * The full-fill and partial-fill branches share `(sellerScriptPubKey,
2818
- * unitPriceSats, tokenId)`. The parser reads both branches and verifies
2819
- * consistency; inconsistency throws.
2879
+ * Parser for the Partial-Fill Sell Order covenant (three-branch, ECDSA cancel).
2880
+ *
2881
+ * Extracts `(sellerPubKeyHash, paymentScriptPubKey, unitPriceSats, tokenId)`
2882
+ * from a scriptPubKey that was produced by `buildPartialFillScript`. Walks
2883
+ * the exact byte layout emitted by the builder and fails on any deviation —
2884
+ * this is deliberate, so a downstream indexer can unambiguously classify a
2885
+ * UTXO as "partial-fill order" or "unknown script" with no false positives.
2886
+ * Covenants built before the input-0 binding (neurai-scripts < 0.10.0) are
2887
+ * rejected: their fill branches can be drained through a foreign input 0.
2820
2888
  */
2821
2889
  /**
2822
2890
  * Parse a covenant scriptPubKey and extract its parameters. Throws with a
@@ -2836,129 +2904,17 @@ function parsePartialFillScript(script, network = 'xna-test') {
2836
2904
  expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (cancel)');
2837
2905
  expectByte(c, OP_CHECKSIG, 'OP_CHECKSIG (cancel)');
2838
2906
  expectByte(c, OP_ELSE, 'OP_ELSE (outer → fill)');
2839
- // ═════ Inner IF — Full-fill branch ═════
2840
- expectByte(c, OP_IF, 'OP_IF (inner full-fill)');
2841
- const expirationFull = readOptionalExpirationGate(c, OP_0, 'full');
2842
- // N = inputAmount
2843
- expectByte(c, OP_0, 'OP_0 (input idx, full)');
2844
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel, full)');
2845
- expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD (full)');
2846
- // payment value check
2847
- expectByte(c, OP_DUP, 'OP_DUP (price, full)');
2848
- const unitPriceSatsFull = readPushPositiveInt(c, 'unitPriceSats (full)');
2849
- expectByte(c, OP_MUL, 'OP_MUL (full)');
2850
- expectByte(c, OP_0, 'OP_0 (payment idx, full)');
2851
- expectByte(c, OP_OUTPUTVALUE, 'OP_OUTPUTVALUE (full)');
2852
- expectByte(c, OP_SWAP, 'OP_SWAP (full)');
2853
- expectByte(c, OP_GREATERTHANOREQUAL, 'OP_GREATERTHANOREQUAL (full)');
2854
- expectByte(c, OP_VERIFY, 'OP_VERIFY (payment full)');
2855
- // payment spk
2856
- expectByte(c, OP_0, 'OP_0 (spk idx, full)');
2857
- expectByte(c, OP_OUTPUTSCRIPT, 'OP_OUTPUTSCRIPT (payment full)');
2858
- const sellerSpkFull = readPush(c, 'sellerScriptPubKey (full)');
2859
- const expectedSpk = new Uint8Array([
2860
- OP_DUP, OP_HASH160, 0x14, ...sellerPubKeyHash, OP_EQUALVERIFY, OP_CHECKSIG
2861
- ]);
2862
- if (!bytesEqual(sellerSpkFull, expectedSpk)) {
2863
- throw new Error('parse: full-fill seller scriptPubKey does not match the cancel PKH');
2864
- }
2865
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (payment spk full)');
2866
- // buyer amount == N (full)
2867
- expectByte(c, OP_DUP, 'OP_DUP (buyer amount, full)');
2868
- expectByte(c, OP_1, 'OP_1 (buyer idx, full)');
2869
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel, full)');
2870
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer amount, full)');
2871
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer amount, full)');
2872
- // buyer name == tokenId (full)
2873
- expectByte(c, OP_1, 'OP_1 (buyer idx, full)');
2874
- expectByte(c, OP_1, 'OP_1 (NAME sel, full)');
2875
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer name, full)');
2876
- const tokenIdFull = readPush(c, 'tokenId (full)');
2877
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer name, full)');
2878
- // tail (full)
2879
- expectByte(c, OP_DROP, 'OP_DROP (full)');
2880
- expectByte(c, OP_1, 'OP_1 (true, full)');
2881
- expectByte(c, OP_ELSE, 'OP_ELSE (inner → partial fill)');
2882
- // ═════ Inner ELSE — Partial-fill branch ═════
2883
- const expirationPartial = readOptionalExpirationGate(c, OP_DUP, 'partial');
2884
- // Payment value
2885
- expectByte(c, OP_DUP, 'OP_DUP (price, partial)');
2886
- const unitPriceSatsPartial = readPushPositiveInt(c, 'unitPriceSats (partial)');
2887
- expectByte(c, OP_MUL, 'OP_MUL (partial)');
2888
- expectByte(c, OP_0, 'OP_0 (pay idx, partial)');
2889
- expectByte(c, OP_OUTPUTVALUE, 'OP_OUTPUTVALUE (partial)');
2890
- expectByte(c, OP_SWAP, 'OP_SWAP (partial)');
2891
- expectByte(c, OP_GREATERTHANOREQUAL, 'OP_GREATERTHANOREQUAL (partial)');
2892
- expectByte(c, OP_VERIFY, 'OP_VERIFY (payment partial)');
2893
- // Payment spk
2894
- expectByte(c, OP_0, 'OP_0 (spk idx, partial)');
2895
- expectByte(c, OP_OUTPUTSCRIPT, 'OP_OUTPUTSCRIPT (payment partial)');
2896
- const sellerSpkPartial = readPush(c, 'sellerScriptPubKey (partial)');
2897
- if (!bytesEqual(sellerSpkPartial, expectedSpk)) {
2898
- throw new Error('parse: partial-fill seller scriptPubKey does not match the cancel PKH');
2899
- }
2900
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (payment spk partial)');
2901
- // Buyer amount
2902
- expectByte(c, OP_DUP, 'OP_DUP (buyer amount, partial)');
2903
- expectByte(c, OP_1, 'OP_1 (buyer idx, partial)');
2904
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel, partial)');
2905
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer amount, partial)');
2906
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer amount, partial)');
2907
- // Buyer name
2908
- expectByte(c, OP_1, 'OP_1 (buyer idx, partial)');
2909
- expectByte(c, OP_1, 'OP_1 (NAME sel, partial)');
2910
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer name, partial)');
2911
- const tokenIdPartial1 = readPush(c, 'tokenId partial #1');
2912
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer name, partial)');
2913
- // Continuation commitment
2914
- expectByte(c, OP_2, 'OP_2 (remainder idx)');
2915
- expectByte(c, OP_OUTPUTAUTHCOMMITMENT, 'OP_OUTPUTAUTHCOMMITMENT (remainder)');
2916
- expectByte(c, OP_2, 'OP_2 (TXFIELD sel: AUTHSCRIPT_COMMITMENT)');
2917
- expectByte(c, OP_TXFIELD, 'OP_TXFIELD');
2918
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder auth)');
2919
- // Continuation name
2920
- expectByte(c, OP_2, 'OP_2 (remainder idx)');
2921
- expectByte(c, OP_1, 'OP_1 (NAME sel)');
2922
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder name)');
2923
- const tokenIdPartial2 = readPush(c, 'tokenId partial #2');
2924
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder name)');
2925
- // Continuation amount
2926
- expectByte(c, OP_2, 'OP_2 (remainder idx)');
2927
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel)');
2928
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder amount)');
2929
- expectByte(c, OP_OVER, 'OP_OVER');
2930
- expectByte(c, OP_0, 'OP_0 (input idx)');
2931
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel)');
2932
- expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD');
2933
- expectByte(c, OP_SWAP, 'OP_SWAP');
2934
- expectByte(c, OP_SUB, 'OP_SUB');
2935
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder amount)');
2936
- // Tail (partial)
2937
- expectByte(c, OP_DROP, 'OP_DROP (partial)');
2938
- expectByte(c, OP_1, 'OP_1 (true, partial)');
2939
- // Close the nested structure
2940
- expectByte(c, OP_ENDIF, 'OP_ENDIF (inner)');
2907
+ // ═════ Outer ELSE — input-0 binding + fill branches ═════
2908
+ const fill = readFillBranches(c);
2941
2909
  expectByte(c, OP_ENDIF, 'OP_ENDIF (outer)');
2942
2910
  assertTrailing(c);
2943
- // Cross-branch consistency: all three (full token, partial name #1,
2944
- // partial name #2) must agree, and the two unit prices must match.
2945
- if (!bytesEqual(tokenIdFull, tokenIdPartial1)) {
2946
- throw new Error('parse: tokenId differs between full-fill and partial-fill branches');
2947
- }
2948
- if (!bytesEqual(tokenIdPartial1, tokenIdPartial2)) {
2949
- throw new Error('parse: tokenId bytes differ between buyer and remainder partial checks');
2950
- }
2951
- if (unitPriceSatsFull !== unitPriceSatsPartial) {
2952
- throw new Error('parse: unitPriceSats differs between full-fill and partial-fill branches');
2953
- }
2954
- assertSameExpiration(expirationFull, expirationPartial, 'full-fill and partial-fill branches');
2955
- const tokenId = new TextDecoder('utf-8', { fatal: true }).decode(tokenIdFull);
2956
2911
  return {
2957
2912
  network,
2958
2913
  sellerPubKeyHash,
2959
- unitPriceSats: unitPriceSatsFull,
2960
- tokenId,
2961
- expiration: expirationFull,
2914
+ paymentScriptPubKey: fill.paymentScriptPubKey,
2915
+ unitPriceSats: fill.unitPriceSats,
2916
+ tokenId: fill.tokenId,
2917
+ expiration: fill.expiration,
2962
2918
  scriptHex: bytesToHex(bytes)
2963
2919
  };
2964
2920
  }
@@ -2969,9 +2925,8 @@ function parsePartialFillScript(script, network = 'xna-test') {
2969
2925
  * payment scriptPubKey bytes (which may be P2PKH or AuthScript) and the
2970
2926
  * configured TXHASH selector.
2971
2927
  *
2972
- * The full-fill and partial-fill branches share `(paymentScriptPubKey,
2973
- * unitPriceSats, tokenId)`. The parser reads both branches and verifies
2974
- * consistency; inconsistency throws.
2928
+ * The fill branches (and their input-0 binding) are read by the shared
2929
+ * `readFillBranches`; covenants built before the binding are rejected.
2975
2930
  */
2976
2931
  /** Quick discriminator without throwing — useful for indexers. */
2977
2932
  function isPartialFillScriptPQ(script) {
@@ -2998,118 +2953,30 @@ function parsePartialFillScriptPQ(script, network = 'xna-test') {
2998
2953
  throw new Error(`parse-pq: pubKeyCommitment must be 32 bytes, got ${pubKeyCommitment.length}`);
2999
2954
  }
3000
2955
  expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (cancel)');
3001
- const txHashSelector = readPushUint8(c, 'txHashSelector');
3002
- if (txHashSelector < 1) {
3003
- throw new Error(`parse-pq: txHashSelector 0x00 is rejected by OP_TXHASH`);
2956
+ const selectorBytes = readPush(c, 'txHashSelector');
2957
+ if (selectorBytes.length !== 2) {
2958
+ throw new Error(`parse-pq: txHashSelector must be a two-byte LE push, got ${selectorBytes.length} bytes`);
2959
+ }
2960
+ const txHashSelector = selectorBytes[0] | (selectorBytes[1] << 8);
2961
+ if (txHashSelector === 0 || txHashSelector > 0x1ff) {
2962
+ throw new Error(`parse-pq: txHashSelector 0x${txHashSelector.toString(16)} is rejected by OP_TXHASH`);
3004
2963
  }
3005
2964
  expectByte(c, OP_TXHASH, 'OP_TXHASH');
3006
2965
  expectByte(c, OP_SWAP, 'OP_SWAP');
3007
2966
  expectByte(c, OP_CHECKSIGFROMSTACK, 'OP_CHECKSIGFROMSTACK');
3008
2967
  expectByte(c, OP_ELSE, 'OP_ELSE (outer → fill)');
3009
- // ═════ Inner IF — Full-fill branch ═════
3010
- expectByte(c, OP_IF, 'OP_IF (inner full-fill)');
3011
- const expirationFull = readOptionalExpirationGate(c, OP_0, 'full');
3012
- expectByte(c, OP_0, 'OP_0 (input idx, full)');
3013
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel, full)');
3014
- expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD (full)');
3015
- expectByte(c, OP_DUP, 'OP_DUP (price, full)');
3016
- const unitPriceSatsFull = readPushPositiveInt(c, 'unitPriceSats (full)');
3017
- expectByte(c, OP_MUL, 'OP_MUL (full)');
3018
- expectByte(c, OP_0, 'OP_0 (payment idx, full)');
3019
- expectByte(c, OP_OUTPUTVALUE, 'OP_OUTPUTVALUE (full)');
3020
- expectByte(c, OP_SWAP, 'OP_SWAP (full)');
3021
- expectByte(c, OP_GREATERTHANOREQUAL, 'OP_GE (full)');
3022
- expectByte(c, OP_VERIFY, 'OP_VERIFY (full)');
3023
- expectByte(c, OP_0, 'OP_0 (payment spk idx, full)');
3024
- expectByte(c, OP_OUTPUTSCRIPT, 'OP_OUTPUTSCRIPT (payment full)');
3025
- const paymentScriptPubKeyFull = readPush(c, 'paymentScriptPubKey (full)');
3026
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (payment full)');
3027
- expectByte(c, OP_DUP, 'OP_DUP (buyer amount, full)');
3028
- expectByte(c, OP_1, 'OP_1 (buyer idx, full)');
3029
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel, full)');
3030
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer amount, full)');
3031
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer amount, full)');
3032
- expectByte(c, OP_1, 'OP_1 (buyer idx, full)');
3033
- expectByte(c, OP_1, 'OP_1 (NAME sel, full)');
3034
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer name, full)');
3035
- const tokenIdFull = readPush(c, 'tokenId (full)');
3036
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer name, full)');
3037
- expectByte(c, OP_DROP, 'OP_DROP (full)');
3038
- expectByte(c, OP_1, 'OP_1 (true, full)');
3039
- expectByte(c, OP_ELSE, 'OP_ELSE (inner → partial fill)');
3040
- // ═════ Inner ELSE — Partial-fill branch ═════
3041
- const expirationPartial = readOptionalExpirationGate(c, OP_DUP, 'partial');
3042
- expectByte(c, OP_DUP, 'OP_DUP (price, partial)');
3043
- const unitPriceSatsPartial = readPushPositiveInt(c, 'unitPriceSats (partial)');
3044
- expectByte(c, OP_MUL, 'OP_MUL (partial)');
3045
- expectByte(c, OP_0, 'OP_0 (payment idx, partial)');
3046
- expectByte(c, OP_OUTPUTVALUE, 'OP_OUTPUTVALUE (partial)');
3047
- expectByte(c, OP_SWAP, 'OP_SWAP (partial)');
3048
- expectByte(c, OP_GREATERTHANOREQUAL, 'OP_GE (partial)');
3049
- expectByte(c, OP_VERIFY, 'OP_VERIFY (partial)');
3050
- expectByte(c, OP_0, 'OP_0 (payment spk idx, partial)');
3051
- expectByte(c, OP_OUTPUTSCRIPT, 'OP_OUTPUTSCRIPT (payment partial)');
3052
- const paymentScriptPubKeyPartial = readPush(c, 'paymentScriptPubKey (partial)');
3053
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (payment partial)');
3054
- expectByte(c, OP_DUP, 'OP_DUP (buyer amount, partial)');
3055
- expectByte(c, OP_1, 'OP_1 (buyer idx, partial)');
3056
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel, partial)');
3057
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer amount, partial)');
3058
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer amount, partial)');
3059
- expectByte(c, OP_1, 'OP_1 (buyer idx, partial)');
3060
- expectByte(c, OP_1, 'OP_1 (NAME sel, partial)');
3061
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer name, partial)');
3062
- const tokenIdPartial1 = readPush(c, 'tokenId partial #1');
3063
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer name, partial)');
3064
- // Continuation commitment
3065
- expectByte(c, OP_2, 'OP_2 (remainder idx)');
3066
- expectByte(c, OP_OUTPUTAUTHCOMMITMENT, 'OP_OUTPUTAUTHCOMMITMENT (remainder)');
3067
- expectByte(c, OP_2, 'OP_2 (TXFIELD sel: AUTHSCRIPT_COMMITMENT)');
3068
- expectByte(c, OP_TXFIELD, 'OP_TXFIELD');
3069
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder auth)');
3070
- expectByte(c, OP_2, 'OP_2 (remainder idx)');
3071
- expectByte(c, OP_1, 'OP_1 (NAME sel)');
3072
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder name)');
3073
- const tokenIdPartial2 = readPush(c, 'tokenId partial #2');
3074
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder name)');
3075
- expectByte(c, OP_2, 'OP_2 (remainder idx)');
3076
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel)');
3077
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder amount)');
3078
- expectByte(c, OP_OVER, 'OP_OVER');
3079
- expectByte(c, OP_0, 'OP_0 (input idx)');
3080
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel)');
3081
- expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD');
3082
- expectByte(c, OP_SWAP, 'OP_SWAP');
3083
- expectByte(c, OP_SUB, 'OP_SUB');
3084
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder amount)');
3085
- expectByte(c, OP_DROP, 'OP_DROP (partial)');
3086
- expectByte(c, OP_1, 'OP_1 (true, partial)');
3087
- expectByte(c, OP_ENDIF, 'OP_ENDIF (inner)');
2968
+ // ═════ Outer ELSE — input-0 binding + fill branches ═════
2969
+ const fill = readFillBranches(c);
3088
2970
  expectByte(c, OP_ENDIF, 'OP_ENDIF (outer)');
3089
2971
  assertTrailing(c);
3090
- // Cross-branch consistency.
3091
- if (!bytesEqual(paymentScriptPubKeyFull, paymentScriptPubKeyPartial)) {
3092
- throw new Error('parse-pq: paymentScriptPubKey differs between full-fill and partial-fill branches');
3093
- }
3094
- if (!bytesEqual(tokenIdFull, tokenIdPartial1)) {
3095
- throw new Error('parse-pq: tokenId differs between full-fill and partial-fill branches');
3096
- }
3097
- if (!bytesEqual(tokenIdPartial1, tokenIdPartial2)) {
3098
- throw new Error('parse-pq: tokenId differs between buyer and remainder partial checks');
3099
- }
3100
- if (unitPriceSatsFull !== unitPriceSatsPartial) {
3101
- throw new Error('parse-pq: unitPriceSats differs between full-fill and partial-fill branches');
3102
- }
3103
- assertSameExpiration(expirationFull, expirationPartial, 'full-fill and partial-fill branches');
3104
- const tokenId = new TextDecoder('utf-8', { fatal: true }).decode(tokenIdFull);
3105
2972
  return {
3106
2973
  network,
3107
2974
  pubKeyCommitment,
3108
- tokenId,
3109
- unitPriceSats: unitPriceSatsFull,
2975
+ tokenId: fill.tokenId,
2976
+ unitPriceSats: fill.unitPriceSats,
3110
2977
  txHashSelector,
3111
- expiration: expirationFull,
3112
- paymentScriptPubKey: paymentScriptPubKeyFull,
2978
+ expiration: fill.expiration,
2979
+ paymentScriptPubKey: fill.paymentScriptPubKey,
3113
2980
  scriptHex: bytesToHex(bytes)
3114
2981
  };
3115
2982
  }