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