@neuraiproject/neurai-scripts 0.5.1 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md 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
@@ -156,6 +156,26 @@ var NeuraiScriptsBundle = (function (exports) {
156
156
  const OP_CHECKSIGVERIFY = 0xad;
157
157
  const OP_CHECKMULTISIG = 0xae;
158
158
  const OP_CHECKMULTISIGVERIFY = 0xaf;
159
+ // ---------- Extended hash opcodes ----------
160
+ // NIP-030: KECCAK256 / BLAKE2B in previously unassigned slots.
161
+ const OP_KECCAK256 = 0xba;
162
+ const OP_BLAKE2B = 0xbb;
163
+ // NIP-034a: modern hash opcodes (BLAKE3, SHA3-256, SHA-512).
164
+ // NIP-036: OP_POSEIDON — SNARK-friendly Poseidon hash over the BN254
165
+ // scalar field. Occupies slot 0xc9.
166
+ const OP_BLAKE3 = 0xc8;
167
+ const OP_POSEIDON = 0xc9;
168
+ const OP_SHA3_256 = 0xca;
169
+ const OP_SHA512 = 0xcb;
170
+ // ---------- Extended signature opcodes ----------
171
+ // NIP-035: strict-profile RFC 8032 PureEd25519 verifier in slot 0xdd.
172
+ // Stack contract: (sig64, msg, pubkey32 -- 0|1). Slots 0xd8..0xdc are
173
+ // reserved by NIP-033 (BLS12-381 family), unassigned in current code.
174
+ const OP_CHECKSIG_ED25519 = 0xdd;
175
+ // NIP-039: generic OP_CHECKSIG-compatible signature accumulator in slot
176
+ // 0xde. Stack contract: (sig, count, pubkey -- count + 0|1). Works with
177
+ // both legacy secp256k1 and PQ ML-DSA-44 keys via CPubKey::Verify().
178
+ const OP_CHECKSIGADD = 0xde;
159
179
  // ---------- Expansion / NOPs ----------
160
180
  // Only the NOPs not aliased by DePIN-Test opcodes are exported as NOPs.
161
181
  // OP_NOP2 == OP_CHECKLOCKTIMEVERIFY (0xb1)
@@ -195,6 +215,23 @@ var NeuraiScriptsBundle = (function (exports) {
195
215
  // scriptPubKey. Symmetric to TXFIELD_AUTHSCRIPT_COMMITMENT for inputs;
196
216
  // ignores any trailing OP_XNA_ASSET asset wrapper bytes.
197
217
  const OP_OUTPUTAUTHCOMMITMENT = 0xd5;
218
+ // ---------- Input value introspection (NIP-024) ----------
219
+ // Pushes the satoshi value of a selected input's spent prevout.
220
+ const OP_INPUTVALUE = 0xd6;
221
+ // ---------- Chain context introspection (NIP-026) ----------
222
+ // Pushes chain-context fields (block height, median time, etc.) selected
223
+ // by a single-byte selector consumed from the stack.
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;
231
+ // ---------- Merkle inclusion (NIP-031) ----------
232
+ // Native Merkle inclusion verifier. Consumes (leaf, scheme_id, proof,
233
+ // root) and pushes a boolean. Flag off → bad-opcode.
234
+ const OP_CHECKMERKLEINCLUSION = 0xc1;
198
235
  // ---------- Byte manipulation (DePIN-Test) ----------
199
236
  const OP_CAT = 0x7e;
200
237
  const OP_SPLIT = 0xb7;
@@ -240,6 +277,9 @@ var NeuraiScriptsBundle = (function (exports) {
240
277
  ASSETFIELD_REISSUABLE: ASSETFIELD_REISSUABLE,
241
278
  ASSETFIELD_TYPE: ASSETFIELD_TYPE,
242
279
  ASSETFIELD_UNITS: ASSETFIELD_UNITS,
280
+ CHAINCONTEXT_CHAIN_ID: CHAINCONTEXT_CHAIN_ID,
281
+ CHAINCONTEXT_HEIGHT: CHAINCONTEXT_HEIGHT,
282
+ CHAINCONTEXT_MTP: CHAINCONTEXT_MTP,
243
283
  OP_0: OP_0,
244
284
  OP_0NOTEQUAL: OP_0NOTEQUAL,
245
285
  OP_1: OP_1,
@@ -269,16 +309,22 @@ var NeuraiScriptsBundle = (function (exports) {
269
309
  OP_9: OP_9,
270
310
  OP_ABS: OP_ABS,
271
311
  OP_ADD: OP_ADD,
312
+ OP_BLAKE2B: OP_BLAKE2B,
313
+ OP_BLAKE3: OP_BLAKE3,
272
314
  OP_BOOLAND: OP_BOOLAND,
273
315
  OP_BOOLOR: OP_BOOLOR,
274
316
  OP_CAT: OP_CAT,
317
+ OP_CHAINCONTEXT: OP_CHAINCONTEXT,
275
318
  OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY,
319
+ OP_CHECKMERKLEINCLUSION: OP_CHECKMERKLEINCLUSION,
276
320
  OP_CHECKMULTISIG: OP_CHECKMULTISIG,
277
321
  OP_CHECKMULTISIGVERIFY: OP_CHECKMULTISIGVERIFY,
278
322
  OP_CHECKSEQUENCEVERIFY: OP_CHECKSEQUENCEVERIFY,
279
323
  OP_CHECKSIG: OP_CHECKSIG,
324
+ OP_CHECKSIGADD: OP_CHECKSIGADD,
280
325
  OP_CHECKSIGFROMSTACK: OP_CHECKSIGFROMSTACK,
281
326
  OP_CHECKSIGVERIFY: OP_CHECKSIGVERIFY,
327
+ OP_CHECKSIG_ED25519: OP_CHECKSIG_ED25519,
282
328
  OP_CHECKTEMPLATEVERIFY: OP_CHECKTEMPLATEVERIFY,
283
329
  OP_CODESEPARATOR: OP_CODESEPARATOR,
284
330
  OP_DEPTH: OP_DEPTH,
@@ -299,6 +345,8 @@ var NeuraiScriptsBundle = (function (exports) {
299
345
  OP_IFDUP: OP_IFDUP,
300
346
  OP_INPUTASSETFIELD: OP_INPUTASSETFIELD,
301
347
  OP_INPUTCOUNT: OP_INPUTCOUNT,
348
+ OP_INPUTVALUE: OP_INPUTVALUE,
349
+ OP_KECCAK256: OP_KECCAK256,
302
350
  OP_LESSTHAN: OP_LESSTHAN,
303
351
  OP_LESSTHANOREQUAL: OP_LESSTHANOREQUAL,
304
352
  OP_MAX: OP_MAX,
@@ -323,6 +371,7 @@ var NeuraiScriptsBundle = (function (exports) {
323
371
  OP_OUTPUTVALUE: OP_OUTPUTVALUE,
324
372
  OP_OVER: OP_OVER,
325
373
  OP_PICK: OP_PICK,
374
+ OP_POSEIDON: OP_POSEIDON,
326
375
  OP_PUSHDATA1: OP_PUSHDATA1,
327
376
  OP_PUSHDATA2: OP_PUSHDATA2,
328
377
  OP_PUSHDATA4: OP_PUSHDATA4,
@@ -337,6 +386,8 @@ var NeuraiScriptsBundle = (function (exports) {
337
386
  OP_ROT: OP_ROT,
338
387
  OP_SHA1: OP_SHA1,
339
388
  OP_SHA256: OP_SHA256,
389
+ OP_SHA3_256: OP_SHA3_256,
390
+ OP_SHA512: OP_SHA512,
340
391
  OP_SIZE: OP_SIZE,
341
392
  OP_SPLIT: OP_SPLIT,
342
393
  OP_SUB: OP_SUB,
@@ -1746,6 +1797,215 @@ var NeuraiScriptsBundle = (function (exports) {
1746
1797
  };
1747
1798
  }
1748
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
+ b.pushInt(expiration.value)
1983
+ .pushBytes(Uint8Array.of(selectorForMode(expiration.mode)))
1984
+ .op(OP_CHAINCONTEXT, OP_GREATERTHAN, OP_VERIFY);
1985
+ }
1986
+ function readOptionalExpirationGate(c, nextOpcodeWithoutGate, label) {
1987
+ if (c.pos >= c.bytes.length || c.bytes[c.pos] === nextOpcodeWithoutGate) {
1988
+ return undefined;
1989
+ }
1990
+ const value = readPushPositiveInt(c, `expiration value (${label})`);
1991
+ if (value <= 0n) {
1992
+ throw new Error(`parse: expiration value (${label}) must be > 0`);
1993
+ }
1994
+ const selector = readPushUint8(c, `expiration selector (${label})`);
1995
+ const mode = modeForSelector(selector);
1996
+ expectByte(c, OP_CHAINCONTEXT, `OP_CHAINCONTEXT (${label})`);
1997
+ expectByte(c, OP_GREATERTHAN, `OP_GREATERTHAN (${label})`);
1998
+ expectByte(c, OP_VERIFY, `OP_VERIFY (${label})`);
1999
+ return { mode, value };
2000
+ }
2001
+ function assertSameExpiration(a, b, label) {
2002
+ if (a === undefined && b === undefined)
2003
+ return;
2004
+ if (a === undefined || b === undefined || a.mode !== b.mode || a.value !== b.value) {
2005
+ throw new Error(`parse: expiration differs between ${label}`);
2006
+ }
2007
+ }
2008
+
1749
2009
  /**
1750
2010
  * Partial-Fill Sell Order covenant script (three-branch).
1751
2011
  *
@@ -1831,6 +2091,7 @@ var NeuraiScriptsBundle = (function (exports) {
1831
2091
  const sellerPubKeyHash = decodeSellerAddress(sellerAddress);
1832
2092
  assertTokenId$1(tokenId);
1833
2093
  assertPrice$1(unitPriceSats);
2094
+ const expiration = assertExpiration(params.expiration);
1834
2095
  const sellerScriptPubKey = encodeP2PKHScriptPubKey(sellerPubKeyHash);
1835
2096
  const tokenIdBytes = new TextEncoder().encode(tokenId);
1836
2097
  const b = new ScriptBuilder();
@@ -1851,6 +2112,7 @@ var NeuraiScriptsBundle = (function (exports) {
1851
2112
  // push N. The entire covenant is drained to vout[1]; no vout[2] is
1852
2113
  // constrained and none is required (consensus forbids zero-amount asset
1853
2114
  // transfers, so the partial-fill continuity check is simply skipped).
2115
+ appendExpirationGate(b, expiration);
1854
2116
  // 1. N = inputAmount
1855
2117
  b.pushInt(0)
1856
2118
  .pushInt(ASSETFIELD_AMOUNT)
@@ -1887,6 +2149,7 @@ var NeuraiScriptsBundle = (function (exports) {
1887
2149
  // scriptSig: <N> <0> <0> ( N, full-flag=0, cancel-flag=0 )
1888
2150
  // Stack entering: [ N ]
1889
2151
  b.op(OP_ELSE);
2152
+ appendExpirationGate(b, expiration);
1890
2153
  // 1. Payment value (output 0) >= N * unitPriceSats
1891
2154
  b.op(OP_DUP) // [ N, N ]
1892
2155
  .pushInt(unitPriceSats) // [ N, N, price ]
@@ -2021,6 +2284,7 @@ var NeuraiScriptsBundle = (function (exports) {
2021
2284
  assertTokenId(tokenId);
2022
2285
  assertPrice(unitPriceSats);
2023
2286
  assertSelector(txHashSelector);
2287
+ const expiration = assertExpiration(params.expiration);
2024
2288
  const payment = encodeSellerScriptPubKey(paymentAddress);
2025
2289
  const tokenIdBytes = new TextEncoder().encode(tokenId);
2026
2290
  const b = new ScriptBuilder();
@@ -2048,6 +2312,7 @@ var NeuraiScriptsBundle = (function (exports) {
2048
2312
  // scriptSig: <1> <0>
2049
2313
  // Stack entering: [ ]
2050
2314
  // 1. N = inputAmount
2315
+ appendExpirationGate(b, expiration);
2051
2316
  b.pushInt(0)
2052
2317
  .pushInt(ASSETFIELD_AMOUNT)
2053
2318
  .op(OP_INPUTASSETFIELD);
@@ -2082,6 +2347,7 @@ var NeuraiScriptsBundle = (function (exports) {
2082
2347
  // scriptSig: <N> <0> <0>
2083
2348
  // Stack entering: [ N ]
2084
2349
  b.op(OP_ELSE);
2350
+ appendExpirationGate(b, expiration);
2085
2351
  // 1. Payment value (output 0) >= N * unitPriceSats
2086
2352
  b.op(OP_DUP)
2087
2353
  .pushInt(unitPriceSats)
@@ -2271,152 +2537,6 @@ var NeuraiScriptsBundle = (function (exports) {
2271
2537
  return bytesToHex(buildCancelScriptSigPQ(sigPQ, pubKey));
2272
2538
  }
2273
2539
 
2274
- /**
2275
- * Shared parsing primitives for strict covenant parsers. Each covenant
2276
- * parser walks the exact byte layout emitted by its builder and fails on
2277
- * any deviation; the primitives here centralize the cursor arithmetic,
2278
- * pushdata decoding, and CScriptNum decoding so the legacy and PQ parsers
2279
- * (and future covenant parsers) cannot drift in rigor.
2280
- */
2281
- function makeCursor(bytes) {
2282
- return { bytes, pos: 0 };
2283
- }
2284
- /** Consume one byte and verify it equals `expected`. */
2285
- function expectByte(c, expected, label) {
2286
- if (c.pos >= c.bytes.length) {
2287
- throw new Error(`parse: unexpected end of script while reading ${label}`);
2288
- }
2289
- const got = c.bytes[c.pos];
2290
- if (got !== expected) {
2291
- throw new Error(`parse: expected ${label} = 0x${expected.toString(16)} at offset ${c.pos}, got 0x${got.toString(16)}`);
2292
- }
2293
- c.pos += 1;
2294
- }
2295
- /** Fail if the cursor has not consumed every byte of the script. */
2296
- function assertTrailing(c) {
2297
- if (c.pos !== c.bytes.length) {
2298
- throw new Error(`parse: ${c.bytes.length - c.pos} trailing bytes after end of script`);
2299
- }
2300
- }
2301
- /**
2302
- * Read one pushdata element from the cursor. Supports direct pushes
2303
- * (1..75 bytes), `OP_PUSHDATA1` and `OP_PUSHDATA2`. `OP_PUSHDATA4` is not
2304
- * supported by any current covenant script and would overflow the
2305
- * per-element cap anyway. Truncation is checked for all length fields
2306
- * and payload ranges.
2307
- */
2308
- function readPush(c, label) {
2309
- if (c.pos >= c.bytes.length) {
2310
- throw new Error(`parse: unexpected end of script while reading push for ${label}`);
2311
- }
2312
- const opcode = c.bytes[c.pos];
2313
- c.pos += 1;
2314
- // Short direct push: 1..75 bytes
2315
- if (opcode >= 0x01 && opcode <= 0x4b) {
2316
- const len = opcode;
2317
- if (c.pos + len > c.bytes.length) {
2318
- throw new Error(`parse: short push of ${len} bytes exceeds script length at ${label}`);
2319
- }
2320
- const data = c.bytes.slice(c.pos, c.pos + len);
2321
- c.pos += len;
2322
- return data;
2323
- }
2324
- // OP_PUSHDATA1
2325
- if (opcode === 0x4c) {
2326
- if (c.pos >= c.bytes.length) {
2327
- throw new Error(`parse: truncated PUSHDATA1 length at ${label}`);
2328
- }
2329
- const len = c.bytes[c.pos];
2330
- c.pos += 1;
2331
- if (c.pos + len > c.bytes.length) {
2332
- throw new Error(`parse: PUSHDATA1 of ${len} bytes exceeds script length at ${label}`);
2333
- }
2334
- const data = c.bytes.slice(c.pos, c.pos + len);
2335
- c.pos += len;
2336
- return data;
2337
- }
2338
- // OP_PUSHDATA2
2339
- if (opcode === 0x4d) {
2340
- if (c.pos + 2 > c.bytes.length) {
2341
- throw new Error(`parse: truncated PUSHDATA2 length at ${label}`);
2342
- }
2343
- const len = c.bytes[c.pos] | (c.bytes[c.pos + 1] << 8);
2344
- c.pos += 2;
2345
- if (c.pos + len > c.bytes.length) {
2346
- throw new Error(`parse: PUSHDATA2 of ${len} bytes exceeds script length at ${label}`);
2347
- }
2348
- const data = c.bytes.slice(c.pos, c.pos + len);
2349
- c.pos += len;
2350
- return data;
2351
- }
2352
- throw new Error(`parse: expected a pushdata opcode at ${label}, got 0x${opcode.toString(16)} at offset ${c.pos - 1}`);
2353
- }
2354
- /**
2355
- * Decode a `CScriptNum` byte vector (little-endian sign-magnitude, up to
2356
- * 8 bytes) into a BigInt. Empty vector encodes 0.
2357
- */
2358
- function decodeScriptNum(data, label) {
2359
- if (data.length === 0)
2360
- return 0n;
2361
- if (data.length > 8) {
2362
- throw new Error(`parse: CScriptNum at ${label} exceeds 8 bytes`);
2363
- }
2364
- let n = 0n;
2365
- for (let i = 0; i < data.length - 1; i += 1) {
2366
- n |= BigInt(data[i]) << BigInt(8 * i);
2367
- }
2368
- const last = data[data.length - 1];
2369
- n |= BigInt(last & 0x7f) << BigInt(8 * (data.length - 1));
2370
- if (last & 0x80) {
2371
- n = -n;
2372
- }
2373
- return n;
2374
- }
2375
- /**
2376
- * Read a push as a non-negative CScriptNum. Recognises OP_1..OP_16
2377
- * shorthand. `OP_0` is not accepted because the covenant callers use this
2378
- * only for values that are strictly positive (prices, selectors, indices).
2379
- */
2380
- function readPushPositiveInt(c, label) {
2381
- if (c.pos >= c.bytes.length) {
2382
- throw new Error(`parse: end of script at ${label}`);
2383
- }
2384
- const opcode = c.bytes[c.pos];
2385
- if (opcode >= OP_1 && opcode <= 0x60) {
2386
- c.pos += 1;
2387
- return BigInt(opcode - OP_1 + 1);
2388
- }
2389
- const data = readPush(c, label);
2390
- return decodeScriptNum(data, label);
2391
- }
2392
- /**
2393
- * Read a 1-byte selector as an UNSIGNED 8-bit integer (0..255). Accepts
2394
- * two on-wire encodings, because old vs new covenant builders differ:
2395
- * - `OP_1..OP_16` shorthand (single opcode) → values 1..16.
2396
- * - `0x01 <byte>` raw 1-byte push → any value 1..255.
2397
- *
2398
- * Values 0x80..0xff MUST use the raw-push form; the CScriptNum encoding
2399
- * would need a 0x00 padding byte and become 2 bytes on-stack, which
2400
- * consensus `OP_TXHASH` rejects. The builder in `script-pq.ts` emits the
2401
- * raw-push form unconditionally; the parser stays lenient so covenants
2402
- * built by older tools (using OP_N for small values) still round-trip.
2403
- */
2404
- function readPushUint8(c, label) {
2405
- if (c.pos >= c.bytes.length) {
2406
- throw new Error(`parse: end of script at ${label}`);
2407
- }
2408
- const opcode = c.bytes[c.pos];
2409
- if (opcode >= OP_1 && opcode <= 0x60) {
2410
- c.pos += 1;
2411
- return opcode - OP_1 + 1;
2412
- }
2413
- const data = readPush(c, label);
2414
- if (data.length !== 1) {
2415
- throw new Error(`parse: ${label} must be a single-byte push, got ${data.length} bytes`);
2416
- }
2417
- return data[0];
2418
- }
2419
-
2420
2540
  /**
2421
2541
  * Parser for the Partial-Fill Sell Order covenant (three-branch).
2422
2542
  *
@@ -2450,6 +2570,7 @@ var NeuraiScriptsBundle = (function (exports) {
2450
2570
  expectByte(c, OP_ELSE, 'OP_ELSE (outer → fill)');
2451
2571
  // ═════ Inner IF — Full-fill branch ═════
2452
2572
  expectByte(c, OP_IF, 'OP_IF (inner full-fill)');
2573
+ const expirationFull = readOptionalExpirationGate(c, OP_0, 'full');
2453
2574
  // N = inputAmount
2454
2575
  expectByte(c, OP_0, 'OP_0 (input idx, full)');
2455
2576
  expectByte(c, OP_2, 'OP_2 (AMOUNT sel, full)');
@@ -2491,6 +2612,7 @@ var NeuraiScriptsBundle = (function (exports) {
2491
2612
  expectByte(c, OP_1, 'OP_1 (true, full)');
2492
2613
  expectByte(c, OP_ELSE, 'OP_ELSE (inner → partial fill)');
2493
2614
  // ═════ Inner ELSE — Partial-fill branch ═════
2615
+ const expirationPartial = readOptionalExpirationGate(c, OP_DUP, 'partial');
2494
2616
  // Payment value
2495
2617
  expectByte(c, OP_DUP, 'OP_DUP (price, partial)');
2496
2618
  const unitPriceSatsPartial = readPushPositiveInt(c, 'unitPriceSats (partial)');
@@ -2561,12 +2683,14 @@ var NeuraiScriptsBundle = (function (exports) {
2561
2683
  if (unitPriceSatsFull !== unitPriceSatsPartial) {
2562
2684
  throw new Error('parse: unitPriceSats differs between full-fill and partial-fill branches');
2563
2685
  }
2686
+ assertSameExpiration(expirationFull, expirationPartial, 'full-fill and partial-fill branches');
2564
2687
  const tokenId = new TextDecoder('utf-8', { fatal: true }).decode(tokenIdFull);
2565
2688
  return {
2566
2689
  network,
2567
2690
  sellerPubKeyHash,
2568
2691
  unitPriceSats: unitPriceSatsFull,
2569
2692
  tokenId,
2693
+ expiration: expirationFull,
2570
2694
  scriptHex: bytesToHex(bytes)
2571
2695
  };
2572
2696
  }
@@ -2616,6 +2740,7 @@ var NeuraiScriptsBundle = (function (exports) {
2616
2740
  expectByte(c, OP_ELSE, 'OP_ELSE (outer → fill)');
2617
2741
  // ═════ Inner IF — Full-fill branch ═════
2618
2742
  expectByte(c, OP_IF, 'OP_IF (inner full-fill)');
2743
+ const expirationFull = readOptionalExpirationGate(c, OP_0, 'full');
2619
2744
  expectByte(c, OP_0, 'OP_0 (input idx, full)');
2620
2745
  expectByte(c, OP_2, 'OP_2 (AMOUNT sel, full)');
2621
2746
  expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD (full)');
@@ -2645,6 +2770,7 @@ var NeuraiScriptsBundle = (function (exports) {
2645
2770
  expectByte(c, OP_1, 'OP_1 (true, full)');
2646
2771
  expectByte(c, OP_ELSE, 'OP_ELSE (inner → partial fill)');
2647
2772
  // ═════ Inner ELSE — Partial-fill branch ═════
2773
+ const expirationPartial = readOptionalExpirationGate(c, OP_DUP, 'partial');
2648
2774
  expectByte(c, OP_DUP, 'OP_DUP (price, partial)');
2649
2775
  const unitPriceSatsPartial = readPushPositiveInt(c, 'unitPriceSats (partial)');
2650
2776
  expectByte(c, OP_MUL, 'OP_MUL (partial)');
@@ -2706,6 +2832,7 @@ var NeuraiScriptsBundle = (function (exports) {
2706
2832
  if (unitPriceSatsFull !== unitPriceSatsPartial) {
2707
2833
  throw new Error('parse-pq: unitPriceSats differs between full-fill and partial-fill branches');
2708
2834
  }
2835
+ assertSameExpiration(expirationFull, expirationPartial, 'full-fill and partial-fill branches');
2709
2836
  const tokenId = new TextDecoder('utf-8', { fatal: true }).decode(tokenIdFull);
2710
2837
  return {
2711
2838
  network,
@@ -2713,6 +2840,7 @@ var NeuraiScriptsBundle = (function (exports) {
2713
2840
  tokenId,
2714
2841
  unitPriceSats: unitPriceSatsFull,
2715
2842
  txHashSelector,
2843
+ expiration: expirationFull,
2716
2844
  paymentScriptPubKey: paymentScriptPubKeyFull,
2717
2845
  scriptHex: bytesToHex(bytes)
2718
2846
  };