@neuraiproject/neurai-scripts 0.1.1 → 0.3.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.
@@ -33,3 +33,16 @@ export declare function decodeScriptNum(data: Uint8Array, label: string): bigint
33
33
  * only for values that are strictly positive (prices, selectors, indices).
34
34
  */
35
35
  export declare function readPushPositiveInt(c: Cursor, label: string): bigint;
36
+ /**
37
+ * Read a 1-byte selector as an UNSIGNED 8-bit integer (0..255). Accepts
38
+ * two on-wire encodings, because old vs new covenant builders differ:
39
+ * - `OP_1..OP_16` shorthand (single opcode) → values 1..16.
40
+ * - `0x01 <byte>` raw 1-byte push → any value 1..255.
41
+ *
42
+ * Values 0x80..0xff MUST use the raw-push form; the CScriptNum encoding
43
+ * would need a 0x00 padding byte and become 2 bytes on-stack, which
44
+ * consensus `OP_TXHASH` rejects. The builder in `script-pq.ts` emits the
45
+ * raw-push form unconditionally; the parser stays lenient so covenants
46
+ * built by older tools (using OP_N for small values) still round-trip.
47
+ */
48
+ export declare function readPushUint8(c: Cursor, label: string): number;
package/dist/index.cjs CHANGED
@@ -1541,6 +1541,204 @@ function encodeSellerScriptPubKey(address) {
1541
1541
  throw new Error(`Unsupported seller address type for "${address}"`);
1542
1542
  }
1543
1543
 
1544
+ /**
1545
+ * Asset-transfer wrapper split helper.
1546
+ *
1547
+ * Neurai asset UTXOs have a scriptPubKey of the form
1548
+ *
1549
+ * <prefix scriptPubKey bytes> OP_XNA_ASSET <pushdata(payload)> OP_DROP
1550
+ *
1551
+ * where `prefix` is the recipient's standard script (typically a P2PKH, an
1552
+ * AuthScript witness v1, or a bare covenant such as the partial-fill sell
1553
+ * order), and `payload` serializes a `CAssetTransfer`:
1554
+ *
1555
+ * payload = rvn_prefix (0x72 0x76 0x6e) || type_marker (0x74 transfer)
1556
+ * || VarStr(assetName)
1557
+ * || int64LE(amountRaw)
1558
+ * [ || messageRef (optional) || int64LE(expireTime) (optional) ]
1559
+ *
1560
+ * This helper separates the two halves so consumers can validate the prefix
1561
+ * (e.g. feed it to `parsePartialFillScript`) while independently reading the
1562
+ * asset data displayed to the user. The optional payload tail
1563
+ * (`message` + `expireTime`) is tolerated but not exposed — the first
1564
+ * version only needs `assetName` and `amountRaw`.
1565
+ *
1566
+ * Bare (non-wrapped) scriptPubKeys round-trip through this helper by
1567
+ * returning `prefixHex === input` and `assetTransfer === null`.
1568
+ */
1569
+ const RVN_MAGIC = Uint8Array.from([0x72, 0x76, 0x6e]); // "rvn"
1570
+ const TRANSFER_TYPE = 0x74;
1571
+ /**
1572
+ * Walk the script one opcode at a time, skipping pushdata payload bytes,
1573
+ * until either OP_XNA_ASSET is reached at top level or the end of the
1574
+ * script. Returns the byte offset of OP_XNA_ASSET, or -1 if not found.
1575
+ * Throws on truncated pushdata.
1576
+ */
1577
+ function findTopLevelAssetOpcode(bytes) {
1578
+ let i = 0;
1579
+ while (i < bytes.length) {
1580
+ const op = bytes[i];
1581
+ if (op === OP_XNA_ASSET)
1582
+ return i;
1583
+ // Short direct push: 0x01..0x4b
1584
+ if (op >= 0x01 && op <= 0x4b) {
1585
+ const len = op;
1586
+ const next = i + 1 + len;
1587
+ if (next > bytes.length) {
1588
+ throw new Error(`splitAssetWrappedScriptPubKey: short push of ${len} bytes at offset ${i} exceeds script length`);
1589
+ }
1590
+ i = next;
1591
+ continue;
1592
+ }
1593
+ if (op === OP_PUSHDATA1) {
1594
+ if (i + 1 >= bytes.length) {
1595
+ throw new Error(`splitAssetWrappedScriptPubKey: truncated PUSHDATA1 length at offset ${i}`);
1596
+ }
1597
+ const len = bytes[i + 1];
1598
+ const next = i + 2 + len;
1599
+ if (next > bytes.length) {
1600
+ throw new Error(`splitAssetWrappedScriptPubKey: PUSHDATA1 of ${len} bytes at offset ${i} exceeds script length`);
1601
+ }
1602
+ i = next;
1603
+ continue;
1604
+ }
1605
+ if (op === OP_PUSHDATA2) {
1606
+ if (i + 2 >= bytes.length) {
1607
+ throw new Error(`splitAssetWrappedScriptPubKey: truncated PUSHDATA2 length at offset ${i}`);
1608
+ }
1609
+ const len = bytes[i + 1] | (bytes[i + 2] << 8);
1610
+ const next = i + 3 + len;
1611
+ if (next > bytes.length) {
1612
+ throw new Error(`splitAssetWrappedScriptPubKey: PUSHDATA2 of ${len} bytes at offset ${i} exceeds script length`);
1613
+ }
1614
+ i = next;
1615
+ continue;
1616
+ }
1617
+ if (op === OP_PUSHDATA4) {
1618
+ if (i + 4 >= bytes.length) {
1619
+ throw new Error(`splitAssetWrappedScriptPubKey: truncated PUSHDATA4 length at offset ${i}`);
1620
+ }
1621
+ const len = (bytes[i + 1] |
1622
+ (bytes[i + 2] << 8) |
1623
+ (bytes[i + 3] << 16) |
1624
+ (bytes[i + 4] << 24)) >>>
1625
+ 0;
1626
+ const next = i + 5 + len;
1627
+ if (next > bytes.length) {
1628
+ throw new Error(`splitAssetWrappedScriptPubKey: PUSHDATA4 of ${len} bytes at offset ${i} exceeds script length`);
1629
+ }
1630
+ i = next;
1631
+ continue;
1632
+ }
1633
+ // Any other opcode (including OP_1..OP_16, OP_DUP, OP_HASH160, etc.) is
1634
+ // one byte wide in Neurai Script. Advance.
1635
+ i += 1;
1636
+ }
1637
+ return -1;
1638
+ }
1639
+ /**
1640
+ * Read the pushdata element that sits immediately after OP_XNA_ASSET and
1641
+ * return its payload bytes together with the cursor position after the
1642
+ * element. Only direct pushes (1..75) and PUSHDATA1 are accepted — a
1643
+ * well-formed asset transfer payload fits within 75 bytes for the common
1644
+ * case and comfortably within 255 bytes even with long names and tails.
1645
+ * PUSHDATA2 and PUSHDATA4 would signal a malformed or adversarial wrapper.
1646
+ */
1647
+ function readPayloadPush(bytes, start) {
1648
+ if (start >= bytes.length) {
1649
+ throw new Error('splitAssetWrappedScriptPubKey: truncated wrapper — missing payload push');
1650
+ }
1651
+ const op = bytes[start];
1652
+ if (op >= 0x01 && op <= 0x4b) {
1653
+ const len = op;
1654
+ const dataStart = start + 1;
1655
+ const dataEnd = dataStart + len;
1656
+ if (dataEnd > bytes.length) {
1657
+ throw new Error(`splitAssetWrappedScriptPubKey: asset payload short push of ${len} bytes exceeds script length`);
1658
+ }
1659
+ return { payload: bytes.slice(dataStart, dataEnd), after: dataEnd };
1660
+ }
1661
+ if (op === OP_PUSHDATA1) {
1662
+ if (start + 1 >= bytes.length) {
1663
+ throw new Error('splitAssetWrappedScriptPubKey: truncated PUSHDATA1 in asset payload');
1664
+ }
1665
+ const len = bytes[start + 1];
1666
+ const dataStart = start + 2;
1667
+ const dataEnd = dataStart + len;
1668
+ if (dataEnd > bytes.length) {
1669
+ throw new Error(`splitAssetWrappedScriptPubKey: asset payload PUSHDATA1 of ${len} bytes exceeds script length`);
1670
+ }
1671
+ return { payload: bytes.slice(dataStart, dataEnd), after: dataEnd };
1672
+ }
1673
+ throw new Error(`splitAssetWrappedScriptPubKey: asset payload push opcode 0x${op.toString(16)} not accepted (expected 0x01..0x4b or PUSHDATA1)`);
1674
+ }
1675
+ function parseAssetTransferPayload(payload) {
1676
+ if (payload.length < 4 + 1 + 8) {
1677
+ // 4 magic+type, 1 varstr length, 8 int64LE amount
1678
+ throw new Error(`splitAssetWrappedScriptPubKey: asset payload of ${payload.length} bytes is too short`);
1679
+ }
1680
+ for (let i = 0; i < 3; i += 1) {
1681
+ if (payload[i] !== RVN_MAGIC[i]) {
1682
+ throw new Error(`splitAssetWrappedScriptPubKey: asset payload magic mismatch — expected "rvn" got 0x${payload[0].toString(16)} 0x${payload[1].toString(16)} 0x${payload[2].toString(16)}`);
1683
+ }
1684
+ }
1685
+ if (payload[3] !== TRANSFER_TYPE) {
1686
+ throw new Error(`splitAssetWrappedScriptPubKey: asset payload type marker 0x${payload[3].toString(16)} is not a transfer (0x74)`);
1687
+ }
1688
+ const nameLen = payload[4];
1689
+ const nameStart = 5;
1690
+ const nameEnd = nameStart + nameLen;
1691
+ if (nameEnd + 8 > payload.length) {
1692
+ throw new Error(`splitAssetWrappedScriptPubKey: asset payload truncated — name length ${nameLen} does not leave room for amount`);
1693
+ }
1694
+ let assetName = '';
1695
+ for (let i = nameStart; i < nameEnd; i += 1) {
1696
+ assetName += String.fromCharCode(payload[i]);
1697
+ }
1698
+ let amountRaw = 0n;
1699
+ for (let i = 0; i < 8; i += 1) {
1700
+ amountRaw |= BigInt(payload[nameEnd + i]) << BigInt(8 * i);
1701
+ }
1702
+ // Any bytes after nameEnd + 8 form the optional tail (message +
1703
+ // expireTime). We intentionally ignore them in this first version; the
1704
+ // raw payload remains available via `payloadHex` if a consumer later
1705
+ // needs to inspect them.
1706
+ return { assetName, amountRaw };
1707
+ }
1708
+ /**
1709
+ * Parse an asset-transfer-wrapped scriptPubKey. Accepts both wrapped and
1710
+ * bare forms. Throws on structural malformation (truncated pushdata,
1711
+ * missing OP_DROP after payload, bad magic, unsupported pushdata width).
1712
+ */
1713
+ function splitAssetWrappedScriptPubKey(spkHex) {
1714
+ const normalized = ensureHex(spkHex, 'scriptPubKey');
1715
+ const bytes = hexToBytes(normalized);
1716
+ const assetOpAt = findTopLevelAssetOpcode(bytes);
1717
+ if (assetOpAt < 0) {
1718
+ return { prefixHex: normalized, assetTransfer: null };
1719
+ }
1720
+ const prefix = bytes.slice(0, assetOpAt);
1721
+ const { payload, after } = readPayloadPush(bytes, assetOpAt + 1);
1722
+ if (after >= bytes.length) {
1723
+ throw new Error('splitAssetWrappedScriptPubKey: asset wrapper missing trailing OP_DROP');
1724
+ }
1725
+ if (bytes[after] !== OP_DROP) {
1726
+ throw new Error(`splitAssetWrappedScriptPubKey: expected OP_DROP at offset ${after}, got 0x${bytes[after].toString(16)}`);
1727
+ }
1728
+ if (after + 1 !== bytes.length) {
1729
+ throw new Error(`splitAssetWrappedScriptPubKey: ${bytes.length - after - 1} trailing bytes after OP_DROP`);
1730
+ }
1731
+ const { assetName, amountRaw } = parseAssetTransferPayload(payload);
1732
+ return {
1733
+ prefixHex: bytesToHex(prefix),
1734
+ assetTransfer: {
1735
+ assetName,
1736
+ amountRaw,
1737
+ payloadHex: bytesToHex(payload),
1738
+ },
1739
+ };
1740
+ }
1741
+
1544
1742
  /**
1545
1743
  * Partial-Fill Sell Order covenant script.
1546
1744
  *
@@ -1767,12 +1965,19 @@ function buildPartialFillScriptPQ(params) {
1767
1965
  // ───────── Cancel branch (PQ via OP_CHECKSIGFROMSTACK) ─────────
1768
1966
  // scriptSig expected: <sigPQ> <pubKeyPQ> OP_1
1769
1967
  // After OP_IF consumes the flag: [ sig, pubKey ]
1968
+ //
1969
+ // The selector MUST be pushed as a raw 1-byte element — consensus
1970
+ // (`interpreter.cpp` OP_TXHASH case) rejects any stack item of
1971
+ // size ≠ 1. Using `pushInt(selector)` would work for 1..127 but emit a
1972
+ // 2-byte CScriptNum for 0x80..0xff (the sign-disambiguation pad), which
1973
+ // makes OP_TXHASH fail with SCRIPT_ERR_TXHASH. See
1974
+ // `memory/project_covenant_v3_findings.md` bug B for details.
1770
1975
  b.op(OP_IF)
1771
1976
  .op(OP_DUP) // [ sig, pubKey, pubKey ]
1772
1977
  .op(OP_SHA256) // [ sig, pubKey, H(pubKey) ]
1773
1978
  .pushBytes(pubKeyCommitment) // [ sig, pubKey, H(pubKey), commitment ]
1774
1979
  .op(OP_EQUALVERIFY) // [ sig, pubKey ]
1775
- .pushInt(txHashSelector) // [ sig, pubKey, selector ]
1980
+ .pushBytes(Uint8Array.of(txHashSelector)) // [ sig, pubKey, selector ] — always 1-byte stack item
1776
1981
  .op(OP_TXHASH) // [ sig, pubKey, txHash ]
1777
1982
  .op(OP_SWAP) // [ sig, txHash, pubKey ]
1778
1983
  .op(OP_CHECKSIGFROMSTACK) // [ 1 | 0 ]
@@ -2067,6 +2272,33 @@ function readPushPositiveInt(c, label) {
2067
2272
  const data = readPush(c, label);
2068
2273
  return decodeScriptNum(data, label);
2069
2274
  }
2275
+ /**
2276
+ * Read a 1-byte selector as an UNSIGNED 8-bit integer (0..255). Accepts
2277
+ * two on-wire encodings, because old vs new covenant builders differ:
2278
+ * - `OP_1..OP_16` shorthand (single opcode) → values 1..16.
2279
+ * - `0x01 <byte>` raw 1-byte push → any value 1..255.
2280
+ *
2281
+ * Values 0x80..0xff MUST use the raw-push form; the CScriptNum encoding
2282
+ * would need a 0x00 padding byte and become 2 bytes on-stack, which
2283
+ * consensus `OP_TXHASH` rejects. The builder in `script-pq.ts` emits the
2284
+ * raw-push form unconditionally; the parser stays lenient so covenants
2285
+ * built by older tools (using OP_N for small values) still round-trip.
2286
+ */
2287
+ function readPushUint8(c, label) {
2288
+ if (c.pos >= c.bytes.length) {
2289
+ throw new Error(`parse: end of script at ${label}`);
2290
+ }
2291
+ const opcode = c.bytes[c.pos];
2292
+ if (opcode >= OP_1 && opcode <= 0x60) {
2293
+ c.pos += 1;
2294
+ return opcode - OP_1 + 1;
2295
+ }
2296
+ const data = readPush(c, label);
2297
+ if (data.length !== 1) {
2298
+ throw new Error(`parse: ${label} must be a single-byte push, got ${data.length} bytes`);
2299
+ }
2300
+ return data[0];
2301
+ }
2070
2302
 
2071
2303
  /**
2072
2304
  * Parser for the Partial-Fill Sell Order covenant.
@@ -2200,11 +2432,13 @@ function parsePartialFillScriptPQ(script, network = 'xna-test') {
2200
2432
  throw new Error(`parse-pq: pubKeyCommitment must be 32 bytes, got ${pubKeyCommitment.length}`);
2201
2433
  }
2202
2434
  expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (cancel)');
2203
- const txHashSelectorBig = readPushPositiveInt(c, 'txHashSelector');
2204
- if (txHashSelectorBig < 1n || txHashSelectorBig > 0xffn) {
2205
- throw new Error(`parse-pq: txHashSelector out of range (${txHashSelectorBig})`);
2435
+ // Selector is read as an unsigned byte — consensus OP_TXHASH treats the
2436
+ // on-stack element as uint8, and the builder emits a raw 1-byte push so
2437
+ // selectors 0x80..0xff round-trip correctly (plan v3 bug B).
2438
+ const txHashSelector = readPushUint8(c, 'txHashSelector');
2439
+ if (txHashSelector < 1) {
2440
+ throw new Error(`parse-pq: txHashSelector 0x00 is rejected by OP_TXHASH`);
2206
2441
  }
2207
- const txHashSelector = Number(txHashSelectorBig);
2208
2442
  expectByte(c, OP_TXHASH, 'OP_TXHASH');
2209
2443
  expectByte(c, OP_SWAP, 'OP_SWAP');
2210
2444
  expectByte(c, OP_CHECKSIGFROMSTACK, 'OP_CHECKSIGFROMSTACK');
@@ -2315,4 +2549,5 @@ exports.parsePartialFillScriptPQ = parsePartialFillScriptPQ;
2315
2549
  exports.pushBytes = pushBytes;
2316
2550
  exports.pushHex = pushHex;
2317
2551
  exports.pushInt = pushInt;
2552
+ exports.splitAssetWrappedScriptPubKey = splitAssetWrappedScriptPubKey;
2318
2553
  //# sourceMappingURL=index.cjs.map