@neuraiproject/neurai-scripts 0.6.0 → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,8 +9,8 @@ Script-assembly library for Neurai. Provides:
9
9
  - **Covenants** — partial-fill sell-order covenant (legacy and PQ variants)
10
10
  targeting the **DePIN-Test** opcode set (`OP_OUTPUTSCRIPT`,
11
11
  `OP_OUTPUTVALUE`, `OP_OUTPUTASSETFIELD`, `OP_INPUTASSETFIELD`,
12
- `OP_TXFIELD`, `OP_CHECKTEMPLATEVERIFY`, `OP_CHECKSIGFROMSTACK`, 64-bit
13
- `OP_MUL`/`OP_SUB`, …).
12
+ `OP_TXFIELD`, `OP_CHECKTEMPLATEVERIFY`, `OP_CHECKSIGFROMSTACK`,
13
+ `OP_CHAINCONTEXT`, 64-bit `OP_MUL`/`OP_SUB`, …).
14
14
 
15
15
  This is the canonical place to add new Neurai script builders; callers
16
16
  compose transactions with
@@ -95,8 +95,8 @@ stack, arithmetic, bitwise, crypto) plus every DePIN-Test addition
95
95
  `OP_TXFIELD`, `OP_TXLOCKTIME`, `OP_OUTPUTVALUE`, `OP_OUTPUTSCRIPT`,
96
96
  `OP_INPUTCOUNT`/`OP_OUTPUTCOUNT`, `OP_OUTPUTASSETFIELD`,
97
97
  `OP_INPUTASSETFIELD`, `OP_REFINPUTCOUNT`/`OP_REFINPUTFIELD`/
98
- `OP_REFINPUTASSETFIELD`, `OP_CAT`, `OP_SPLIT`, `OP_REVERSEBYTES`, 64-bit
99
- `OP_MUL`/`OP_DIV`/`OP_MOD`).
98
+ `OP_REFINPUTASSETFIELD`, `OP_CHAINCONTEXT`, `OP_CAT`, `OP_SPLIT`,
99
+ `OP_REVERSEBYTES`, 64-bit `OP_MUL`/`OP_DIV`/`OP_MOD`).
100
100
 
101
101
  Also exports selector tables:
102
102
 
@@ -115,6 +115,11 @@ opcodes.ASSETFIELD_HAS_IPFS // 0x05
115
115
  opcodes.ASSETFIELD_IPFS_HASH // 0x06
116
116
  opcodes.ASSETFIELD_TYPE // 0x07
117
117
 
118
+ // For OP_CHAINCONTEXT
119
+ opcodes.CHAINCONTEXT_HEIGHT // 0x01
120
+ opcodes.CHAINCONTEXT_MTP // 0x02
121
+ opcodes.CHAINCONTEXT_CHAIN_ID // 0x03
122
+
118
123
  // Bitmask selectors for OP_TXHASH (any non-zero combination is valid)
119
124
  opcodes.TXHASH_VERSION // 0x01
120
125
  opcodes.TXHASH_LOCKTIME // 0x02
@@ -334,6 +339,18 @@ order, and the whole chain confirms together when the next block is
334
339
  mined. If the seller wants to stop the order at any point, she spends
335
340
  the current live UTXO via the cancel branch.
336
341
 
342
+ Orders can also carry an optional expiry. When `expiration` is set, both
343
+ buyer fill branches start with:
344
+
345
+ ```
346
+ <expiration.value> <HEIGHT|MTP> OP_CHAINCONTEXT OP_GREATERTHAN OP_VERIFY
347
+ ```
348
+
349
+ So fills are valid only while the configured height or median-time-past
350
+ deadline is still greater than the chain context. At the deadline block/time
351
+ and after it, buyer fills fail and the seller can recover the live order via
352
+ the cancel branch.
353
+
337
354
  #### Alice / Bob / Carol flow
338
355
 
339
356
  1. **Alice** locks 100 CAT in a covenant UTXO (`buildPartialFillScript`).
@@ -366,7 +383,11 @@ import {
366
383
  const scriptPubKeyHex = buildPartialFillScriptHex({
367
384
  sellerAddress: aliceP2PKHAddress, // "t..." on testnet / "N..." on mainnet
368
385
  tokenId: 'CAT',
369
- unitPriceSats: 100_000_000n // 1 XNA = 1e8 sats per indivisible unit
386
+ unitPriceSats: 100_000_000n, // 1 XNA = 1e8 sats per indivisible unit
387
+ expiration: {
388
+ mode: 'height', // or 'mtp' for median-time-past seconds
389
+ value: 1_250_000n // fills are rejected at/after this value
390
+ }
370
391
  });
371
392
  // Throws if the address is not a legacy P2PKH — the legacy covenant uses
372
393
  // OP_HASH160 + OP_CHECKSIG on the cancel branch and cannot commit to an
@@ -391,7 +412,8 @@ const cancelScriptSigHex = buildCancelScriptSigHex(aliceCancelSig, alicePubKey);
391
412
  for (const utxo of candidateUtxos) {
392
413
  try {
393
414
  const order = parsePartialFillScript(utxo.scriptPubKeyHex, 'xna-test');
394
- // order.tokenId, order.unitPriceSats, order.sellerPubKeyHash, order.network
415
+ // order.tokenId, order.unitPriceSats, order.sellerPubKeyHash,
416
+ // order.expiration, order.network
395
417
  // The parser returns the 20-byte PKH; base58check-encode with the
396
418
  // network's legacy prefix (0x35 mainnet / 0x7f testnet) if you need
397
419
  // to display the seller's address.
@@ -409,6 +431,7 @@ OP_IF // cancel bra
409
431
  OP_ELSE
410
432
  OP_IF // full-fill branch
411
433
  # Stack entering: [ ] (scriptSig pushed <1> <0>)
434
+ # Optional expiry: <deadline> <HEIGHT|MTP> OP_CHAINCONTEXT OP_GREATERTHAN OP_VERIFY
412
435
  <0> <0x02> OP_INPUTASSETFIELD // N = inputAmount
413
436
  OP_DUP <unitPriceSats> OP_MUL
414
437
  <0> OP_OUTPUTVALUE OP_SWAP OP_GREATERTHANOREQUAL OP_VERIFY // payment value
@@ -418,6 +441,7 @@ OP_ELSE
418
441
  OP_DROP OP_1 // no vout[2] required
419
442
  OP_ELSE // partial-fill branch
420
443
  # Stack entering: [ N ] (scriptSig pushed <N> <0> <0>)
444
+ # Optional expiry: <deadline> <HEIGHT|MTP> OP_CHAINCONTEXT OP_GREATERTHAN OP_VERIFY
421
445
  OP_DUP <unitPriceSats> OP_MUL
422
446
  <0> OP_OUTPUTVALUE OP_SWAP OP_GREATERTHANOREQUAL OP_VERIFY // payment value
423
447
  <0> OP_OUTPUTSCRIPT <sellerP2PKH> OP_EQUALVERIFY // payment dest
@@ -222,6 +222,12 @@ var NeuraiScriptsBundle = (function (exports) {
222
222
  // Pushes chain-context fields (block height, median time, etc.) selected
223
223
  // by a single-byte selector consumed from the stack.
224
224
  const OP_CHAINCONTEXT = 0xd7;
225
+ // ---------- Selectors for OP_CHAINCONTEXT ----------
226
+ // Valid selector bytes consumed by OP_CHAINCONTEXT. HEIGHT is the candidate
227
+ // confirmation block height; MTP is the previous block's median time past.
228
+ const CHAINCONTEXT_HEIGHT = 0x01;
229
+ const CHAINCONTEXT_MTP = 0x02;
230
+ const CHAINCONTEXT_CHAIN_ID = 0x03;
225
231
  // ---------- Merkle inclusion (NIP-031) ----------
226
232
  // Native Merkle inclusion verifier. Consumes (leaf, scheme_id, proof,
227
233
  // root) and pushes a boolean. Flag off → bad-opcode.
@@ -271,6 +277,9 @@ var NeuraiScriptsBundle = (function (exports) {
271
277
  ASSETFIELD_REISSUABLE: ASSETFIELD_REISSUABLE,
272
278
  ASSETFIELD_TYPE: ASSETFIELD_TYPE,
273
279
  ASSETFIELD_UNITS: ASSETFIELD_UNITS,
280
+ CHAINCONTEXT_CHAIN_ID: CHAINCONTEXT_CHAIN_ID,
281
+ CHAINCONTEXT_HEIGHT: CHAINCONTEXT_HEIGHT,
282
+ CHAINCONTEXT_MTP: CHAINCONTEXT_MTP,
274
283
  OP_0: OP_0,
275
284
  OP_0NOTEQUAL: OP_0NOTEQUAL,
276
285
  OP_1: OP_1,
@@ -1788,6 +1797,220 @@ var NeuraiScriptsBundle = (function (exports) {
1788
1797
  };
1789
1798
  }
1790
1799
 
1800
+ /**
1801
+ * Shared parsing primitives for strict covenant parsers. Each covenant
1802
+ * parser walks the exact byte layout emitted by its builder and fails on
1803
+ * any deviation; the primitives here centralize the cursor arithmetic,
1804
+ * pushdata decoding, and CScriptNum decoding so the legacy and PQ parsers
1805
+ * (and future covenant parsers) cannot drift in rigor.
1806
+ */
1807
+ function makeCursor(bytes) {
1808
+ return { bytes, pos: 0 };
1809
+ }
1810
+ /** Consume one byte and verify it equals `expected`. */
1811
+ function expectByte(c, expected, label) {
1812
+ if (c.pos >= c.bytes.length) {
1813
+ throw new Error(`parse: unexpected end of script while reading ${label}`);
1814
+ }
1815
+ const got = c.bytes[c.pos];
1816
+ if (got !== expected) {
1817
+ throw new Error(`parse: expected ${label} = 0x${expected.toString(16)} at offset ${c.pos}, got 0x${got.toString(16)}`);
1818
+ }
1819
+ c.pos += 1;
1820
+ }
1821
+ /** Fail if the cursor has not consumed every byte of the script. */
1822
+ function assertTrailing(c) {
1823
+ if (c.pos !== c.bytes.length) {
1824
+ throw new Error(`parse: ${c.bytes.length - c.pos} trailing bytes after end of script`);
1825
+ }
1826
+ }
1827
+ /**
1828
+ * Read one pushdata element from the cursor. Supports direct pushes
1829
+ * (1..75 bytes), `OP_PUSHDATA1` and `OP_PUSHDATA2`. `OP_PUSHDATA4` is not
1830
+ * supported by any current covenant script and would overflow the
1831
+ * per-element cap anyway. Truncation is checked for all length fields
1832
+ * and payload ranges.
1833
+ */
1834
+ function readPush(c, label) {
1835
+ if (c.pos >= c.bytes.length) {
1836
+ throw new Error(`parse: unexpected end of script while reading push for ${label}`);
1837
+ }
1838
+ const opcode = c.bytes[c.pos];
1839
+ c.pos += 1;
1840
+ // Short direct push: 1..75 bytes
1841
+ if (opcode >= 0x01 && opcode <= 0x4b) {
1842
+ const len = opcode;
1843
+ if (c.pos + len > c.bytes.length) {
1844
+ throw new Error(`parse: short push of ${len} bytes exceeds script length at ${label}`);
1845
+ }
1846
+ const data = c.bytes.slice(c.pos, c.pos + len);
1847
+ c.pos += len;
1848
+ return data;
1849
+ }
1850
+ // OP_PUSHDATA1
1851
+ if (opcode === 0x4c) {
1852
+ if (c.pos >= c.bytes.length) {
1853
+ throw new Error(`parse: truncated PUSHDATA1 length at ${label}`);
1854
+ }
1855
+ const len = c.bytes[c.pos];
1856
+ c.pos += 1;
1857
+ if (c.pos + len > c.bytes.length) {
1858
+ throw new Error(`parse: PUSHDATA1 of ${len} bytes exceeds script length at ${label}`);
1859
+ }
1860
+ const data = c.bytes.slice(c.pos, c.pos + len);
1861
+ c.pos += len;
1862
+ return data;
1863
+ }
1864
+ // OP_PUSHDATA2
1865
+ if (opcode === 0x4d) {
1866
+ if (c.pos + 2 > c.bytes.length) {
1867
+ throw new Error(`parse: truncated PUSHDATA2 length at ${label}`);
1868
+ }
1869
+ const len = c.bytes[c.pos] | (c.bytes[c.pos + 1] << 8);
1870
+ c.pos += 2;
1871
+ if (c.pos + len > c.bytes.length) {
1872
+ throw new Error(`parse: PUSHDATA2 of ${len} bytes exceeds script length at ${label}`);
1873
+ }
1874
+ const data = c.bytes.slice(c.pos, c.pos + len);
1875
+ c.pos += len;
1876
+ return data;
1877
+ }
1878
+ throw new Error(`parse: expected a pushdata opcode at ${label}, got 0x${opcode.toString(16)} at offset ${c.pos - 1}`);
1879
+ }
1880
+ /**
1881
+ * Decode a `CScriptNum` byte vector (little-endian sign-magnitude, up to
1882
+ * 8 bytes) into a BigInt. Empty vector encodes 0.
1883
+ */
1884
+ function decodeScriptNum(data, label) {
1885
+ if (data.length === 0)
1886
+ return 0n;
1887
+ if (data.length > 8) {
1888
+ throw new Error(`parse: CScriptNum at ${label} exceeds 8 bytes`);
1889
+ }
1890
+ let n = 0n;
1891
+ for (let i = 0; i < data.length - 1; i += 1) {
1892
+ n |= BigInt(data[i]) << BigInt(8 * i);
1893
+ }
1894
+ const last = data[data.length - 1];
1895
+ n |= BigInt(last & 0x7f) << BigInt(8 * (data.length - 1));
1896
+ if (last & 0x80) {
1897
+ n = -n;
1898
+ }
1899
+ return n;
1900
+ }
1901
+ /**
1902
+ * Read a push as a non-negative CScriptNum. Recognises OP_1..OP_16
1903
+ * shorthand. `OP_0` is not accepted because the covenant callers use this
1904
+ * only for values that are strictly positive (prices, selectors, indices).
1905
+ */
1906
+ function readPushPositiveInt(c, label) {
1907
+ if (c.pos >= c.bytes.length) {
1908
+ throw new Error(`parse: end of script at ${label}`);
1909
+ }
1910
+ const opcode = c.bytes[c.pos];
1911
+ if (opcode >= OP_1 && opcode <= 0x60) {
1912
+ c.pos += 1;
1913
+ return BigInt(opcode - OP_1 + 1);
1914
+ }
1915
+ const data = readPush(c, label);
1916
+ return decodeScriptNum(data, label);
1917
+ }
1918
+ /**
1919
+ * Read a 1-byte selector as an UNSIGNED 8-bit integer (0..255). Accepts
1920
+ * two on-wire encodings, because old vs new covenant builders differ:
1921
+ * - `OP_1..OP_16` shorthand (single opcode) → values 1..16.
1922
+ * - `0x01 <byte>` raw 1-byte push → any value 1..255.
1923
+ *
1924
+ * Values 0x80..0xff MUST use the raw-push form; the CScriptNum encoding
1925
+ * would need a 0x00 padding byte and become 2 bytes on-stack, which
1926
+ * consensus `OP_TXHASH` rejects. The builder in `script-pq.ts` emits the
1927
+ * raw-push form unconditionally; the parser stays lenient so covenants
1928
+ * built by older tools (using OP_N for small values) still round-trip.
1929
+ */
1930
+ function readPushUint8(c, label) {
1931
+ if (c.pos >= c.bytes.length) {
1932
+ throw new Error(`parse: end of script at ${label}`);
1933
+ }
1934
+ const opcode = c.bytes[c.pos];
1935
+ if (opcode >= OP_1 && opcode <= 0x60) {
1936
+ c.pos += 1;
1937
+ return opcode - OP_1 + 1;
1938
+ }
1939
+ const data = readPush(c, label);
1940
+ if (data.length !== 1) {
1941
+ throw new Error(`parse: ${label} must be a single-byte push, got ${data.length} bytes`);
1942
+ }
1943
+ return data[0];
1944
+ }
1945
+
1946
+ const MAX_INT64 = 0x7fffffffffffffffn;
1947
+ function selectorForMode(mode) {
1948
+ if (mode === 'height')
1949
+ return CHAINCONTEXT_HEIGHT;
1950
+ if (mode === 'mtp')
1951
+ return CHAINCONTEXT_MTP;
1952
+ throw new Error('expiration.mode must be "height" or "mtp"');
1953
+ }
1954
+ function modeForSelector(selector) {
1955
+ if (selector === CHAINCONTEXT_HEIGHT)
1956
+ return 'height';
1957
+ if (selector === CHAINCONTEXT_MTP)
1958
+ return 'mtp';
1959
+ throw new Error('expiration OP_CHAINCONTEXT selector must be HEIGHT (0x01) or MTP (0x02)');
1960
+ }
1961
+ function assertExpiration(expiration) {
1962
+ if (expiration === undefined)
1963
+ return undefined;
1964
+ if (expiration === null || typeof expiration !== 'object') {
1965
+ throw new Error('expiration must be an object');
1966
+ }
1967
+ selectorForMode(expiration.mode);
1968
+ if (typeof expiration.value !== 'bigint') {
1969
+ throw new Error('expiration.value must be a bigint');
1970
+ }
1971
+ if (expiration.value <= 0n) {
1972
+ throw new Error('expiration.value must be > 0');
1973
+ }
1974
+ if (expiration.value > MAX_INT64) {
1975
+ throw new Error('expiration.value exceeds int64 range');
1976
+ }
1977
+ return expiration;
1978
+ }
1979
+ function appendExpirationGate(b, expiration) {
1980
+ if (!expiration)
1981
+ return;
1982
+ // Selectors 1 (HEIGHT) and 2 (MTP) must be pushed as OP_1 / OP_2 so the
1983
+ // resulting script is consensus-minimal (MINIMALDATA). `pushBytes(0x01 N)`
1984
+ // would emit `01 0N`, which the consensus rule rejects for N in 1..16.
1985
+ // Parser side stays lenient (`readPushUint8` accepts both forms) so old
1986
+ // covenants in the raw `01 0N` form keep round-tripping.
1987
+ b.pushInt(expiration.value)
1988
+ .pushInt(selectorForMode(expiration.mode))
1989
+ .op(OP_CHAINCONTEXT, OP_GREATERTHAN, OP_VERIFY);
1990
+ }
1991
+ function readOptionalExpirationGate(c, nextOpcodeWithoutGate, label) {
1992
+ if (c.pos >= c.bytes.length || c.bytes[c.pos] === nextOpcodeWithoutGate) {
1993
+ return undefined;
1994
+ }
1995
+ const value = readPushPositiveInt(c, `expiration value (${label})`);
1996
+ if (value <= 0n) {
1997
+ throw new Error(`parse: expiration value (${label}) must be > 0`);
1998
+ }
1999
+ const selector = readPushUint8(c, `expiration selector (${label})`);
2000
+ const mode = modeForSelector(selector);
2001
+ expectByte(c, OP_CHAINCONTEXT, `OP_CHAINCONTEXT (${label})`);
2002
+ expectByte(c, OP_GREATERTHAN, `OP_GREATERTHAN (${label})`);
2003
+ expectByte(c, OP_VERIFY, `OP_VERIFY (${label})`);
2004
+ return { mode, value };
2005
+ }
2006
+ function assertSameExpiration(a, b, label) {
2007
+ if (a === undefined && b === undefined)
2008
+ return;
2009
+ if (a === undefined || b === undefined || a.mode !== b.mode || a.value !== b.value) {
2010
+ throw new Error(`parse: expiration differs between ${label}`);
2011
+ }
2012
+ }
2013
+
1791
2014
  /**
1792
2015
  * Partial-Fill Sell Order covenant script (three-branch).
1793
2016
  *
@@ -1873,6 +2096,7 @@ var NeuraiScriptsBundle = (function (exports) {
1873
2096
  const sellerPubKeyHash = decodeSellerAddress(sellerAddress);
1874
2097
  assertTokenId$1(tokenId);
1875
2098
  assertPrice$1(unitPriceSats);
2099
+ const expiration = assertExpiration(params.expiration);
1876
2100
  const sellerScriptPubKey = encodeP2PKHScriptPubKey(sellerPubKeyHash);
1877
2101
  const tokenIdBytes = new TextEncoder().encode(tokenId);
1878
2102
  const b = new ScriptBuilder();
@@ -1893,6 +2117,7 @@ var NeuraiScriptsBundle = (function (exports) {
1893
2117
  // push N. The entire covenant is drained to vout[1]; no vout[2] is
1894
2118
  // constrained and none is required (consensus forbids zero-amount asset
1895
2119
  // transfers, so the partial-fill continuity check is simply skipped).
2120
+ appendExpirationGate(b, expiration);
1896
2121
  // 1. N = inputAmount
1897
2122
  b.pushInt(0)
1898
2123
  .pushInt(ASSETFIELD_AMOUNT)
@@ -1929,6 +2154,7 @@ var NeuraiScriptsBundle = (function (exports) {
1929
2154
  // scriptSig: <N> <0> <0> ( N, full-flag=0, cancel-flag=0 )
1930
2155
  // Stack entering: [ N ]
1931
2156
  b.op(OP_ELSE);
2157
+ appendExpirationGate(b, expiration);
1932
2158
  // 1. Payment value (output 0) >= N * unitPriceSats
1933
2159
  b.op(OP_DUP) // [ N, N ]
1934
2160
  .pushInt(unitPriceSats) // [ N, N, price ]
@@ -2063,6 +2289,7 @@ var NeuraiScriptsBundle = (function (exports) {
2063
2289
  assertTokenId(tokenId);
2064
2290
  assertPrice(unitPriceSats);
2065
2291
  assertSelector(txHashSelector);
2292
+ const expiration = assertExpiration(params.expiration);
2066
2293
  const payment = encodeSellerScriptPubKey(paymentAddress);
2067
2294
  const tokenIdBytes = new TextEncoder().encode(tokenId);
2068
2295
  const b = new ScriptBuilder();
@@ -2090,6 +2317,7 @@ var NeuraiScriptsBundle = (function (exports) {
2090
2317
  // scriptSig: <1> <0>
2091
2318
  // Stack entering: [ ]
2092
2319
  // 1. N = inputAmount
2320
+ appendExpirationGate(b, expiration);
2093
2321
  b.pushInt(0)
2094
2322
  .pushInt(ASSETFIELD_AMOUNT)
2095
2323
  .op(OP_INPUTASSETFIELD);
@@ -2124,6 +2352,7 @@ var NeuraiScriptsBundle = (function (exports) {
2124
2352
  // scriptSig: <N> <0> <0>
2125
2353
  // Stack entering: [ N ]
2126
2354
  b.op(OP_ELSE);
2355
+ appendExpirationGate(b, expiration);
2127
2356
  // 1. Payment value (output 0) >= N * unitPriceSats
2128
2357
  b.op(OP_DUP)
2129
2358
  .pushInt(unitPriceSats)
@@ -2313,152 +2542,6 @@ var NeuraiScriptsBundle = (function (exports) {
2313
2542
  return bytesToHex(buildCancelScriptSigPQ(sigPQ, pubKey));
2314
2543
  }
2315
2544
 
2316
- /**
2317
- * Shared parsing primitives for strict covenant parsers. Each covenant
2318
- * parser walks the exact byte layout emitted by its builder and fails on
2319
- * any deviation; the primitives here centralize the cursor arithmetic,
2320
- * pushdata decoding, and CScriptNum decoding so the legacy and PQ parsers
2321
- * (and future covenant parsers) cannot drift in rigor.
2322
- */
2323
- function makeCursor(bytes) {
2324
- return { bytes, pos: 0 };
2325
- }
2326
- /** Consume one byte and verify it equals `expected`. */
2327
- function expectByte(c, expected, label) {
2328
- if (c.pos >= c.bytes.length) {
2329
- throw new Error(`parse: unexpected end of script while reading ${label}`);
2330
- }
2331
- const got = c.bytes[c.pos];
2332
- if (got !== expected) {
2333
- throw new Error(`parse: expected ${label} = 0x${expected.toString(16)} at offset ${c.pos}, got 0x${got.toString(16)}`);
2334
- }
2335
- c.pos += 1;
2336
- }
2337
- /** Fail if the cursor has not consumed every byte of the script. */
2338
- function assertTrailing(c) {
2339
- if (c.pos !== c.bytes.length) {
2340
- throw new Error(`parse: ${c.bytes.length - c.pos} trailing bytes after end of script`);
2341
- }
2342
- }
2343
- /**
2344
- * Read one pushdata element from the cursor. Supports direct pushes
2345
- * (1..75 bytes), `OP_PUSHDATA1` and `OP_PUSHDATA2`. `OP_PUSHDATA4` is not
2346
- * supported by any current covenant script and would overflow the
2347
- * per-element cap anyway. Truncation is checked for all length fields
2348
- * and payload ranges.
2349
- */
2350
- function readPush(c, label) {
2351
- if (c.pos >= c.bytes.length) {
2352
- throw new Error(`parse: unexpected end of script while reading push for ${label}`);
2353
- }
2354
- const opcode = c.bytes[c.pos];
2355
- c.pos += 1;
2356
- // Short direct push: 1..75 bytes
2357
- if (opcode >= 0x01 && opcode <= 0x4b) {
2358
- const len = opcode;
2359
- if (c.pos + len > c.bytes.length) {
2360
- throw new Error(`parse: short push of ${len} bytes exceeds script length at ${label}`);
2361
- }
2362
- const data = c.bytes.slice(c.pos, c.pos + len);
2363
- c.pos += len;
2364
- return data;
2365
- }
2366
- // OP_PUSHDATA1
2367
- if (opcode === 0x4c) {
2368
- if (c.pos >= c.bytes.length) {
2369
- throw new Error(`parse: truncated PUSHDATA1 length at ${label}`);
2370
- }
2371
- const len = c.bytes[c.pos];
2372
- c.pos += 1;
2373
- if (c.pos + len > c.bytes.length) {
2374
- throw new Error(`parse: PUSHDATA1 of ${len} bytes exceeds script length at ${label}`);
2375
- }
2376
- const data = c.bytes.slice(c.pos, c.pos + len);
2377
- c.pos += len;
2378
- return data;
2379
- }
2380
- // OP_PUSHDATA2
2381
- if (opcode === 0x4d) {
2382
- if (c.pos + 2 > c.bytes.length) {
2383
- throw new Error(`parse: truncated PUSHDATA2 length at ${label}`);
2384
- }
2385
- const len = c.bytes[c.pos] | (c.bytes[c.pos + 1] << 8);
2386
- c.pos += 2;
2387
- if (c.pos + len > c.bytes.length) {
2388
- throw new Error(`parse: PUSHDATA2 of ${len} bytes exceeds script length at ${label}`);
2389
- }
2390
- const data = c.bytes.slice(c.pos, c.pos + len);
2391
- c.pos += len;
2392
- return data;
2393
- }
2394
- throw new Error(`parse: expected a pushdata opcode at ${label}, got 0x${opcode.toString(16)} at offset ${c.pos - 1}`);
2395
- }
2396
- /**
2397
- * Decode a `CScriptNum` byte vector (little-endian sign-magnitude, up to
2398
- * 8 bytes) into a BigInt. Empty vector encodes 0.
2399
- */
2400
- function decodeScriptNum(data, label) {
2401
- if (data.length === 0)
2402
- return 0n;
2403
- if (data.length > 8) {
2404
- throw new Error(`parse: CScriptNum at ${label} exceeds 8 bytes`);
2405
- }
2406
- let n = 0n;
2407
- for (let i = 0; i < data.length - 1; i += 1) {
2408
- n |= BigInt(data[i]) << BigInt(8 * i);
2409
- }
2410
- const last = data[data.length - 1];
2411
- n |= BigInt(last & 0x7f) << BigInt(8 * (data.length - 1));
2412
- if (last & 0x80) {
2413
- n = -n;
2414
- }
2415
- return n;
2416
- }
2417
- /**
2418
- * Read a push as a non-negative CScriptNum. Recognises OP_1..OP_16
2419
- * shorthand. `OP_0` is not accepted because the covenant callers use this
2420
- * only for values that are strictly positive (prices, selectors, indices).
2421
- */
2422
- function readPushPositiveInt(c, label) {
2423
- if (c.pos >= c.bytes.length) {
2424
- throw new Error(`parse: end of script at ${label}`);
2425
- }
2426
- const opcode = c.bytes[c.pos];
2427
- if (opcode >= OP_1 && opcode <= 0x60) {
2428
- c.pos += 1;
2429
- return BigInt(opcode - OP_1 + 1);
2430
- }
2431
- const data = readPush(c, label);
2432
- return decodeScriptNum(data, label);
2433
- }
2434
- /**
2435
- * Read a 1-byte selector as an UNSIGNED 8-bit integer (0..255). Accepts
2436
- * two on-wire encodings, because old vs new covenant builders differ:
2437
- * - `OP_1..OP_16` shorthand (single opcode) → values 1..16.
2438
- * - `0x01 <byte>` raw 1-byte push → any value 1..255.
2439
- *
2440
- * Values 0x80..0xff MUST use the raw-push form; the CScriptNum encoding
2441
- * would need a 0x00 padding byte and become 2 bytes on-stack, which
2442
- * consensus `OP_TXHASH` rejects. The builder in `script-pq.ts` emits the
2443
- * raw-push form unconditionally; the parser stays lenient so covenants
2444
- * built by older tools (using OP_N for small values) still round-trip.
2445
- */
2446
- function readPushUint8(c, label) {
2447
- if (c.pos >= c.bytes.length) {
2448
- throw new Error(`parse: end of script at ${label}`);
2449
- }
2450
- const opcode = c.bytes[c.pos];
2451
- if (opcode >= OP_1 && opcode <= 0x60) {
2452
- c.pos += 1;
2453
- return opcode - OP_1 + 1;
2454
- }
2455
- const data = readPush(c, label);
2456
- if (data.length !== 1) {
2457
- throw new Error(`parse: ${label} must be a single-byte push, got ${data.length} bytes`);
2458
- }
2459
- return data[0];
2460
- }
2461
-
2462
2545
  /**
2463
2546
  * Parser for the Partial-Fill Sell Order covenant (three-branch).
2464
2547
  *
@@ -2492,6 +2575,7 @@ var NeuraiScriptsBundle = (function (exports) {
2492
2575
  expectByte(c, OP_ELSE, 'OP_ELSE (outer → fill)');
2493
2576
  // ═════ Inner IF — Full-fill branch ═════
2494
2577
  expectByte(c, OP_IF, 'OP_IF (inner full-fill)');
2578
+ const expirationFull = readOptionalExpirationGate(c, OP_0, 'full');
2495
2579
  // N = inputAmount
2496
2580
  expectByte(c, OP_0, 'OP_0 (input idx, full)');
2497
2581
  expectByte(c, OP_2, 'OP_2 (AMOUNT sel, full)');
@@ -2533,6 +2617,7 @@ var NeuraiScriptsBundle = (function (exports) {
2533
2617
  expectByte(c, OP_1, 'OP_1 (true, full)');
2534
2618
  expectByte(c, OP_ELSE, 'OP_ELSE (inner → partial fill)');
2535
2619
  // ═════ Inner ELSE — Partial-fill branch ═════
2620
+ const expirationPartial = readOptionalExpirationGate(c, OP_DUP, 'partial');
2536
2621
  // Payment value
2537
2622
  expectByte(c, OP_DUP, 'OP_DUP (price, partial)');
2538
2623
  const unitPriceSatsPartial = readPushPositiveInt(c, 'unitPriceSats (partial)');
@@ -2603,12 +2688,14 @@ var NeuraiScriptsBundle = (function (exports) {
2603
2688
  if (unitPriceSatsFull !== unitPriceSatsPartial) {
2604
2689
  throw new Error('parse: unitPriceSats differs between full-fill and partial-fill branches');
2605
2690
  }
2691
+ assertSameExpiration(expirationFull, expirationPartial, 'full-fill and partial-fill branches');
2606
2692
  const tokenId = new TextDecoder('utf-8', { fatal: true }).decode(tokenIdFull);
2607
2693
  return {
2608
2694
  network,
2609
2695
  sellerPubKeyHash,
2610
2696
  unitPriceSats: unitPriceSatsFull,
2611
2697
  tokenId,
2698
+ expiration: expirationFull,
2612
2699
  scriptHex: bytesToHex(bytes)
2613
2700
  };
2614
2701
  }
@@ -2658,6 +2745,7 @@ var NeuraiScriptsBundle = (function (exports) {
2658
2745
  expectByte(c, OP_ELSE, 'OP_ELSE (outer → fill)');
2659
2746
  // ═════ Inner IF — Full-fill branch ═════
2660
2747
  expectByte(c, OP_IF, 'OP_IF (inner full-fill)');
2748
+ const expirationFull = readOptionalExpirationGate(c, OP_0, 'full');
2661
2749
  expectByte(c, OP_0, 'OP_0 (input idx, full)');
2662
2750
  expectByte(c, OP_2, 'OP_2 (AMOUNT sel, full)');
2663
2751
  expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD (full)');
@@ -2687,6 +2775,7 @@ var NeuraiScriptsBundle = (function (exports) {
2687
2775
  expectByte(c, OP_1, 'OP_1 (true, full)');
2688
2776
  expectByte(c, OP_ELSE, 'OP_ELSE (inner → partial fill)');
2689
2777
  // ═════ Inner ELSE — Partial-fill branch ═════
2778
+ const expirationPartial = readOptionalExpirationGate(c, OP_DUP, 'partial');
2690
2779
  expectByte(c, OP_DUP, 'OP_DUP (price, partial)');
2691
2780
  const unitPriceSatsPartial = readPushPositiveInt(c, 'unitPriceSats (partial)');
2692
2781
  expectByte(c, OP_MUL, 'OP_MUL (partial)');
@@ -2748,6 +2837,7 @@ var NeuraiScriptsBundle = (function (exports) {
2748
2837
  if (unitPriceSatsFull !== unitPriceSatsPartial) {
2749
2838
  throw new Error('parse-pq: unitPriceSats differs between full-fill and partial-fill branches');
2750
2839
  }
2840
+ assertSameExpiration(expirationFull, expirationPartial, 'full-fill and partial-fill branches');
2751
2841
  const tokenId = new TextDecoder('utf-8', { fatal: true }).decode(tokenIdFull);
2752
2842
  return {
2753
2843
  network,
@@ -2755,6 +2845,7 @@ var NeuraiScriptsBundle = (function (exports) {
2755
2845
  tokenId,
2756
2846
  unitPriceSats: unitPriceSatsFull,
2757
2847
  txHashSelector,
2848
+ expiration: expirationFull,
2758
2849
  paymentScriptPubKey: paymentScriptPubKeyFull,
2759
2850
  scriptHex: bytesToHex(bytes)
2760
2851
  };