@neuraiproject/neurai-scripts 0.8.1 → 0.9.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.
@@ -1,9 +1,3 @@
1
- /**
2
- * Low-level Script assembler. Emits the exact byte layout expected by the
3
- * Neurai interpreter: pushdata prefixes follow the same rules as Bitcoin
4
- * (direct push for 1..75 bytes, OP_PUSHDATA1/2/4 otherwise), and integers
5
- * are minimally-encoded as CScriptNum.
6
- */
7
1
  /**
8
2
  * Minimal CScriptNum encoding (Bitcoin consensus rules).
9
3
  *
package/dist/index.cjs CHANGED
@@ -43,6 +43,18 @@ function bytesEqual(a, b) {
43
43
  return true;
44
44
  }
45
45
 
46
+ /** Exact monetary primitives. This module has no runtime dependencies. */
47
+ /** Normalize a raw integer without preserving an already rounded number. */
48
+ function toRawInteger(value, label = 'amount') {
49
+ if (typeof value === 'bigint')
50
+ return value;
51
+ if (typeof value === 'number' && Number.isSafeInteger(value))
52
+ return BigInt(value);
53
+ if (typeof value === 'string' && /^-?\d+$/.test(value) && value.length <= 100)
54
+ return BigInt(value);
55
+ throw new Error(`${label}: expected an exact integer; use bigint or an integer string for large values`);
56
+ }
57
+
46
58
  /**
47
59
  * Opcode constants for Neurai Script.
48
60
  *
@@ -414,12 +426,6 @@ var opcodes = /*#__PURE__*/Object.freeze({
414
426
  TXHASH_VERSION: TXHASH_VERSION
415
427
  });
416
428
 
417
- /**
418
- * Low-level Script assembler. Emits the exact byte layout expected by the
419
- * Neurai interpreter: pushdata prefixes follow the same rules as Bitcoin
420
- * (direct push for 1..75 bytes, OP_PUSHDATA1/2/4 otherwise), and integers
421
- * are minimally-encoded as CScriptNum.
422
- */
423
429
  /**
424
430
  * Minimal CScriptNum encoding (Bitcoin consensus rules).
425
431
  *
@@ -429,7 +435,7 @@ var opcodes = /*#__PURE__*/Object.freeze({
429
435
  * - otherwise: sign-magnitude little-endian, with a sign bit on the last byte
430
436
  */
431
437
  function encodeScriptNum(value) {
432
- let n = typeof value === 'bigint' ? value : BigInt(value);
438
+ let n = toRawInteger(value, 'ScriptNum');
433
439
  if (n === 0n)
434
440
  return new Uint8Array();
435
441
  const negative = n < 0n;
@@ -483,7 +489,7 @@ function pushBytes(data) {
483
489
  * when available to match how the node's own templates look on the wire.
484
490
  */
485
491
  function pushInt(value) {
486
- const n = typeof value === 'bigint' ? value : BigInt(value);
492
+ const n = toRawInteger(value, 'ScriptNum');
487
493
  if (n === -1n)
488
494
  return Uint8Array.of(OP_1NEGATE);
489
495
  if (n === 0n)
@@ -573,10 +579,17 @@ function encodeP2WSHScriptPubKey(witnessScriptSha256) {
573
579
  }
574
580
 
575
581
  /**
576
- * AuthScript (witness v1) scriptPubKey + witness-stack builders.
582
+ * AuthScript scriptPubKey + witness-stack builders.
577
583
  *
578
- * AuthScript outputs encode a 32-byte commitment in a witness v1 program:
579
- * scriptPubKey = OP_1 0x20 <32-byte program>
584
+ * AuthScript outputs encode a 32-byte commitment in a witness program:
585
+ * scriptPubKey = OP_n 0x20 <32-byte program>
586
+ *
587
+ * OP_1 generic AuthScript v1 (nc1p… / tnc1p…): any auth type, any witnessScript
588
+ * OP_2 strict PQ v2 (pq1z… / tpq1z…): auth type 0x01, witnessScript OP_TRUE
589
+ * OP_3 strict ECDSA v3 (nq1r… / tnq1r…): auth type 0x02, witnessScript OP_TRUE
590
+ *
591
+ * The witness version is also the first byte of the commitment preimage:
592
+ * tagged_hash("NeuraiAuthScript", version || auth_descriptor || SHA256(witnessScript))
580
593
  *
581
594
  * The program is `HASH160`/`SHA256` over a descriptor that depends on the
582
595
  * `auth_type` byte carried as the first witness-stack element at spend time.
@@ -603,11 +616,24 @@ const AUTHSCRIPT_LEGACY = 0x02;
603
616
  const AUTHSCRIPT_REF = 0x03;
604
617
  /** Cap for PQ signature / pubkey pushes under NIP-018 (3072 B). */
605
618
  const MAX_PQ_PUSH = 3072;
606
- function encodeAuthScriptScriptPubKey(program) {
619
+ const WITNESS_VERSION_OPCODE = {
620
+ 1: OP_1,
621
+ 2: OP_2,
622
+ 3: OP_3
623
+ };
624
+ /**
625
+ * `OP_n 0x20 <program>` for witness version `n`. Defaults to the generic
626
+ * AuthScript v1 (`OP_1`), which is what every covenant commits to.
627
+ */
628
+ function encodeAuthScriptScriptPubKey(program, witnessVersion = 1) {
607
629
  if (!(program instanceof Uint8Array) || program.length !== 32) {
608
630
  throw new Error('AuthScript program must be a 32-byte Uint8Array');
609
631
  }
610
- return concatBytes(Uint8Array.of(OP_1, 0x20), program);
632
+ const opcode = WITNESS_VERSION_OPCODE[witnessVersion];
633
+ if (opcode === undefined) {
634
+ throw new Error(`AuthScript witness version must be 1, 2 or 3, got ${String(witnessVersion)}`);
635
+ }
636
+ return concatBytes(Uint8Array.of(opcode, 0x20), program);
611
637
  }
612
638
  function assertWitnessScript(ws) {
613
639
  if (!(ws instanceof Uint8Array) || ws.length === 0) {
@@ -679,6 +705,45 @@ function buildAuthScriptWitnessPQ(input) {
679
705
  input.witnessScript
680
706
  ];
681
707
  }
708
+ /** Length of the versioned ML-DSA-44 pubkey the node expects (0x05 prefix + 1312 B). */
709
+ const STRICT_PQ_PUBKEY_LENGTH = 1313;
710
+ /** Version prefix of an ML-DSA-44 pubkey on the witness stack. */
711
+ const PQ_PUBKEY_PREFIX = 0x05;
712
+ /**
713
+ * Witness stack for spending a strict PQ witness v2 output (`pq1z…`):
714
+ * exactly `[0x01, sig, pubKey, OP_TRUE]`. The node rejects any other
715
+ * shape (extra arguments, another witnessScript) for the strict families.
716
+ */
717
+ function buildStrictWitnessPQ(input) {
718
+ if (!(input.signature instanceof Uint8Array) || input.signature.length === 0) {
719
+ throw new Error('signature must be a non-empty Uint8Array');
720
+ }
721
+ if (input.signature.length > MAX_PQ_PUSH) {
722
+ throw new Error(`signature of ${input.signature.length} bytes exceeds MAX_PQ_SCRIPT_ELEMENT_SIZE (${MAX_PQ_PUSH})`);
723
+ }
724
+ if (!(input.pubKey instanceof Uint8Array) ||
725
+ input.pubKey.length !== STRICT_PQ_PUBKEY_LENGTH ||
726
+ input.pubKey[0] !== PQ_PUBKEY_PREFIX) {
727
+ throw new Error(`pubKey must be the ${STRICT_PQ_PUBKEY_LENGTH}-byte versioned ML-DSA-44 key (0x05 prefix)`);
728
+ }
729
+ return [Uint8Array.of(AUTHSCRIPT_PQ), input.signature, input.pubKey, Uint8Array.of(OP_TRUE)];
730
+ }
731
+ /**
732
+ * Witness stack for spending a strict ECDSA witness v3 output (`nq1r…`):
733
+ * exactly `[0x02, sig, pubKey33, OP_TRUE]`. The node rejects uncompressed
734
+ * keys for this family.
735
+ */
736
+ function buildStrictWitnessECDSA(input) {
737
+ if (!(input.signature instanceof Uint8Array) || input.signature.length === 0) {
738
+ throw new Error('signature must be a non-empty Uint8Array');
739
+ }
740
+ if (!(input.pubKey instanceof Uint8Array) ||
741
+ input.pubKey.length !== 33 ||
742
+ (input.pubKey[0] !== 0x02 && input.pubKey[0] !== 0x03)) {
743
+ throw new Error('pubKey must be a compressed (33B) secp256k1 key for strict ECDSA witness v3');
744
+ }
745
+ return [Uint8Array.of(AUTHSCRIPT_LEGACY), input.signature, input.pubKey, Uint8Array.of(OP_TRUE)];
746
+ }
682
747
  /**
683
748
  * Build the witness stack for a NoAuth AuthScript spend. The spend is gated
684
749
  * by the witnessScript alone (covenants, hash-locks, time-locks, ...); no
@@ -800,6 +865,8 @@ function encodeP2SHScriptPubKey(redeemScriptHash160) {
800
865
  return concatBytes(Uint8Array.of(OP_HASH160, 0x14), redeemScriptHash160, Uint8Array.of(OP_EQUAL));
801
866
  }
802
867
 
868
+ /** Exact monetary primitives. This module has no runtime dependencies. */
869
+
803
870
  // base-x encoding / decoding
804
871
  // Copyright (c) 2018 base-x contributors
805
872
  // Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
@@ -1515,37 +1582,96 @@ function resolveAddressInput(address) {
1515
1582
 
1516
1583
  const LEGACY_MAINNET_PREFIX = 53;
1517
1584
  const LEGACY_TESTNET_PREFIX = 127;
1518
- const PQ_MAINNET_HRP = 'nq';
1519
- const PQ_TESTNET_HRP = 'tnq';
1520
- function inferNetworkFromAddress(address) {
1521
- const normalized = resolveAddressInput(address).toLowerCase();
1522
- if (normalized.startsWith(PQ_MAINNET_HRP + '1'))
1523
- return 'xna-pq';
1524
- if (normalized.startsWith(PQ_TESTNET_HRP + '1'))
1525
- return 'xna-pq-test';
1526
- if (normalized.startsWith('n'))
1527
- return 'xna';
1528
- if (normalized.startsWith('t'))
1529
- return 'xna-test';
1530
- throw new Error(`Unsupported Neurai address: ${address}`);
1585
+ const WITNESS_FAMILIES = [
1586
+ {
1587
+ type: 'authscript',
1588
+ witnessVersion: 1,
1589
+ hrp: { mainnet: 'nc', testnet: 'tnc' },
1590
+ network: { mainnet: 'xna-authscript', testnet: 'xna-authscript-test' }
1591
+ },
1592
+ {
1593
+ type: 'pq',
1594
+ witnessVersion: 2,
1595
+ hrp: { mainnet: 'pq', testnet: 'tpq' },
1596
+ network: { mainnet: 'xna-pq', testnet: 'xna-pq-test' }
1597
+ },
1598
+ {
1599
+ type: 'ecdsa',
1600
+ witnessVersion: 3,
1601
+ hrp: { mainnet: 'nq', testnet: 'tnq' },
1602
+ network: { mainnet: 'xna', testnet: 'xna-test' }
1603
+ }
1604
+ ];
1605
+ /** The family that owns `hrp` (lowercase), with the chain it encodes. */
1606
+ function witnessFamilyByHrp(hrp) {
1607
+ for (const family of WITNESS_FAMILIES) {
1608
+ if (family.hrp.mainnet === hrp)
1609
+ return { family, chain: 'mainnet' };
1610
+ if (family.hrp.testnet === hrp)
1611
+ return { family, chain: 'testnet' };
1612
+ }
1613
+ return undefined;
1614
+ }
1615
+ /** The family encoded by `witnessVersion`, or undefined for any other version. */
1616
+ function witnessFamilyByVersion(witnessVersion) {
1617
+ return WITNESS_FAMILIES.find((family) => family.witnessVersion === witnessVersion);
1531
1618
  }
1532
1619
 
1533
- function decodeAddress(address) {
1534
- const normalized = resolveAddressInput(address);
1535
- const lowered = normalized.toLowerCase();
1536
- if (!normalized)
1537
- throw new Error('Address is required');
1538
- if (lowered.startsWith(PQ_MAINNET_HRP + '1') || lowered.startsWith(PQ_TESTNET_HRP + '1')) {
1539
- const decoded = distExports.bech32m.decode(normalized);
1540
- const version = decoded.words[0];
1541
- const program = Uint8Array.from(distExports.bech32m.fromWords(decoded.words.slice(1)));
1542
- if (version !== 1 || program.length !== 32) {
1543
- throw new Error(`Unsupported AuthScript address program for ${address}`);
1544
- }
1545
- const network = lowered.startsWith(PQ_TESTNET_HRP + '1') ? 'xna-pq-test' : 'xna-pq';
1546
- return { address: normalized, type: 'authscript', network, program, commitment: program };
1620
+ // Longest Bech32m string the node's decoder accepts (bech32.cpp).
1621
+ const BECH32M_MAX_LENGTH = 90;
1622
+ const AUTHSCRIPT_PROGRAM_LENGTH = 32;
1623
+ function tryBech32mDecode(address) {
1624
+ try {
1625
+ const { prefix, words } = distExports.bech32m.decode(address, BECH32M_MAX_LENGTH);
1626
+ return { hrp: prefix.toLowerCase(), words };
1627
+ }
1628
+ catch {
1629
+ return null;
1630
+ }
1631
+ }
1632
+ function decodeWitnessAddress(address, parts) {
1633
+ const owner = witnessFamilyByHrp(parts.hrp);
1634
+ if (!owner) {
1635
+ throw new Error(`Unsupported Bech32m prefix "${parts.hrp}" for ${address}`);
1636
+ }
1637
+ if (parts.words.length === 0) {
1638
+ throw new Error(`Empty witness program in ${address}`);
1639
+ }
1640
+ const version = parts.words[0];
1641
+ const { family, chain } = owner;
1642
+ if (version !== family.witnessVersion) {
1643
+ const actual = witnessFamilyByVersion(version);
1644
+ const hint = actual
1645
+ ? `; witness v${version} addresses use the "${actual.hrp[chain]}" prefix`
1646
+ : '';
1647
+ const legacyHint = family.type === 'ecdsa' && version === 1
1648
+ ? ' Generic AuthScript v1 addresses are now encoded as nc1p… / tnc1p… ' +
1649
+ '(same scriptPubKey): regenerate the address (neurai-key xna-authscript networks).'
1650
+ : '';
1651
+ throw new Error(`Address ${address}: the "${parts.hrp}" prefix only encodes witness v${family.witnessVersion}, ` +
1652
+ `not v${version}${hint}.${legacyHint}`);
1653
+ }
1654
+ let program;
1655
+ try {
1656
+ program = Uint8Array.from(distExports.bech32m.fromWords(parts.words.slice(1)));
1657
+ }
1658
+ catch {
1659
+ throw new Error(`Invalid witness program padding in ${address}`);
1660
+ }
1661
+ if (program.length !== AUTHSCRIPT_PROGRAM_LENGTH) {
1662
+ throw new Error(`Unsupported AuthScript program length ${program.length} for ${address} (expected ${AUTHSCRIPT_PROGRAM_LENGTH})`);
1547
1663
  }
1548
- const payload = Uint8Array.from(bs58check.decode(normalized));
1664
+ return {
1665
+ address,
1666
+ type: family.type,
1667
+ witnessVersion: family.witnessVersion,
1668
+ network: family.network[chain],
1669
+ program,
1670
+ commitment: program
1671
+ };
1672
+ }
1673
+ function decodeLegacyAddress(address) {
1674
+ const payload = Uint8Array.from(bs58check.decode(address));
1549
1675
  if (payload.length !== 21) {
1550
1676
  throw new Error(`Unsupported legacy address payload length for ${address}`);
1551
1677
  }
@@ -1554,13 +1680,51 @@ function decodeAddress(address) {
1554
1680
  throw new Error(`Unsupported legacy address prefix ${prefix} for ${address}`);
1555
1681
  }
1556
1682
  return {
1557
- address: normalized,
1683
+ address,
1558
1684
  type: 'p2pkh',
1559
- network: inferNetworkFromAddress(normalized),
1685
+ network: prefix === LEGACY_MAINNET_PREFIX ? 'xna-legacy' : 'xna-legacy-test',
1560
1686
  program: payload.slice(1),
1561
1687
  hash: payload.slice(1)
1562
1688
  };
1563
1689
  }
1690
+ /**
1691
+ * Decode a Neurai address the way the node does (base58.cpp
1692
+ * `DecodeDestination`): Bech32m first, Base58Check otherwise.
1693
+ *
1694
+ * - Base58 P2PKH → `type: 'p2pkh'`, network `xna-legacy` / `xna-legacy-test`
1695
+ * (an `xna-old-legacy` address is indistinguishable and reports
1696
+ * `xna-legacy`).
1697
+ * - Bech32m → `authscript` (v1, `nc`/`tnc`), `pq` (v2, `pq`/`tpq`) or
1698
+ * `ecdsa` (v3, `nq`/`tnq`), with `witnessVersion` and the 32-byte
1699
+ * commitment. Any other HRP/version pair is rejected, including the old
1700
+ * `nq1p…` / `tnq1p…` encoding of generic AuthScript v1.
1701
+ *
1702
+ * The decoder does not know whether a witness family is active on the
1703
+ * target chain: before activation the node refuses v2/v3 addresses and a
1704
+ * witness output is anyone-can-spend.
1705
+ */
1706
+ function decodeAddress(address) {
1707
+ const normalized = resolveAddressInput(address);
1708
+ if (!normalized)
1709
+ throw new Error('Address is required');
1710
+ const bech32mParts = tryBech32mDecode(normalized);
1711
+ if (bech32mParts) {
1712
+ return decodeWitnessAddress(normalized, bech32mParts);
1713
+ }
1714
+ try {
1715
+ return decodeLegacyAddress(normalized);
1716
+ }
1717
+ catch (legacyError) {
1718
+ // Not Base58 either. When the string carries a known Bech32m prefix the
1719
+ // Bech32m failure (bad checksum, mixed case…) is the useful diagnosis.
1720
+ const separator = normalized.lastIndexOf('1');
1721
+ const hrp = separator > 0 ? normalized.slice(0, separator).toLowerCase() : '';
1722
+ if (witnessFamilyByHrp(hrp)) {
1723
+ throw new Error(`Invalid Bech32m address ${normalized} (checksum, case or character error)`);
1724
+ }
1725
+ throw legacyError;
1726
+ }
1727
+ }
1564
1728
 
1565
1729
  /**
1566
1730
  * Address helpers. Wraps `decodeAddress` from
@@ -1568,9 +1732,12 @@ function decodeAddress(address) {
1568
1732
  * scriptPubKey bytes a covenant needs to hardcode. The actual
1569
1733
  * scriptPubKey encoders live in `./standard/*`; this module delegates.
1570
1734
  *
1571
- * Two destination types are supported for the payment output (output[0]):
1572
- * - Legacy P2PKH (base58check)
1573
- * - AuthScript witness v1 (bech32m)
1735
+ * Every Neurai destination type is supported for the payment output
1736
+ * (output[0]):
1737
+ * - Legacy P2PKH (base58check) → `76a914<20>88ac`
1738
+ * - Generic AuthScript witness v1 (nc1p… / tnc1p…) → `5120<32>`
1739
+ * - Strict PQ witness v2 (pq1z… / tpq1z…) → `5220<32>`
1740
+ * - Strict ECDSA witness v3 (nq1r… / tnq1r…) → `5320<32>`
1574
1741
  */
1575
1742
  /**
1576
1743
  * Resolve any accepted seller address string into its scriptPubKey.
@@ -1587,11 +1754,14 @@ function encodeSellerScriptPubKey(address) {
1587
1754
  hash
1588
1755
  };
1589
1756
  }
1590
- if (decoded.type === 'authscript') {
1757
+ if (decoded.type === 'authscript' || decoded.type === 'pq' || decoded.type === 'ecdsa') {
1758
+ // The witness version is part of the destination: a pq1z… / nq1r…
1759
+ // payment must be hardcoded with OP_2 / OP_3, never with OP_1.
1591
1760
  const program = Uint8Array.from(decoded.program);
1592
1761
  return {
1593
- kind: 'authscript',
1594
- bytes: encodeAuthScriptScriptPubKey(program),
1762
+ kind: decoded.type,
1763
+ witnessVersion: decoded.witnessVersion,
1764
+ bytes: encodeAuthScriptScriptPubKey(program, decoded.witnessVersion),
1595
1765
  hash: program
1596
1766
  };
1597
1767
  }
@@ -1606,8 +1776,8 @@ function encodeSellerScriptPubKey(address) {
1606
1776
  * <prefix scriptPubKey bytes> OP_XNA_ASSET <pushdata(payload)> OP_DROP
1607
1777
  *
1608
1778
  * where `prefix` is the recipient's standard script (typically a P2PKH, an
1609
- * AuthScript witness v1, or a bare covenant such as the partial-fill sell
1610
- * order), and `payload` serializes a `CAssetTransfer`:
1779
+ * AuthScript `OP_1`/`OP_2`/`OP_3` witness program, or a bare covenant such
1780
+ * as the partial-fill sell order), and `payload` serializes a `CAssetTransfer`:
1611
1781
  *
1612
1782
  * payload = marker ("rvn" 0x72 0x76 0x6e | "xna" 0x78 0x6e 0x61)
1613
1783
  * || type_marker (0x74 transfer)
@@ -2953,6 +3123,8 @@ exports.AUTHSCRIPT_REF = AUTHSCRIPT_REF;
2953
3123
  exports.DEFAULT_PQ_TXHASH_SELECTOR = DEFAULT_PQ_TXHASH_SELECTOR;
2954
3124
  exports.MULTISIG_MAX_PUBKEYS = MULTISIG_MAX_PUBKEYS;
2955
3125
  exports.NULLDATA_STANDARD_MAX_SIZE = NULLDATA_STANDARD_MAX_SIZE;
3126
+ exports.PQ_PUBKEY_PREFIX = PQ_PUBKEY_PREFIX;
3127
+ exports.STRICT_PQ_PUBKEY_LENGTH = STRICT_PQ_PUBKEY_LENGTH;
2956
3128
  exports.ScriptBuilder = ScriptBuilder;
2957
3129
  exports.buildAuthScriptWitnessLegacy = buildAuthScriptWitnessLegacy;
2958
3130
  exports.buildAuthScriptWitnessNoAuth = buildAuthScriptWitnessNoAuth;
@@ -2971,6 +3143,8 @@ exports.buildPartialFillScript = buildPartialFillScript;
2971
3143
  exports.buildPartialFillScriptHex = buildPartialFillScriptHex;
2972
3144
  exports.buildPartialFillScriptPQ = buildPartialFillScriptPQ;
2973
3145
  exports.buildPartialFillScriptPQHex = buildPartialFillScriptPQHex;
3146
+ exports.buildStrictWitnessECDSA = buildStrictWitnessECDSA;
3147
+ exports.buildStrictWitnessPQ = buildStrictWitnessPQ;
2974
3148
  exports.bytesEqual = bytesEqual;
2975
3149
  exports.bytesToHex = bytesToHex;
2976
3150
  exports.concatBytes = concatBytes;