@neuraiproject/neurai-scripts 0.8.2 → 0.9.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/dist/index.cjs CHANGED
@@ -579,10 +579,17 @@ function encodeP2WSHScriptPubKey(witnessScriptSha256) {
579
579
  }
580
580
 
581
581
  /**
582
- * AuthScript (witness v1) scriptPubKey + witness-stack builders.
582
+ * AuthScript scriptPubKey + witness-stack builders.
583
583
  *
584
- * AuthScript outputs encode a 32-byte commitment in a witness v1 program:
585
- * 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))
586
593
  *
587
594
  * The program is `HASH160`/`SHA256` over a descriptor that depends on the
588
595
  * `auth_type` byte carried as the first witness-stack element at spend time.
@@ -609,11 +616,24 @@ const AUTHSCRIPT_LEGACY = 0x02;
609
616
  const AUTHSCRIPT_REF = 0x03;
610
617
  /** Cap for PQ signature / pubkey pushes under NIP-018 (3072 B). */
611
618
  const MAX_PQ_PUSH = 3072;
612
- 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) {
613
629
  if (!(program instanceof Uint8Array) || program.length !== 32) {
614
630
  throw new Error('AuthScript program must be a 32-byte Uint8Array');
615
631
  }
616
- 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);
617
637
  }
618
638
  function assertWitnessScript(ws) {
619
639
  if (!(ws instanceof Uint8Array) || ws.length === 0) {
@@ -685,6 +705,45 @@ function buildAuthScriptWitnessPQ(input) {
685
705
  input.witnessScript
686
706
  ];
687
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
+ }
688
747
  /**
689
748
  * Build the witness stack for a NoAuth AuthScript spend. The spend is gated
690
749
  * by the witnessScript alone (covenants, hash-locks, time-locks, ...); no
@@ -1523,37 +1582,96 @@ function resolveAddressInput(address) {
1523
1582
 
1524
1583
  const LEGACY_MAINNET_PREFIX = 53;
1525
1584
  const LEGACY_TESTNET_PREFIX = 127;
1526
- const PQ_MAINNET_HRP = 'nq';
1527
- const PQ_TESTNET_HRP = 'tnq';
1528
- function inferNetworkFromAddress(address) {
1529
- const normalized = resolveAddressInput(address).toLowerCase();
1530
- if (normalized.startsWith(PQ_MAINNET_HRP + '1'))
1531
- return 'xna-pq';
1532
- if (normalized.startsWith(PQ_TESTNET_HRP + '1'))
1533
- return 'xna-pq-test';
1534
- if (normalized.startsWith('n'))
1535
- return 'xna';
1536
- if (normalized.startsWith('t'))
1537
- return 'xna-test';
1538
- 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);
1539
1618
  }
1540
1619
 
1541
- function decodeAddress(address) {
1542
- const normalized = resolveAddressInput(address);
1543
- const lowered = normalized.toLowerCase();
1544
- if (!normalized)
1545
- throw new Error('Address is required');
1546
- if (lowered.startsWith(PQ_MAINNET_HRP + '1') || lowered.startsWith(PQ_TESTNET_HRP + '1')) {
1547
- const decoded = distExports.bech32m.decode(normalized);
1548
- const version = decoded.words[0];
1549
- const program = Uint8Array.from(distExports.bech32m.fromWords(decoded.words.slice(1)));
1550
- if (version !== 1 || program.length !== 32) {
1551
- throw new Error(`Unsupported AuthScript address program for ${address}`);
1552
- }
1553
- const network = lowered.startsWith(PQ_TESTNET_HRP + '1') ? 'xna-pq-test' : 'xna-pq';
1554
- 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})`);
1555
1663
  }
1556
- 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));
1557
1675
  if (payload.length !== 21) {
1558
1676
  throw new Error(`Unsupported legacy address payload length for ${address}`);
1559
1677
  }
@@ -1562,13 +1680,51 @@ function decodeAddress(address) {
1562
1680
  throw new Error(`Unsupported legacy address prefix ${prefix} for ${address}`);
1563
1681
  }
1564
1682
  return {
1565
- address: normalized,
1683
+ address,
1566
1684
  type: 'p2pkh',
1567
- network: inferNetworkFromAddress(normalized),
1685
+ network: prefix === LEGACY_MAINNET_PREFIX ? 'xna-legacy' : 'xna-legacy-test',
1568
1686
  program: payload.slice(1),
1569
1687
  hash: payload.slice(1)
1570
1688
  };
1571
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
+ }
1572
1728
 
1573
1729
  /**
1574
1730
  * Address helpers. Wraps `decodeAddress` from
@@ -1576,9 +1732,12 @@ function decodeAddress(address) {
1576
1732
  * scriptPubKey bytes a covenant needs to hardcode. The actual
1577
1733
  * scriptPubKey encoders live in `./standard/*`; this module delegates.
1578
1734
  *
1579
- * Two destination types are supported for the payment output (output[0]):
1580
- * - Legacy P2PKH (base58check)
1581
- * - 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>`
1582
1741
  */
1583
1742
  /**
1584
1743
  * Resolve any accepted seller address string into its scriptPubKey.
@@ -1595,11 +1754,14 @@ function encodeSellerScriptPubKey(address) {
1595
1754
  hash
1596
1755
  };
1597
1756
  }
1598
- 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.
1599
1760
  const program = Uint8Array.from(decoded.program);
1600
1761
  return {
1601
- kind: 'authscript',
1602
- bytes: encodeAuthScriptScriptPubKey(program),
1762
+ kind: decoded.type,
1763
+ witnessVersion: decoded.witnessVersion,
1764
+ bytes: encodeAuthScriptScriptPubKey(program, decoded.witnessVersion),
1603
1765
  hash: program
1604
1766
  };
1605
1767
  }
@@ -1614,8 +1776,8 @@ function encodeSellerScriptPubKey(address) {
1614
1776
  * <prefix scriptPubKey bytes> OP_XNA_ASSET <pushdata(payload)> OP_DROP
1615
1777
  *
1616
1778
  * where `prefix` is the recipient's standard script (typically a P2PKH, an
1617
- * AuthScript witness v1, or a bare covenant such as the partial-fill sell
1618
- * 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`:
1619
1781
  *
1620
1782
  * payload = marker ("rvn" 0x72 0x76 0x6e | "xna" 0x78 0x6e 0x61)
1621
1783
  * || type_marker (0x74 transfer)
@@ -2961,6 +3123,8 @@ exports.AUTHSCRIPT_REF = AUTHSCRIPT_REF;
2961
3123
  exports.DEFAULT_PQ_TXHASH_SELECTOR = DEFAULT_PQ_TXHASH_SELECTOR;
2962
3124
  exports.MULTISIG_MAX_PUBKEYS = MULTISIG_MAX_PUBKEYS;
2963
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;
2964
3128
  exports.ScriptBuilder = ScriptBuilder;
2965
3129
  exports.buildAuthScriptWitnessLegacy = buildAuthScriptWitnessLegacy;
2966
3130
  exports.buildAuthScriptWitnessNoAuth = buildAuthScriptWitnessNoAuth;
@@ -2979,6 +3143,8 @@ exports.buildPartialFillScript = buildPartialFillScript;
2979
3143
  exports.buildPartialFillScriptHex = buildPartialFillScriptHex;
2980
3144
  exports.buildPartialFillScriptPQ = buildPartialFillScriptPQ;
2981
3145
  exports.buildPartialFillScriptPQHex = buildPartialFillScriptPQHex;
3146
+ exports.buildStrictWitnessECDSA = buildStrictWitnessECDSA;
3147
+ exports.buildStrictWitnessPQ = buildStrictWitnessPQ;
2982
3148
  exports.bytesEqual = bytesEqual;
2983
3149
  exports.bytesToHex = bytesToHex;
2984
3150
  exports.concatBytes = concatBytes;