@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/address.d.ts CHANGED
@@ -4,15 +4,25 @@
4
4
  * scriptPubKey bytes a covenant needs to hardcode. The actual
5
5
  * scriptPubKey encoders live in `./standard/*`; this module delegates.
6
6
  *
7
- * Two destination types are supported for the payment output (output[0]):
8
- * - Legacy P2PKH (base58check)
9
- * - AuthScript witness v1 (bech32m)
7
+ * Every Neurai destination type is supported for the payment output
8
+ * (output[0]):
9
+ * - Legacy P2PKH (base58check) → `76a914<20>88ac`
10
+ * - Generic AuthScript witness v1 (nc1p… / tnc1p…) → `5120<32>`
11
+ * - Strict PQ witness v2 (pq1z… / tpq1z…) → `5220<32>`
12
+ * - Strict ECDSA witness v3 (nq1r… / tnq1r…) → `5320<32>`
10
13
  */
11
14
  import { encodeP2PKHScriptPubKey } from './standard/p2pkh.js';
12
15
  import { encodeAuthScriptScriptPubKey } from './standard/authscript.js';
13
- export type SellerAddressKind = 'p2pkh' | 'authscript';
16
+ import type { AuthScriptWitnessVersion } from './standard/authscript.js';
17
+ /**
18
+ * `authscript` is the generic witness v1; `pq` and `ecdsa` are the strict
19
+ * witness v2 and v3 families.
20
+ */
21
+ export type SellerAddressKind = 'p2pkh' | 'authscript' | 'pq' | 'ecdsa';
14
22
  export interface SellerScriptPubKey {
15
23
  kind: SellerAddressKind;
24
+ /** Witness version of an AuthScript destination (1, 2 or 3). */
25
+ witnessVersion?: AuthScriptWitnessVersion;
16
26
  /** Raw scriptPubKey bytes that output[0] of a fill tx must equal. */
17
27
  bytes: Uint8Array;
18
28
  /**
@@ -6,8 +6,8 @@
6
6
  * <prefix scriptPubKey bytes> OP_XNA_ASSET <pushdata(payload)> OP_DROP
7
7
  *
8
8
  * where `prefix` is the recipient's standard script (typically a P2PKH, an
9
- * AuthScript witness v1, or a bare covenant such as the partial-fill sell
10
- * order), and `payload` serializes a `CAssetTransfer`:
9
+ * AuthScript `OP_1`/`OP_2`/`OP_3` witness program, or a bare covenant such
10
+ * as the partial-fill sell order), and `payload` serializes a `CAssetTransfer`:
11
11
  *
12
12
  * payload = marker ("rvn" 0x72 0x76 0x6e | "xna" 0x78 0x6e 0x61)
13
13
  * || type_marker (0x74 transfer)
package/dist/browser.js CHANGED
@@ -577,10 +577,17 @@ function encodeP2WSHScriptPubKey(witnessScriptSha256) {
577
577
  }
578
578
 
579
579
  /**
580
- * AuthScript (witness v1) scriptPubKey + witness-stack builders.
580
+ * AuthScript scriptPubKey + witness-stack builders.
581
581
  *
582
- * AuthScript outputs encode a 32-byte commitment in a witness v1 program:
583
- * scriptPubKey = OP_1 0x20 <32-byte program>
582
+ * AuthScript outputs encode a 32-byte commitment in a witness program:
583
+ * scriptPubKey = OP_n 0x20 <32-byte program>
584
+ *
585
+ * OP_1 generic AuthScript v1 (nc1p… / tnc1p…): any auth type, any witnessScript
586
+ * OP_2 strict PQ v2 (pq1z… / tpq1z…): auth type 0x01, witnessScript OP_TRUE
587
+ * OP_3 strict ECDSA v3 (nq1r… / tnq1r…): auth type 0x02, witnessScript OP_TRUE
588
+ *
589
+ * The witness version is also the first byte of the commitment preimage:
590
+ * tagged_hash("NeuraiAuthScript", version || auth_descriptor || SHA256(witnessScript))
584
591
  *
585
592
  * The program is `HASH160`/`SHA256` over a descriptor that depends on the
586
593
  * `auth_type` byte carried as the first witness-stack element at spend time.
@@ -607,11 +614,24 @@ const AUTHSCRIPT_LEGACY = 0x02;
607
614
  const AUTHSCRIPT_REF = 0x03;
608
615
  /** Cap for PQ signature / pubkey pushes under NIP-018 (3072 B). */
609
616
  const MAX_PQ_PUSH = 3072;
610
- function encodeAuthScriptScriptPubKey(program) {
617
+ const WITNESS_VERSION_OPCODE = {
618
+ 1: OP_1,
619
+ 2: OP_2,
620
+ 3: OP_3
621
+ };
622
+ /**
623
+ * `OP_n 0x20 <program>` for witness version `n`. Defaults to the generic
624
+ * AuthScript v1 (`OP_1`), which is what every covenant commits to.
625
+ */
626
+ function encodeAuthScriptScriptPubKey(program, witnessVersion = 1) {
611
627
  if (!(program instanceof Uint8Array) || program.length !== 32) {
612
628
  throw new Error('AuthScript program must be a 32-byte Uint8Array');
613
629
  }
614
- return concatBytes(Uint8Array.of(OP_1, 0x20), program);
630
+ const opcode = WITNESS_VERSION_OPCODE[witnessVersion];
631
+ if (opcode === undefined) {
632
+ throw new Error(`AuthScript witness version must be 1, 2 or 3, got ${String(witnessVersion)}`);
633
+ }
634
+ return concatBytes(Uint8Array.of(opcode, 0x20), program);
615
635
  }
616
636
  function assertWitnessScript(ws) {
617
637
  if (!(ws instanceof Uint8Array) || ws.length === 0) {
@@ -683,6 +703,45 @@ function buildAuthScriptWitnessPQ(input) {
683
703
  input.witnessScript
684
704
  ];
685
705
  }
706
+ /** Length of the versioned ML-DSA-44 pubkey the node expects (0x05 prefix + 1312 B). */
707
+ const STRICT_PQ_PUBKEY_LENGTH = 1313;
708
+ /** Version prefix of an ML-DSA-44 pubkey on the witness stack. */
709
+ const PQ_PUBKEY_PREFIX = 0x05;
710
+ /**
711
+ * Witness stack for spending a strict PQ witness v2 output (`pq1z…`):
712
+ * exactly `[0x01, sig, pubKey, OP_TRUE]`. The node rejects any other
713
+ * shape (extra arguments, another witnessScript) for the strict families.
714
+ */
715
+ function buildStrictWitnessPQ(input) {
716
+ if (!(input.signature instanceof Uint8Array) || input.signature.length === 0) {
717
+ throw new Error('signature must be a non-empty Uint8Array');
718
+ }
719
+ if (input.signature.length > MAX_PQ_PUSH) {
720
+ throw new Error(`signature of ${input.signature.length} bytes exceeds MAX_PQ_SCRIPT_ELEMENT_SIZE (${MAX_PQ_PUSH})`);
721
+ }
722
+ if (!(input.pubKey instanceof Uint8Array) ||
723
+ input.pubKey.length !== STRICT_PQ_PUBKEY_LENGTH ||
724
+ input.pubKey[0] !== PQ_PUBKEY_PREFIX) {
725
+ throw new Error(`pubKey must be the ${STRICT_PQ_PUBKEY_LENGTH}-byte versioned ML-DSA-44 key (0x05 prefix)`);
726
+ }
727
+ return [Uint8Array.of(AUTHSCRIPT_PQ), input.signature, input.pubKey, Uint8Array.of(OP_TRUE)];
728
+ }
729
+ /**
730
+ * Witness stack for spending a strict ECDSA witness v3 output (`nq1r…`):
731
+ * exactly `[0x02, sig, pubKey33, OP_TRUE]`. The node rejects uncompressed
732
+ * keys for this family.
733
+ */
734
+ function buildStrictWitnessECDSA(input) {
735
+ if (!(input.signature instanceof Uint8Array) || input.signature.length === 0) {
736
+ throw new Error('signature must be a non-empty Uint8Array');
737
+ }
738
+ if (!(input.pubKey instanceof Uint8Array) ||
739
+ input.pubKey.length !== 33 ||
740
+ (input.pubKey[0] !== 0x02 && input.pubKey[0] !== 0x03)) {
741
+ throw new Error('pubKey must be a compressed (33B) secp256k1 key for strict ECDSA witness v3');
742
+ }
743
+ return [Uint8Array.of(AUTHSCRIPT_LEGACY), input.signature, input.pubKey, Uint8Array.of(OP_TRUE)];
744
+ }
686
745
  /**
687
746
  * Build the witness stack for a NoAuth AuthScript spend. The spend is gated
688
747
  * by the witnessScript alone (covenants, hash-locks, time-locks, ...); no
@@ -1521,37 +1580,96 @@ function resolveAddressInput(address) {
1521
1580
 
1522
1581
  const LEGACY_MAINNET_PREFIX = 53;
1523
1582
  const LEGACY_TESTNET_PREFIX = 127;
1524
- const PQ_MAINNET_HRP = 'nq';
1525
- const PQ_TESTNET_HRP = 'tnq';
1526
- function inferNetworkFromAddress(address) {
1527
- const normalized = resolveAddressInput(address).toLowerCase();
1528
- if (normalized.startsWith(PQ_MAINNET_HRP + '1'))
1529
- return 'xna-pq';
1530
- if (normalized.startsWith(PQ_TESTNET_HRP + '1'))
1531
- return 'xna-pq-test';
1532
- if (normalized.startsWith('n'))
1533
- return 'xna';
1534
- if (normalized.startsWith('t'))
1535
- return 'xna-test';
1536
- throw new Error(`Unsupported Neurai address: ${address}`);
1583
+ const WITNESS_FAMILIES = [
1584
+ {
1585
+ type: 'authscript',
1586
+ witnessVersion: 1,
1587
+ hrp: { mainnet: 'nc', testnet: 'tnc' },
1588
+ network: { mainnet: 'xna-authscript', testnet: 'xna-authscript-test' }
1589
+ },
1590
+ {
1591
+ type: 'pq',
1592
+ witnessVersion: 2,
1593
+ hrp: { mainnet: 'pq', testnet: 'tpq' },
1594
+ network: { mainnet: 'xna-pq', testnet: 'xna-pq-test' }
1595
+ },
1596
+ {
1597
+ type: 'ecdsa',
1598
+ witnessVersion: 3,
1599
+ hrp: { mainnet: 'nq', testnet: 'tnq' },
1600
+ network: { mainnet: 'xna', testnet: 'xna-test' }
1601
+ }
1602
+ ];
1603
+ /** The family that owns `hrp` (lowercase), with the chain it encodes. */
1604
+ function witnessFamilyByHrp(hrp) {
1605
+ for (const family of WITNESS_FAMILIES) {
1606
+ if (family.hrp.mainnet === hrp)
1607
+ return { family, chain: 'mainnet' };
1608
+ if (family.hrp.testnet === hrp)
1609
+ return { family, chain: 'testnet' };
1610
+ }
1611
+ return undefined;
1612
+ }
1613
+ /** The family encoded by `witnessVersion`, or undefined for any other version. */
1614
+ function witnessFamilyByVersion(witnessVersion) {
1615
+ return WITNESS_FAMILIES.find((family) => family.witnessVersion === witnessVersion);
1537
1616
  }
1538
1617
 
1539
- function decodeAddress(address) {
1540
- const normalized = resolveAddressInput(address);
1541
- const lowered = normalized.toLowerCase();
1542
- if (!normalized)
1543
- throw new Error('Address is required');
1544
- if (lowered.startsWith(PQ_MAINNET_HRP + '1') || lowered.startsWith(PQ_TESTNET_HRP + '1')) {
1545
- const decoded = distExports.bech32m.decode(normalized);
1546
- const version = decoded.words[0];
1547
- const program = Uint8Array.from(distExports.bech32m.fromWords(decoded.words.slice(1)));
1548
- if (version !== 1 || program.length !== 32) {
1549
- throw new Error(`Unsupported AuthScript address program for ${address}`);
1550
- }
1551
- const network = lowered.startsWith(PQ_TESTNET_HRP + '1') ? 'xna-pq-test' : 'xna-pq';
1552
- return { address: normalized, type: 'authscript', network, program, commitment: program };
1618
+ // Longest Bech32m string the node's decoder accepts (bech32.cpp).
1619
+ const BECH32M_MAX_LENGTH = 90;
1620
+ const AUTHSCRIPT_PROGRAM_LENGTH = 32;
1621
+ function tryBech32mDecode(address) {
1622
+ try {
1623
+ const { prefix, words } = distExports.bech32m.decode(address, BECH32M_MAX_LENGTH);
1624
+ return { hrp: prefix.toLowerCase(), words };
1625
+ }
1626
+ catch {
1627
+ return null;
1628
+ }
1629
+ }
1630
+ function decodeWitnessAddress(address, parts) {
1631
+ const owner = witnessFamilyByHrp(parts.hrp);
1632
+ if (!owner) {
1633
+ throw new Error(`Unsupported Bech32m prefix "${parts.hrp}" for ${address}`);
1634
+ }
1635
+ if (parts.words.length === 0) {
1636
+ throw new Error(`Empty witness program in ${address}`);
1637
+ }
1638
+ const version = parts.words[0];
1639
+ const { family, chain } = owner;
1640
+ if (version !== family.witnessVersion) {
1641
+ const actual = witnessFamilyByVersion(version);
1642
+ const hint = actual
1643
+ ? `; witness v${version} addresses use the "${actual.hrp[chain]}" prefix`
1644
+ : '';
1645
+ const legacyHint = family.type === 'ecdsa' && version === 1
1646
+ ? ' Generic AuthScript v1 addresses are now encoded as nc1p… / tnc1p… ' +
1647
+ '(same scriptPubKey): regenerate the address (neurai-key xna-authscript networks).'
1648
+ : '';
1649
+ throw new Error(`Address ${address}: the "${parts.hrp}" prefix only encodes witness v${family.witnessVersion}, ` +
1650
+ `not v${version}${hint}.${legacyHint}`);
1651
+ }
1652
+ let program;
1653
+ try {
1654
+ program = Uint8Array.from(distExports.bech32m.fromWords(parts.words.slice(1)));
1655
+ }
1656
+ catch {
1657
+ throw new Error(`Invalid witness program padding in ${address}`);
1658
+ }
1659
+ if (program.length !== AUTHSCRIPT_PROGRAM_LENGTH) {
1660
+ throw new Error(`Unsupported AuthScript program length ${program.length} for ${address} (expected ${AUTHSCRIPT_PROGRAM_LENGTH})`);
1553
1661
  }
1554
- const payload = Uint8Array.from(bs58check.decode(normalized));
1662
+ return {
1663
+ address,
1664
+ type: family.type,
1665
+ witnessVersion: family.witnessVersion,
1666
+ network: family.network[chain],
1667
+ program,
1668
+ commitment: program
1669
+ };
1670
+ }
1671
+ function decodeLegacyAddress(address) {
1672
+ const payload = Uint8Array.from(bs58check.decode(address));
1555
1673
  if (payload.length !== 21) {
1556
1674
  throw new Error(`Unsupported legacy address payload length for ${address}`);
1557
1675
  }
@@ -1560,13 +1678,51 @@ function decodeAddress(address) {
1560
1678
  throw new Error(`Unsupported legacy address prefix ${prefix} for ${address}`);
1561
1679
  }
1562
1680
  return {
1563
- address: normalized,
1681
+ address,
1564
1682
  type: 'p2pkh',
1565
- network: inferNetworkFromAddress(normalized),
1683
+ network: prefix === LEGACY_MAINNET_PREFIX ? 'xna-legacy' : 'xna-legacy-test',
1566
1684
  program: payload.slice(1),
1567
1685
  hash: payload.slice(1)
1568
1686
  };
1569
1687
  }
1688
+ /**
1689
+ * Decode a Neurai address the way the node does (base58.cpp
1690
+ * `DecodeDestination`): Bech32m first, Base58Check otherwise.
1691
+ *
1692
+ * - Base58 P2PKH → `type: 'p2pkh'`, network `xna-legacy` / `xna-legacy-test`
1693
+ * (an `xna-old-legacy` address is indistinguishable and reports
1694
+ * `xna-legacy`).
1695
+ * - Bech32m → `authscript` (v1, `nc`/`tnc`), `pq` (v2, `pq`/`tpq`) or
1696
+ * `ecdsa` (v3, `nq`/`tnq`), with `witnessVersion` and the 32-byte
1697
+ * commitment. Any other HRP/version pair is rejected, including the old
1698
+ * `nq1p…` / `tnq1p…` encoding of generic AuthScript v1.
1699
+ *
1700
+ * The decoder does not know whether a witness family is active on the
1701
+ * target chain: before activation the node refuses v2/v3 addresses and a
1702
+ * witness output is anyone-can-spend.
1703
+ */
1704
+ function decodeAddress(address) {
1705
+ const normalized = resolveAddressInput(address);
1706
+ if (!normalized)
1707
+ throw new Error('Address is required');
1708
+ const bech32mParts = tryBech32mDecode(normalized);
1709
+ if (bech32mParts) {
1710
+ return decodeWitnessAddress(normalized, bech32mParts);
1711
+ }
1712
+ try {
1713
+ return decodeLegacyAddress(normalized);
1714
+ }
1715
+ catch (legacyError) {
1716
+ // Not Base58 either. When the string carries a known Bech32m prefix the
1717
+ // Bech32m failure (bad checksum, mixed case…) is the useful diagnosis.
1718
+ const separator = normalized.lastIndexOf('1');
1719
+ const hrp = separator > 0 ? normalized.slice(0, separator).toLowerCase() : '';
1720
+ if (witnessFamilyByHrp(hrp)) {
1721
+ throw new Error(`Invalid Bech32m address ${normalized} (checksum, case or character error)`);
1722
+ }
1723
+ throw legacyError;
1724
+ }
1725
+ }
1570
1726
 
1571
1727
  /**
1572
1728
  * Address helpers. Wraps `decodeAddress` from
@@ -1574,9 +1730,12 @@ function decodeAddress(address) {
1574
1730
  * scriptPubKey bytes a covenant needs to hardcode. The actual
1575
1731
  * scriptPubKey encoders live in `./standard/*`; this module delegates.
1576
1732
  *
1577
- * Two destination types are supported for the payment output (output[0]):
1578
- * - Legacy P2PKH (base58check)
1579
- * - AuthScript witness v1 (bech32m)
1733
+ * Every Neurai destination type is supported for the payment output
1734
+ * (output[0]):
1735
+ * - Legacy P2PKH (base58check) → `76a914<20>88ac`
1736
+ * - Generic AuthScript witness v1 (nc1p… / tnc1p…) → `5120<32>`
1737
+ * - Strict PQ witness v2 (pq1z… / tpq1z…) → `5220<32>`
1738
+ * - Strict ECDSA witness v3 (nq1r… / tnq1r…) → `5320<32>`
1580
1739
  */
1581
1740
  /**
1582
1741
  * Resolve any accepted seller address string into its scriptPubKey.
@@ -1593,11 +1752,14 @@ function encodeSellerScriptPubKey(address) {
1593
1752
  hash
1594
1753
  };
1595
1754
  }
1596
- if (decoded.type === 'authscript') {
1755
+ if (decoded.type === 'authscript' || decoded.type === 'pq' || decoded.type === 'ecdsa') {
1756
+ // The witness version is part of the destination: a pq1z… / nq1r…
1757
+ // payment must be hardcoded with OP_2 / OP_3, never with OP_1.
1597
1758
  const program = Uint8Array.from(decoded.program);
1598
1759
  return {
1599
- kind: 'authscript',
1600
- bytes: encodeAuthScriptScriptPubKey(program),
1760
+ kind: decoded.type,
1761
+ witnessVersion: decoded.witnessVersion,
1762
+ bytes: encodeAuthScriptScriptPubKey(program, decoded.witnessVersion),
1601
1763
  hash: program
1602
1764
  };
1603
1765
  }
@@ -1612,8 +1774,8 @@ function encodeSellerScriptPubKey(address) {
1612
1774
  * <prefix scriptPubKey bytes> OP_XNA_ASSET <pushdata(payload)> OP_DROP
1613
1775
  *
1614
1776
  * where `prefix` is the recipient's standard script (typically a P2PKH, an
1615
- * AuthScript witness v1, or a bare covenant such as the partial-fill sell
1616
- * order), and `payload` serializes a `CAssetTransfer`:
1777
+ * AuthScript `OP_1`/`OP_2`/`OP_3` witness program, or a bare covenant such
1778
+ * as the partial-fill sell order), and `payload` serializes a `CAssetTransfer`:
1617
1779
  *
1618
1780
  * payload = marker ("rvn" 0x72 0x76 0x6e | "xna" 0x78 0x6e 0x61)
1619
1781
  * || type_marker (0x74 transfer)
@@ -2952,5 +3114,5 @@ function parsePartialFillScriptPQ(script, network = 'xna-test') {
2952
3114
  };
2953
3115
  }
2954
3116
 
2955
- 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, buildCancelWitnessStack, buildCancelWitnessStackPQ, buildFillScriptSig, buildFillScriptSigHex, buildFillWitnessStack, 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 };
3117
+ export { AUTHSCRIPT_LEGACY, AUTHSCRIPT_NOAUTH, AUTHSCRIPT_PQ, AUTHSCRIPT_REF, DEFAULT_PQ_TXHASH_SELECTOR, MULTISIG_MAX_PUBKEYS, NULLDATA_STANDARD_MAX_SIZE, PQ_PUBKEY_PREFIX, STRICT_PQ_PUBKEY_LENGTH, ScriptBuilder, buildAuthScriptWitnessLegacy, buildAuthScriptWitnessNoAuth, buildAuthScriptWitnessPQ, buildAuthScriptWitnessRef, buildCancelScriptSig, buildCancelScriptSigHex, buildCancelScriptSigPQ, buildCancelScriptSigPQHex, buildCancelWitnessStack, buildCancelWitnessStackPQ, buildFillScriptSig, buildFillScriptSigHex, buildFillWitnessStack, buildPartialFillScript, buildPartialFillScriptHex, buildPartialFillScriptPQ, buildPartialFillScriptPQHex, buildStrictWitnessECDSA, buildStrictWitnessPQ, bytesEqual, bytesToHex, concatBytes, encodeAuthScriptScriptPubKey, encodeMultisigRedeemScript, encodeMultisigRedeemScriptHex, encodeNullDataScript, encodeP2PKHScriptPubKey, encodeP2SHScriptPubKey, encodeP2WPKHScriptPubKey, encodeP2WSHScriptPubKey, encodeScriptNum, encodeSellerScriptPubKey, ensureHex, hexToBytes, isPartialFillScriptPQ, opcodes, parsePartialFillScript, parsePartialFillScriptPQ, pushBytes, pushHex, pushInt, splitAssetWrappedScriptPubKey };
2956
3118
  //# sourceMappingURL=browser.js.map