@neuraiproject/neurai-scripts 0.10.0 → 0.12.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.cjs CHANGED
@@ -5,25 +5,25 @@
5
5
  * duplicated here to keep this package free of runtime coupling beyond its
6
6
  * declared `dependencies` field. All sizes are little-endian, per Neurai.
7
7
  */
8
- function ensureHex(hex, label = 'hex') {
8
+ function ensureHex$1(hex, label = 'hex') {
9
9
  const normalized = String(hex || '').trim().toLowerCase();
10
10
  if (!/^[0-9a-f]*$/.test(normalized) || normalized.length % 2 !== 0) {
11
11
  throw new Error(`Invalid ${label}: expected even-length hex string`);
12
12
  }
13
13
  return normalized;
14
14
  }
15
- function hexToBytes(hex) {
16
- const normalized = ensureHex(hex);
15
+ function hexToBytes$1(hex) {
16
+ const normalized = ensureHex$1(hex);
17
17
  const bytes = new Uint8Array(normalized.length / 2);
18
18
  for (let i = 0; i < normalized.length; i += 2) {
19
19
  bytes[i / 2] = Number.parseInt(normalized.slice(i, i + 2), 16);
20
20
  }
21
21
  return bytes;
22
22
  }
23
- function bytesToHex(bytes) {
23
+ function bytesToHex$1(bytes) {
24
24
  return Array.from(bytes, (value) => value.toString(16).padStart(2, '0')).join('');
25
25
  }
26
- function concatBytes(...parts) {
26
+ function concatBytes$1(...parts) {
27
27
  const total = parts.reduce((sum, part) => sum + part.length, 0);
28
28
  const out = new Uint8Array(total);
29
29
  let offset = 0;
@@ -45,7 +45,7 @@ function bytesEqual(a, b) {
45
45
 
46
46
  /** Exact monetary primitives. This module has no runtime dependencies. */
47
47
  /** Normalize a raw integer without preserving an already rounded number. */
48
- function toRawInteger(value, label = 'amount') {
48
+ function toRawInteger$1(value, label = 'amount') {
49
49
  if (typeof value === 'bigint')
50
50
  return value;
51
51
  if (typeof value === 'number' && Number.isSafeInteger(value))
@@ -187,6 +187,10 @@ const OP_CHECKSIG_ED25519 = 0xdd;
187
187
  // 0xde. Stack contract: (sig, count, pubkey -- count + 0|1). Works with
188
188
  // both legacy secp256k1 and PQ ML-DSA-44 keys via CPubKey::Verify().
189
189
  const OP_CHECKSIGADD = 0xde;
190
+ // NIP-054 (P2AH): M-of-N authorization by owner-token roles in slot 0xdf,
191
+ // AuthScript only. Stack contract: (c a b T 1 M G role_1 .. role_n n -- 1),
192
+ // failing the script instead of pushing 0. See covenants/asset-auth.
193
+ const OP_CHECKASSETAUTH = 0xdf;
190
194
  // ---------- Expansion / NOPs ----------
191
195
  // Only the NOPs not aliased by DePIN-Test opcodes are exported as NOPs.
192
196
  // OP_NOP2 == OP_CHECKLOCKTIMEVERIFY (0xb1)
@@ -345,6 +349,7 @@ var opcodes = /*#__PURE__*/Object.freeze({
345
349
  OP_BOOLOR: OP_BOOLOR,
346
350
  OP_CAT: OP_CAT,
347
351
  OP_CHAINCONTEXT: OP_CHAINCONTEXT,
352
+ OP_CHECKASSETAUTH: OP_CHECKASSETAUTH,
348
353
  OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY,
349
354
  OP_CHECKMERKLEINCLUSION: OP_CHECKMERKLEINCLUSION,
350
355
  OP_CHECKMULTISIG: OP_CHECKMULTISIG,
@@ -459,7 +464,7 @@ var opcodes = /*#__PURE__*/Object.freeze({
459
464
  * - otherwise: sign-magnitude little-endian, with a sign bit on the last byte
460
465
  */
461
466
  function encodeScriptNum(value) {
462
- let n = toRawInteger(value, 'ScriptNum');
467
+ let n = toRawInteger$1(value, 'ScriptNum');
463
468
  if (n === 0n)
464
469
  return new Uint8Array();
465
470
  const negative = n < 0n;
@@ -498,13 +503,13 @@ function pushBytes(data) {
498
503
  return Uint8Array.of(OP_0);
499
504
  }
500
505
  if (data.length <= 75) {
501
- return concatBytes(Uint8Array.of(data.length), data);
506
+ return concatBytes$1(Uint8Array.of(data.length), data);
502
507
  }
503
508
  if (data.length <= 0xff) {
504
- return concatBytes(Uint8Array.of(0x4c, data.length), data);
509
+ return concatBytes$1(Uint8Array.of(0x4c, data.length), data);
505
510
  }
506
511
  if (data.length <= 3072) {
507
- return concatBytes(Uint8Array.of(0x4d, data.length & 0xff, (data.length >> 8) & 0xff), data);
512
+ return concatBytes$1(Uint8Array.of(0x4d, data.length & 0xff, (data.length >> 8) & 0xff), data);
508
513
  }
509
514
  throw new Error(`pushBytes: element of ${data.length} bytes exceeds MAX_PQ_SCRIPT_ELEMENT_SIZE (3072)`);
510
515
  }
@@ -513,7 +518,7 @@ function pushBytes(data) {
513
518
  * when available to match how the node's own templates look on the wire.
514
519
  */
515
520
  function pushInt(value) {
516
- const n = toRawInteger(value, 'ScriptNum');
521
+ const n = toRawInteger$1(value, 'ScriptNum');
517
522
  if (n === -1n)
518
523
  return Uint8Array.of(OP_1NEGATE);
519
524
  if (n === 0n)
@@ -524,7 +529,7 @@ function pushInt(value) {
524
529
  return pushBytes(encodeScriptNum(n));
525
530
  }
526
531
  function pushHex(hex) {
527
- return pushBytes(hexToBytes(hex));
532
+ return pushBytes(hexToBytes$1(hex));
528
533
  }
529
534
  /** Fluent assembler for readable script definitions. */
530
535
  class ScriptBuilder {
@@ -555,10 +560,10 @@ class ScriptBuilder {
555
560
  return this;
556
561
  }
557
562
  build() {
558
- return concatBytes(...this.parts);
563
+ return concatBytes$1(...this.parts);
559
564
  }
560
565
  buildHex() {
561
- return bytesToHex(this.build());
566
+ return bytesToHex$1(this.build());
562
567
  }
563
568
  }
564
569
 
@@ -570,7 +575,7 @@ function encodeP2PKHScriptPubKey(pubKeyHash) {
570
575
  if (!(pubKeyHash instanceof Uint8Array) || pubKeyHash.length !== 20) {
571
576
  throw new Error('P2PKH pubKeyHash must be a 20-byte Uint8Array');
572
577
  }
573
- return concatBytes(Uint8Array.of(OP_DUP, OP_HASH160, 0x14), pubKeyHash, Uint8Array.of(OP_EQUALVERIFY, OP_CHECKSIG));
578
+ return concatBytes$1(Uint8Array.of(OP_DUP, OP_HASH160, 0x14), pubKeyHash, Uint8Array.of(OP_EQUALVERIFY, OP_CHECKSIG));
574
579
  }
575
580
 
576
581
  /**
@@ -584,7 +589,7 @@ function encodeP2WPKHScriptPubKey(pubKeyHash) {
584
589
  if (!(pubKeyHash instanceof Uint8Array) || pubKeyHash.length !== 20) {
585
590
  throw new Error('P2WPKH pubKeyHash must be a 20-byte Uint8Array');
586
591
  }
587
- return concatBytes(Uint8Array.of(OP_0, 0x14), pubKeyHash);
592
+ return concatBytes$1(Uint8Array.of(OP_0, 0x14), pubKeyHash);
588
593
  }
589
594
 
590
595
  /**
@@ -599,7 +604,7 @@ function encodeP2WSHScriptPubKey(witnessScriptSha256) {
599
604
  if (!(witnessScriptSha256 instanceof Uint8Array) || witnessScriptSha256.length !== 32) {
600
605
  throw new Error('P2WSH witnessScriptSha256 must be a 32-byte Uint8Array');
601
606
  }
602
- return concatBytes(Uint8Array.of(OP_0, 0x20), witnessScriptSha256);
607
+ return concatBytes$1(Uint8Array.of(OP_0, 0x20), witnessScriptSha256);
603
608
  }
604
609
 
605
610
  /**
@@ -657,7 +662,7 @@ function encodeAuthScriptScriptPubKey(program, witnessVersion = 1) {
657
662
  if (opcode === undefined) {
658
663
  throw new Error(`AuthScript witness version must be 1, 2 or 3, got ${String(witnessVersion)}`);
659
664
  }
660
- return concatBytes(Uint8Array.of(opcode, 0x20), program);
665
+ return concatBytes$1(Uint8Array.of(opcode, 0x20), program);
661
666
  }
662
667
  function assertWitnessScript(ws) {
663
668
  if (!(ws instanceof Uint8Array) || ws.length === 0) {
@@ -835,7 +840,7 @@ function encodeNullDataScript(payload, options = {}) {
835
840
  const parts = [Uint8Array.of(OP_RETURN)];
836
841
  for (const p of payloads)
837
842
  parts.push(pushBytes(p));
838
- return concatBytes(...parts);
843
+ return concatBytes$1(...parts);
839
844
  }
840
845
 
841
846
  /**
@@ -872,10 +877,10 @@ function encodeMultisigRedeemScript({ m, pubKeys }) {
872
877
  parts.push(pushBytes(pk));
873
878
  parts.push(pushInt(pubKeys.length));
874
879
  parts.push(Uint8Array.of(OP_CHECKMULTISIG));
875
- return concatBytes(...parts);
880
+ return concatBytes$1(...parts);
876
881
  }
877
882
  function encodeMultisigRedeemScriptHex(params) {
878
- return bytesToHex(encodeMultisigRedeemScript(params));
883
+ return bytesToHex$1(encodeMultisigRedeemScript(params));
879
884
  }
880
885
  /**
881
886
  * P2SH scriptPubKey wrapping any redeem script. Pass the 20-byte HASH160 of
@@ -886,10 +891,98 @@ function encodeP2SHScriptPubKey(redeemScriptHash160) {
886
891
  if (!(redeemScriptHash160 instanceof Uint8Array) || redeemScriptHash160.length !== 20) {
887
892
  throw new Error('redeemScriptHash160 must be a 20-byte Uint8Array');
888
893
  }
889
- return concatBytes(Uint8Array.of(OP_HASH160, 0x14), redeemScriptHash160, Uint8Array.of(OP_EQUAL));
894
+ return concatBytes$1(Uint8Array.of(OP_HASH160, 0x14), redeemScriptHash160, Uint8Array.of(OP_EQUAL));
890
895
  }
891
896
 
892
897
  /** Exact monetary primitives. This module has no runtime dependencies. */
898
+ /** Normalize a raw integer without preserving an already rounded number. */
899
+ function toRawInteger(value, label = 'amount') {
900
+ if (typeof value === 'bigint')
901
+ return value;
902
+ if (typeof value === 'number' && Number.isSafeInteger(value))
903
+ return BigInt(value);
904
+ if (typeof value === 'string' && /^-?\d+$/.test(value) && value.length <= 100)
905
+ return BigInt(value);
906
+ throw new Error(`${label}: expected an exact integer; use bigint or an integer string for large values`);
907
+ }
908
+
909
+ function ensureHex(hex, label = 'hex') {
910
+ const normalized = String(hex || '').trim().toLowerCase();
911
+ if (!/^[0-9a-f]*$/.test(normalized) || normalized.length % 2 !== 0) {
912
+ throw new Error(`Invalid ${label}: expected even-length hex string`);
913
+ }
914
+ return normalized;
915
+ }
916
+ function hexToBytes(hex) {
917
+ const normalized = ensureHex(hex);
918
+ const bytes = new Uint8Array(normalized.length / 2);
919
+ for (let i = 0; i < normalized.length; i += 2) {
920
+ bytes[i / 2] = Number.parseInt(normalized.slice(i, i + 2), 16);
921
+ }
922
+ return bytes;
923
+ }
924
+ function bytesToHex(bytes) {
925
+ return Array.from(bytes, (value) => value.toString(16).padStart(2, '0')).join('');
926
+ }
927
+ function concatBytes(...parts) {
928
+ const total = parts.reduce((sum, part) => sum + part.length, 0);
929
+ const out = new Uint8Array(total);
930
+ let offset = 0;
931
+ for (const part of parts) {
932
+ out.set(part, offset);
933
+ offset += part.length;
934
+ }
935
+ return out;
936
+ }
937
+ function reverseBytes(bytes) {
938
+ return Uint8Array.from(Array.from(bytes).reverse());
939
+ }
940
+ function u32LE(value) {
941
+ if (!Number.isInteger(value) || value < 0 || value > 0xffffffff) {
942
+ throw new Error(`uint32 out of range: ${value}`);
943
+ }
944
+ const out = new Uint8Array(4);
945
+ const view = new DataView(out.buffer);
946
+ view.setUint32(0, value, true);
947
+ return out;
948
+ }
949
+ function u64LE(value) {
950
+ const bigintValue = toRawInteger(value);
951
+ if (bigintValue < 0n || bigintValue > 0xffffffffffffffffn) {
952
+ throw new Error(`uint64 out of range: ${bigintValue}`);
953
+ }
954
+ const out = new Uint8Array(8);
955
+ let remaining = bigintValue;
956
+ for (let i = 0; i < 8; i += 1) {
957
+ out[i] = Number(remaining & 0xffn);
958
+ remaining >>= 8n;
959
+ }
960
+ return out;
961
+ }
962
+ function compactSize$1(value) {
963
+ const bigintValue = toRawInteger(value);
964
+ if (bigintValue < 0n)
965
+ throw new Error('CompactSize cannot encode negative numbers');
966
+ if (bigintValue < 253n) {
967
+ return Uint8Array.of(Number(bigintValue));
968
+ }
969
+ if (bigintValue <= 0xffffn) {
970
+ return concatBytes(Uint8Array.of(0xfd), u16LE(Number(bigintValue)));
971
+ }
972
+ if (bigintValue <= 0xffffffffn) {
973
+ return concatBytes(Uint8Array.of(0xfe), u32LE(Number(bigintValue)));
974
+ }
975
+ return concatBytes(Uint8Array.of(0xff), u64LE(bigintValue));
976
+ }
977
+ function u16LE(value) {
978
+ if (!Number.isInteger(value) || value < 0 || value > 0xffff) {
979
+ throw new Error(`uint16 out of range: ${value}`);
980
+ }
981
+ const out = new Uint8Array(2);
982
+ const view = new DataView(out.buffer);
983
+ view.setUint16(0, value, true);
984
+ return out;
985
+ }
893
986
 
894
987
  // base-x encoding / decoding
895
988
  // Copyright (c) 2018 base-x contributors
@@ -1749,6 +1842,192 @@ function decodeAddress(address) {
1749
1842
  throw legacyError;
1750
1843
  }
1751
1844
  }
1845
+ function serializeOutput(output) {
1846
+ const scriptPubKey = hexToBytes(ensureHex(output.scriptPubKeyHex, 'scriptPubKeyHex'));
1847
+ return concatBytes(u64LE(output.valueSats), compactSize$1(scriptPubKey.length), scriptPubKey);
1848
+ }
1849
+
1850
+ // Hard deserialization bound, mirroring the node (serialize.h MAX_SIZE):
1851
+ // ReadCompactSize rejects anything above it, canonical or not.
1852
+ const MAX_SIZE = 0x02000000;
1853
+ class ByteReader {
1854
+ bytes;
1855
+ offset = 0;
1856
+ constructor(bytes) {
1857
+ this.bytes = bytes;
1858
+ }
1859
+ need(count) {
1860
+ if (count > this.bytes.length - this.offset) {
1861
+ throw new Error(`Transaction hex truncated: need ${count} more byte(s) at offset ${this.offset}, ` +
1862
+ `${this.bytes.length - this.offset} remaining`);
1863
+ }
1864
+ }
1865
+ readBytes(count) {
1866
+ this.need(count);
1867
+ const slice = this.bytes.subarray(this.offset, this.offset + count);
1868
+ this.offset += count;
1869
+ return slice;
1870
+ }
1871
+ readU8() {
1872
+ return this.readBytes(1)[0];
1873
+ }
1874
+ readU32() {
1875
+ const slice = this.readBytes(4);
1876
+ return (slice[0] | (slice[1] << 8) | (slice[2] << 16) | (slice[3] << 24)) >>> 0;
1877
+ }
1878
+ readU64() {
1879
+ const slice = this.readBytes(8);
1880
+ let value = 0n;
1881
+ for (let i = 7; i >= 0; i -= 1) {
1882
+ value = (value << 8n) | BigInt(slice[i]);
1883
+ }
1884
+ return value;
1885
+ }
1886
+ // Canonical CompactSize with the node's range bound: the shortest encoding
1887
+ // is mandatory and anything above MAX_SIZE throws, exactly like
1888
+ // ReadCompactSize. Lengths are validated against the remaining bytes by the
1889
+ // callers BEFORE any allocation or iteration.
1890
+ readCompactSize() {
1891
+ const first = this.readU8();
1892
+ let value;
1893
+ if (first < 0xfd) {
1894
+ value = first;
1895
+ }
1896
+ else if (first === 0xfd) {
1897
+ const slice = this.readBytes(2);
1898
+ value = slice[0] | (slice[1] << 8);
1899
+ if (value < 0xfd)
1900
+ throw new Error('Non-canonical CompactSize (0xfd form for value < 253)');
1901
+ }
1902
+ else if (first === 0xfe) {
1903
+ value = this.readU32();
1904
+ if (value < 0x10000)
1905
+ throw new Error('Non-canonical CompactSize (0xfe form for value < 0x10000)');
1906
+ }
1907
+ else {
1908
+ const big = this.readU64();
1909
+ if (big < 0x100000000n)
1910
+ throw new Error('Non-canonical CompactSize (0xff form for value < 2^32)');
1911
+ if (big > BigInt(MAX_SIZE))
1912
+ throw new Error(`CompactSize exceeds MAX_SIZE: ${big}`);
1913
+ value = Number(big);
1914
+ }
1915
+ if (value > MAX_SIZE) {
1916
+ throw new Error(`CompactSize exceeds MAX_SIZE: ${value}`);
1917
+ }
1918
+ return value;
1919
+ }
1920
+ /** Read a length prefix that must fit in the remaining bytes at `bytesPerItem`. */
1921
+ readCount(bytesPerItem, label) {
1922
+ const count = this.readCompactSize();
1923
+ if (count * bytesPerItem > this.bytes.length - this.offset) {
1924
+ throw new Error(`Declared ${label} count ${count} does not fit in the remaining ` +
1925
+ `${this.bytes.length - this.offset} byte(s)`);
1926
+ }
1927
+ return count;
1928
+ }
1929
+ get finished() {
1930
+ return this.offset === this.bytes.length;
1931
+ }
1932
+ get position() {
1933
+ return this.offset;
1934
+ }
1935
+ }
1936
+ function readOutpoint(reader) {
1937
+ const txid = bytesToHex(reverseBytes(reader.readBytes(32)));
1938
+ const vout = reader.readU32();
1939
+ return { txid, vout };
1940
+ }
1941
+ function readInput(reader) {
1942
+ const { txid, vout } = readOutpoint(reader);
1943
+ const scriptLength = reader.readCount(1, 'scriptSig');
1944
+ const scriptSigHex = bytesToHex(reader.readBytes(scriptLength));
1945
+ const sequence = reader.readU32();
1946
+ return { txid, vout, scriptSigHex, sequence };
1947
+ }
1948
+ function readOutput(reader) {
1949
+ const valueSats = reader.readU64();
1950
+ const scriptLength = reader.readCount(1, 'scriptPubKey');
1951
+ const scriptPubKeyHex = bytesToHex(reader.readBytes(scriptLength));
1952
+ return { valueSats, scriptPubKeyHex };
1953
+ }
1954
+ // Minimum serialized size per item, used only to bound counts before reading:
1955
+ // input = outpoint(36) + compactSize(1) + sequence(4); output = value(8) +
1956
+ // compactSize(1); witness element = compactSize(1).
1957
+ const MIN_INPUT_SIZE = 41;
1958
+ const MIN_OUTPUT_SIZE = 9;
1959
+ function parseTransaction(hex) {
1960
+ const reader = new ByteReader(hexToBytes(ensureHex(hex, 'transaction hex')));
1961
+ // nVersion is a signed int32 (negative versions exist on-chain historically).
1962
+ const version = reader.readU32() | 0;
1963
+ const inputs = [];
1964
+ const outputs = [];
1965
+ let flags = 0;
1966
+ const vinCount = reader.readCount(MIN_INPUT_SIZE, 'input');
1967
+ if (vinCount === 0) {
1968
+ // Either a dummy marker for the extended (witness) format, or a genuinely
1969
+ // empty vin. Mirrors UnserializeTransaction: a flags byte follows; when it
1970
+ // is non-zero the real vin/vout follow, when zero the vout is NOT read.
1971
+ flags = reader.readU8();
1972
+ if (flags !== 0) {
1973
+ const realVinCount = reader.readCount(MIN_INPUT_SIZE, 'input');
1974
+ for (let i = 0; i < realVinCount; i += 1)
1975
+ inputs.push(readInput(reader));
1976
+ const voutCount = reader.readCount(MIN_OUTPUT_SIZE, 'output');
1977
+ for (let i = 0; i < voutCount; i += 1)
1978
+ outputs.push(readOutput(reader));
1979
+ }
1980
+ }
1981
+ else {
1982
+ for (let i = 0; i < vinCount; i += 1)
1983
+ inputs.push(readInput(reader));
1984
+ const voutCount = reader.readCount(MIN_OUTPUT_SIZE, 'output');
1985
+ for (let i = 0; i < voutCount; i += 1)
1986
+ outputs.push(readOutput(reader));
1987
+ }
1988
+ // NIP-014: reference inputs sit between vout and witness, announced by flag
1989
+ // 0x02. Without the flag a version 3 transaction reads as 1.0.7 reads it.
1990
+ const vrefin = [];
1991
+ const hasRefInputs = (flags & 2) !== 0;
1992
+ if (hasRefInputs) {
1993
+ flags ^= 2;
1994
+ const refCount = reader.readCount(36, 'refinput');
1995
+ for (let i = 0; i < refCount; i += 1)
1996
+ vrefin.push(readOutpoint(reader));
1997
+ if (vrefin.length === 0) {
1998
+ // One encoding per transaction: the flag means some.
1999
+ throw new Error('Superfluous reference inputs record (flag 0x02 with no reference inputs)');
2000
+ }
2001
+ }
2002
+ if (flags & 1) {
2003
+ flags ^= 1;
2004
+ for (const input of inputs) {
2005
+ const stackSize = reader.readCount(1, 'witness element');
2006
+ const stack = [];
2007
+ for (let i = 0; i < stackSize; i += 1) {
2008
+ const elementLength = reader.readCount(1, 'witness bytes');
2009
+ stack.push(bytesToHex(reader.readBytes(elementLength)));
2010
+ }
2011
+ input.witness = stack;
2012
+ }
2013
+ if (hasRefInputs && !inputs.some(inputHasWitness)) {
2014
+ // With reference inputs the witness flag means some witness; 1.0.7 reads
2015
+ // an empty witness record without them, and so does the node.
2016
+ throw new Error('Superfluous witness record (flag 0x01 with no witness data)');
2017
+ }
2018
+ }
2019
+ if (flags) {
2020
+ throw new Error(`Unknown transaction optional data (flags 0x${flags.toString(16)})`);
2021
+ }
2022
+ const locktime = reader.readU32();
2023
+ if (!reader.finished) {
2024
+ throw new Error(`Trailing bytes after transaction (offset ${reader.position})`);
2025
+ }
2026
+ return { version, inputs, outputs, vrefin, locktime };
2027
+ }
2028
+ function inputHasWitness(input) {
2029
+ return (input.witness?.length ?? 0) > 0;
2030
+ }
1752
2031
 
1753
2032
  /**
1754
2033
  * Address helpers. Wraps `decodeAddress` from
@@ -1974,8 +2253,8 @@ function parseAssetTransferPayload(payload) {
1974
2253
  * missing OP_DROP after payload, bad magic, unsupported pushdata width).
1975
2254
  */
1976
2255
  function splitAssetWrappedScriptPubKey(spkHex) {
1977
- const normalized = ensureHex(spkHex, 'scriptPubKey');
1978
- const bytes = hexToBytes(normalized);
2256
+ const normalized = ensureHex$1(spkHex, 'scriptPubKey');
2257
+ const bytes = hexToBytes$1(normalized);
1979
2258
  const assetOpAt = findTopLevelAssetOpcode(bytes);
1980
2259
  if (assetOpAt < 0) {
1981
2260
  return { prefixHex: normalized, assetTransfer: null };
@@ -1993,12 +2272,12 @@ function splitAssetWrappedScriptPubKey(spkHex) {
1993
2272
  }
1994
2273
  const { assetName, amountRaw, marker } = parseAssetTransferPayload(payload);
1995
2274
  return {
1996
- prefixHex: bytesToHex(prefix),
2275
+ prefixHex: bytesToHex$1(prefix),
1997
2276
  assetTransfer: {
1998
2277
  assetName,
1999
2278
  amountRaw,
2000
2279
  marker,
2001
- payloadHex: bytesToHex(payload),
2280
+ payloadHex: bytesToHex$1(payload),
2002
2281
  },
2003
2282
  };
2004
2283
  }
@@ -2260,7 +2539,7 @@ const INPUT_INDEX_TXHASH_SELECTOR = Uint8Array.of(TXHASH_CURRENT_INDEX, 0x00);
2260
2539
  * `OP_TXHASH(0x0080)` evaluated at input 0:
2261
2540
  * `SHA256(tag || tag || 80 00 || 00 00 00 00)` with `tag = SHA256("NeuraiTxHash")`.
2262
2541
  */
2263
- const INPUT_ZERO_TXHASH = hexToBytes('419632cabaf8bb70b96a8c92c4601a9c2ba11e96841daebc9d98f4835eeb0e36');
2542
+ const INPUT_ZERO_TXHASH = hexToBytes$1('419632cabaf8bb70b96a8c92c4601a9c2ba11e96841daebc9d98f4835eeb0e36');
2264
2543
  function appendPaymentAndBuyerChecks(b, p) {
2265
2544
  // output[0].value >= N * unitPriceSats [ N ]
2266
2545
  b.op(OP_DUP)
@@ -2553,7 +2832,7 @@ function buildPartialFillScript(params) {
2553
2832
  }
2554
2833
  /** Hex convenience wrapper for `buildPartialFillScript`. */
2555
2834
  function buildPartialFillScriptHex(params) {
2556
- return bytesToHex(buildPartialFillScript(params));
2835
+ return bytesToHex$1(buildPartialFillScript(params));
2557
2836
  }
2558
2837
 
2559
2838
  /**
@@ -2660,7 +2939,7 @@ function buildPartialFillScriptPQ(params) {
2660
2939
  return b.build();
2661
2940
  }
2662
2941
  function buildPartialFillScriptPQHex(params) {
2663
- return bytesToHex(buildPartialFillScriptPQ(params));
2942
+ return bytesToHex$1(buildPartialFillScriptPQ(params));
2664
2943
  }
2665
2944
 
2666
2945
  /**
@@ -2717,7 +2996,7 @@ function buildFillScriptSig(amount, total) {
2717
2996
  return b.build();
2718
2997
  }
2719
2998
  function buildFillScriptSigHex(amount, total) {
2720
- return bytesToHex(buildFillScriptSig(amount, total));
2999
+ return bytesToHex$1(buildFillScriptSig(amount, total));
2721
3000
  }
2722
3001
  /**
2723
3002
  * Unlock the covenant via the seller's cancel branch.
@@ -2747,7 +3026,7 @@ function buildCancelScriptSig(signatureDer, pubKey) {
2747
3026
  .build();
2748
3027
  }
2749
3028
  function buildCancelScriptSigHex(signatureDer, pubKey) {
2750
- return bytesToHex(buildCancelScriptSig(signatureDer, pubKey));
3029
+ return bytesToHex$1(buildCancelScriptSig(signatureDer, pubKey));
2751
3030
  }
2752
3031
 
2753
3032
  /**
@@ -2791,7 +3070,7 @@ function buildCancelScriptSigPQ(sigPQ, pubKey) {
2791
3070
  .build();
2792
3071
  }
2793
3072
  function buildCancelScriptSigPQHex(sigPQ, pubKey) {
2794
- return bytesToHex(buildCancelScriptSigPQ(sigPQ, pubKey));
3073
+ return bytesToHex$1(buildCancelScriptSigPQ(sigPQ, pubKey));
2795
3074
  }
2796
3075
 
2797
3076
  /**
@@ -2893,7 +3172,7 @@ function buildCancelWitnessStackPQ(sigPQ, pubKey) {
2893
3172
  * descriptive message if the bytes don't match the partial-fill template.
2894
3173
  */
2895
3174
  function parsePartialFillScript(script, network = 'xna-test') {
2896
- const bytes = typeof script === 'string' ? hexToBytes(script) : script;
3175
+ const bytes = typeof script === 'string' ? hexToBytes$1(script) : script;
2897
3176
  const c = makeCursor(bytes);
2898
3177
  // ═════ Outer IF — Cancel branch ═════
2899
3178
  expectByte(c, OP_IF, 'OP_IF (outer cancel)');
@@ -2917,7 +3196,7 @@ function parsePartialFillScript(script, network = 'xna-test') {
2917
3196
  unitPriceSats: fill.unitPriceSats,
2918
3197
  tokenId: fill.tokenId,
2919
3198
  expiration: fill.expiration,
2920
- scriptHex: bytesToHex(bytes)
3199
+ scriptHex: bytesToHex$1(bytes)
2921
3200
  };
2922
3201
  }
2923
3202
 
@@ -2932,7 +3211,7 @@ function parsePartialFillScript(script, network = 'xna-test') {
2932
3211
  */
2933
3212
  /** Quick discriminator without throwing — useful for indexers. */
2934
3213
  function isPartialFillScriptPQ(script) {
2935
- const bytes = typeof script === 'string' ? hexToBytes(script) : script;
3214
+ const bytes = typeof script === 'string' ? hexToBytes$1(script) : script;
2936
3215
  // PQ cancel starts with: OP_IF OP_DUP OP_SHA256
2937
3216
  return (bytes.length > 3 &&
2938
3217
  bytes[0] === OP_IF &&
@@ -2944,7 +3223,7 @@ function isPartialFillScriptPQ(script) {
2944
3223
  * exact layout produced by `buildPartialFillScriptPQ`.
2945
3224
  */
2946
3225
  function parsePartialFillScriptPQ(script, network = 'xna-test') {
2947
- const bytes = typeof script === 'string' ? hexToBytes(script) : script;
3226
+ const bytes = typeof script === 'string' ? hexToBytes$1(script) : script;
2948
3227
  const c = makeCursor(bytes);
2949
3228
  // ═════ Outer IF — Cancel branch (PQ) ═════
2950
3229
  expectByte(c, OP_IF, 'OP_IF (outer cancel)');
@@ -2979,10 +3258,839 @@ function parsePartialFillScriptPQ(script, network = 'xna-test') {
2979
3258
  txHashSelector,
2980
3259
  expiration: fill.expiration,
2981
3260
  paymentScriptPubKey: fill.paymentScriptPubKey,
2982
- scriptHex: bytesToHex(bytes)
3261
+ scriptHex: bytesToHex$1(bytes)
2983
3262
  };
2984
3263
  }
2985
3264
 
3265
+ /**
3266
+ * NIP-054 P2AH custody policy (`OP_CHECKASSETAUTH`, AuthScript only).
3267
+ *
3268
+ * The policy is the witnessScript of a generic AuthScript v1 (NoAuth)
3269
+ * address. A spend of that address needs M of the N owner-token roles of the
3270
+ * list to approve it (G of them when an owner token held by the custody
3271
+ * leaves it):
3272
+ *
3273
+ * policy: <1> <M> <G> <role_1> ... <role_n> <n> OP_CHECKASSETAUTH
3274
+ * witness: [0x00, <c>, <a>, <b>, <T>, policy]
3275
+ *
3276
+ * Build the four arguments with `buildAssetAuthArgs` and wrap them with
3277
+ * `buildAuthScriptWitnessNoAuth({ args, witnessScript: policy })`. A role
3278
+ * approves either by spending its owner token from P2PKH or a strict
3279
+ * AuthScript address with a SIGHASH_ALL signature (synchronous spend, every
3280
+ * argument 0), or by a vote (see `vote.ts` and `proposal.ts`).
3281
+ */
3282
+ /** The only policy version defined by NIP-054. */
3283
+ const ASSETAUTH_POLICY_VERSION = 1;
3284
+ /** Highest number of roles in one policy. */
3285
+ const ASSETAUTH_MAX_ROLES = 16;
3286
+ /** c, a, b and T are script numbers of at most 4 bytes. */
3287
+ const MAX_ARGUMENT = 0x7fffffff;
3288
+ const encoder = new TextEncoder();
3289
+ const decoder = new TextDecoder();
3290
+ function compareBytes(x, y) {
3291
+ const n = Math.min(x.length, y.length);
3292
+ for (let i = 0; i < n; i += 1) {
3293
+ if (x[i] !== y[i])
3294
+ return x[i] - y[i];
3295
+ }
3296
+ return x.length - y.length;
3297
+ }
3298
+ /** Role names as the node checks them: sorted by bytes, no duplicates. */
3299
+ function sortedRoles(roles) {
3300
+ if (!Array.isArray(roles) || roles.length < 1 || roles.length > ASSETAUTH_MAX_ROLES) {
3301
+ throw new Error(`roles must list 1 to ${ASSETAUTH_MAX_ROLES} owner tokens`);
3302
+ }
3303
+ const names = roles.map((role) => {
3304
+ if (typeof role !== 'string' || !role.endsWith('!')) {
3305
+ throw new Error(`role ${JSON.stringify(role)} is not an owner token name (NAME!)`);
3306
+ }
3307
+ return encoder.encode(role);
3308
+ });
3309
+ names.sort(compareBytes);
3310
+ for (let i = 1; i < names.length; i += 1) {
3311
+ if (compareBytes(names[i - 1], names[i]) === 0) {
3312
+ throw new Error(`role ${decoder.decode(names[i])} is listed twice`);
3313
+ }
3314
+ }
3315
+ return names;
3316
+ }
3317
+ function assertThresholds(M, G, n) {
3318
+ if (!Number.isInteger(M) || !Number.isInteger(G) || M < 1 || M > G || G > n) {
3319
+ throw new Error(`thresholds must satisfy 1 <= M <= G <= ${n} (got M=${M}, G=${G})`);
3320
+ }
3321
+ }
3322
+ function buildAssetAuthPolicyScript(policy) {
3323
+ const roles = sortedRoles(policy.roles);
3324
+ assertThresholds(policy.M, policy.G, roles.length);
3325
+ const b = new ScriptBuilder()
3326
+ .pushInt(ASSETAUTH_POLICY_VERSION)
3327
+ .pushInt(policy.M)
3328
+ .pushInt(policy.G);
3329
+ for (const role of roles)
3330
+ b.pushBytes(role);
3331
+ return b.pushInt(roles.length).op(OP_CHECKASSETAUTH).build();
3332
+ }
3333
+ /** Inverse of `buildAssetAuthPolicyScript`; rejects any other script. */
3334
+ function parseAssetAuthPolicyScript(script) {
3335
+ const end = script.length - 2;
3336
+ const nOp = script[end];
3337
+ if (script.length < 6 || script[end + 1] !== OP_CHECKASSETAUTH || nOp < OP_1 || nOp > OP_16) {
3338
+ throw new Error('parse: not an OP_CHECKASSETAUTH policy script');
3339
+ }
3340
+ const c = makeCursor(script);
3341
+ if (readPushUint8(c, 'version') !== ASSETAUTH_POLICY_VERSION) {
3342
+ throw new Error(`parse: policy version must be ${ASSETAUTH_POLICY_VERSION}`);
3343
+ }
3344
+ const M = readPushUint8(c, 'M');
3345
+ const G = readPushUint8(c, 'G');
3346
+ const names = [];
3347
+ while (c.pos < end)
3348
+ names.push(readPush(c, `role ${names.length + 1}`));
3349
+ if (c.pos !== end || names.length !== nOp - OP_1 + 1) {
3350
+ throw new Error('parse: role count does not match n');
3351
+ }
3352
+ const roles = names.map((name) => decoder.decode(name));
3353
+ const policy = { M, G, roles };
3354
+ // Strictly increasing as written: a re-sorted list would be another script.
3355
+ const rebuilt = buildAssetAuthPolicyScript(policy);
3356
+ if (compareBytes(rebuilt, script) !== 0) {
3357
+ throw new Error('parse: roles are not owner names in strictly increasing byte order');
3358
+ }
3359
+ return policy;
3360
+ }
3361
+ /**
3362
+ * Witness `args` [<c>, <a>, <b>, <T>] for the custody input: minimal script
3363
+ * numbers, 0 as the empty element. All default to 0, the synchronous spend.
3364
+ */
3365
+ function buildAssetAuthArgs({ c = 0, a = 0, b = 0, T = 0 } = {}) {
3366
+ for (const [name, value] of Object.entries({ c, a, b, T })) {
3367
+ if (!Number.isInteger(value) || value < 0 || value > MAX_ARGUMENT) {
3368
+ throw new Error(`${name} must be an integer from 0 to ${MAX_ARGUMENT}`);
3369
+ }
3370
+ }
3371
+ return [c, a, b, T].map((value) => encodeScriptNum(value));
3372
+ }
3373
+
3374
+ // Split a JS number into u32 halves without a BigInt allocation. Exact only for integers
3375
+ // `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below
3376
+ // that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).
3377
+ const fromNumH = (n) => (n / 2 ** 32) | 0;
3378
+ const fromNumL = (n) => n >>> 0;
3379
+ // Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call
3380
+ // BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.
3381
+ function setU64FromNum(view, byteOffset, n, isLE) {
3382
+ const h = fromNumH(n);
3383
+ const l = fromNumL(n);
3384
+ view.setUint32(byteOffset, isLE ? l : h, isLE);
3385
+ view.setUint32(byteOffset + 4, isLE ? h : l, isLE);
3386
+ }
3387
+
3388
+ /**
3389
+ * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
3390
+ * @param a - value to test
3391
+ * @returns `true` when the value is a Uint8Array-compatible view.
3392
+ * @example
3393
+ * Check whether a value is a Uint8Array-compatible view.
3394
+ * ```ts
3395
+ * isBytes(new Uint8Array([1, 2, 3]));
3396
+ * ```
3397
+ */
3398
+ function isBytes(a) {
3399
+ // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.
3400
+ // The fallback still requires a real ArrayBuffer view, so plain
3401
+ // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and
3402
+ // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
3403
+ return (a instanceof Uint8Array ||
3404
+ (ArrayBuffer.isView(a) &&
3405
+ a.constructor.name === 'Uint8Array' &&
3406
+ 'BYTES_PER_ELEMENT' in a &&
3407
+ a.BYTES_PER_ELEMENT === 1));
3408
+ }
3409
+ // Shared error-message prefix builder. Only called on throw paths, so assert
3410
+ // success paths never pay for the string concatenation.
3411
+ const atitle = (title) => (title ? `"${title}" ` : '');
3412
+ /**
3413
+ * Asserts something is Uint8Array.
3414
+ * @param value - value to validate
3415
+ * @param length - optional exact length constraint
3416
+ * @param title - label included in thrown errors
3417
+ * @returns The validated byte array.
3418
+ * @throws On wrong argument types. {@link TypeError}
3419
+ * @throws On wrong argument ranges or values. {@link RangeError}
3420
+ * @example
3421
+ * Validate that a value is a byte array.
3422
+ * ```ts
3423
+ * abytes(new Uint8Array([1, 2, 3]));
3424
+ * ```
3425
+ */
3426
+ function abytes(value, length, title = '') {
3427
+ // Success path first: this runs at the start of every update() / digestInto(), and the
3428
+ // common `abytes(data)` form must not pay for length handling it does not use.
3429
+ if (isBytes(value) && (length === undefined))
3430
+ return value;
3431
+ const bytes = isBytes(value);
3432
+ const ofLen = '';
3433
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
3434
+ const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;
3435
+ if (!bytes)
3436
+ throw new TypeError(message);
3437
+ throw new RangeError(message);
3438
+ }
3439
+ const aobject = (value, label) => {
3440
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
3441
+ throw new TypeError((label === 'object' ? '' : `"${label}" `) + 'expected object, got type=' + typeof value);
3442
+ };
3443
+ const aopts = (value, label) => {
3444
+ aobject(value, label);
3445
+ const proto = Object.getPrototypeOf(value);
3446
+ if (proto !== Object.prototype && proto !== null)
3447
+ throw new TypeError(`"${label}" expected plain object`);
3448
+ // Object.assign() treats an own "__proto__" source key as a write to the target's legacy
3449
+ // prototype setter. Reject it before merging so inherited option values cannot be injected.
3450
+ if (Object.hasOwn(value, '__proto__'))
3451
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
3452
+ };
3453
+ /**
3454
+ * Asserts a hash instance has not been destroyed or finished.
3455
+ * @param instance - hash instance to validate
3456
+ * @param checkFinished - whether to reject finalized instances
3457
+ * @throws If the hash instance has already been destroyed or finalized. {@link Error}
3458
+ * @example
3459
+ * Validate that a hash instance is still usable.
3460
+ * ```ts
3461
+ * import { aexists } from '@noble/hashes/utils.js';
3462
+ * import { sha256 } from '@noble/hashes/sha2.js';
3463
+ * const hash = sha256.create();
3464
+ * aexists(hash);
3465
+ * ```
3466
+ */
3467
+ function aexists(instance, checkFinished = true) {
3468
+ // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their
3469
+ // truthiness is checked - re-validating their type per call was pure hot-path overhead.
3470
+ if (instance.destroyed)
3471
+ throw new Error('hash was destroyed');
3472
+ if (checkFinished && instance.finished)
3473
+ throw new Error('digest() was already called');
3474
+ }
3475
+ /**
3476
+ * Asserts output is a sufficiently-sized byte array.
3477
+ * @param out - destination buffer
3478
+ * @param instance - hash instance providing output length
3479
+ * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
3480
+ * @throws On wrong argument types. {@link TypeError}
3481
+ * @throws On wrong argument ranges or values. {@link RangeError}
3482
+ * @example
3483
+ * Validate a caller-provided digest buffer.
3484
+ * ```ts
3485
+ * import { aoutput } from '@noble/hashes/utils.js';
3486
+ * import { sha256 } from '@noble/hashes/sha2.js';
3487
+ * const hash = sha256.create();
3488
+ * aoutput(new Uint8Array(hash.outputLen), hash);
3489
+ * ```
3490
+ */
3491
+ function aoutput(out, instance) {
3492
+ abytes(out, undefined, 'output');
3493
+ // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast
3494
+ // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.
3495
+ const min = instance.outputLen;
3496
+ if (!(out.length >= min)) {
3497
+ throw new RangeError('"output" expected length >= ' + min);
3498
+ }
3499
+ }
3500
+ /**
3501
+ * Zeroizes typed arrays in place. Warning: JS provides no guarantees.
3502
+ * @param arrays - arrays to overwrite with zeros
3503
+ * @example
3504
+ * Zeroize sensitive buffers in place.
3505
+ * ```ts
3506
+ * clean(new Uint8Array([1, 2, 3]));
3507
+ * ```
3508
+ */
3509
+ function clean(...arrays) {
3510
+ for (let i = 0; i < arrays.length; i++) {
3511
+ arrays[i].fill(0);
3512
+ }
3513
+ }
3514
+ /**
3515
+ * Creates a DataView for byte-level manipulation.
3516
+ * @param arr - source typed array
3517
+ * @returns DataView over the same buffer region.
3518
+ * @example
3519
+ * Create a DataView over an existing buffer.
3520
+ * ```ts
3521
+ * createView(new Uint8Array(4));
3522
+ * ```
3523
+ */
3524
+ function createView(arr) {
3525
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
3526
+ }
3527
+ /**
3528
+ * Rotate-right operation for uint32 values.
3529
+ * @param word - source word
3530
+ * @param shift - shift amount in bits
3531
+ * @returns Rotated word.
3532
+ * @example
3533
+ * Rotate a 32-bit word to the right.
3534
+ * ```ts
3535
+ * rotr(0x12345678, 8);
3536
+ * ```
3537
+ */
3538
+ function rotr(word, shift) {
3539
+ return (word << (32 - shift)) | (word >>> shift);
3540
+ }
3541
+ /**
3542
+ * Merges default options and passed options.
3543
+ * @param defaults - base option object
3544
+ * @param opts - user overrides
3545
+ * @param title - label included in thrown override errors
3546
+ * @returns Fresh merged option object with a null prototype.
3547
+ * @throws On wrong argument types. {@link TypeError}
3548
+ * @example
3549
+ * Merge user overrides onto default options.
3550
+ * ```ts
3551
+ * checkOpts({ dkLen: 32 }, { asyncTick: 10 });
3552
+ * ```
3553
+ */
3554
+ function checkOpts(defaults, opts, title = 'opts') {
3555
+ aopts(defaults, 'defaults');
3556
+ if (opts !== undefined)
3557
+ aopts(opts, title);
3558
+ // Callers read optional fields directly, so omitted values must not fall through to ambient
3559
+ // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).
3560
+ const merged = Object.assign(Object.create(null), defaults, opts);
3561
+ return merged;
3562
+ }
3563
+ /**
3564
+ * Creates a callable hash function from a stateful class constructor.
3565
+ * @param hashCons - hash constructor or factory
3566
+ * @param info - optional metadata such as DER OID
3567
+ * @returns Frozen callable hash wrapper with `.create()`.
3568
+ * Wrapper construction eagerly calls `hashCons(undefined)` once to read
3569
+ * `outputLen` / `blockLen`, so constructor side effects happen at module
3570
+ * init time.
3571
+ * @throws On wrong argument types. {@link TypeError}
3572
+ * @example
3573
+ * Wrap a stateful hash constructor into a callable helper.
3574
+ * ```ts
3575
+ * import { createHasher } from '@noble/hashes/utils.js';
3576
+ * import { sha256 } from '@noble/hashes/sha2.js';
3577
+ * const wrapped = createHasher(sha256.create, { oid: sha256.oid });
3578
+ * wrapped(new Uint8Array([1]));
3579
+ * ```
3580
+ */
3581
+ function createHasher(hashCons, info = {}) {
3582
+ if (typeof hashCons !== 'function')
3583
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
3584
+ info = checkOpts({}, info, 'info');
3585
+ const hashC = (msg, opts) => hashCons(opts)
3586
+ .update(msg)
3587
+ .digest();
3588
+ const tmp = hashCons(undefined);
3589
+ hashC.outputLen = tmp.outputLen;
3590
+ hashC.blockLen = tmp.blockLen;
3591
+ hashC.canXOF = tmp.canXOF;
3592
+ hashC.create = (opts) => hashCons(opts);
3593
+ Object.assign(hashC, info);
3594
+ return Object.freeze(hashC);
3595
+ }
3596
+ /**
3597
+ * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
3598
+ * @param suffix - final OID byte for the selected hash.
3599
+ * The helper accepts any byte even though only the documented NIST hash
3600
+ * suffixes are meaningful downstream.
3601
+ * @returns Object containing the DER-encoded OID.
3602
+ * @example
3603
+ * Build OID metadata for a NIST hash.
3604
+ * ```ts
3605
+ * oidNist(0x01);
3606
+ * ```
3607
+ */
3608
+ const oidNist = (suffix) => ({
3609
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
3610
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
3611
+ oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),
3612
+ });
3613
+
3614
+ /**
3615
+ * Internal Merkle-Damgard hash utils.
3616
+ * @module
3617
+ */
3618
+ /**
3619
+ * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
3620
+ * Returns bits from `b` when `a` is set, otherwise from `c`.
3621
+ * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
3622
+ * set the same bit.
3623
+ * @param a - selector word
3624
+ * @param b - word chosen when selector bit is set
3625
+ * @param c - word chosen when selector bit is clear
3626
+ * @returns Mixed 32-bit word.
3627
+ * @example
3628
+ * Combine three words with the shared 32-bit choice primitive.
3629
+ * ```ts
3630
+ * Chi(0xffffffff, 0x12345678, 0x87654321);
3631
+ * ```
3632
+ */
3633
+ function Chi(a, b, c) {
3634
+ return (a & b) ^ (~a & c);
3635
+ }
3636
+ /**
3637
+ * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
3638
+ * Returns bits shared by at least two inputs.
3639
+ * @param a - first input word
3640
+ * @param b - second input word
3641
+ * @param c - third input word
3642
+ * @returns Mixed 32-bit word.
3643
+ * @example
3644
+ * Combine three words with the shared 32-bit majority primitive.
3645
+ * ```ts
3646
+ * Maj(0xffffffff, 0x12345678, 0x87654321);
3647
+ * ```
3648
+ */
3649
+ function Maj(a, b, c) {
3650
+ return (a & b) ^ (a & c) ^ (b & c);
3651
+ }
3652
+ /**
3653
+ * Merkle-Damgard hash construction base class.
3654
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
3655
+ * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
3656
+ * strings with partial-byte tails.
3657
+ * @param blockLen - internal block size in bytes
3658
+ * @param outputLen - digest size in bytes
3659
+ * @param padOffset - trailing length field size in bytes
3660
+ * @param isLE - whether length and state words are encoded in little-endian
3661
+ * @example
3662
+ * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
3663
+ * ```ts
3664
+ * import { _SHA1 } from '@noble/hashes/legacy.js';
3665
+ * const hash = new _SHA1();
3666
+ * hash.update(new Uint8Array([97, 98, 99]));
3667
+ * hash.digest();
3668
+ * ```
3669
+ */
3670
+ class HashMD {
3671
+ blockLen;
3672
+ outputLen;
3673
+ canXOF = false;
3674
+ padOffset;
3675
+ isLE;
3676
+ // For partial updates less than block size
3677
+ buffer;
3678
+ view;
3679
+ finished = false;
3680
+ length = 0;
3681
+ pos = 0;
3682
+ destroyed = false;
3683
+ constructor(blockLen, outputLen, padOffset, isLE) {
3684
+ this.blockLen = blockLen;
3685
+ this.outputLen = outputLen;
3686
+ this.padOffset = padOffset;
3687
+ this.isLE = isLE;
3688
+ this.buffer = new Uint8Array(blockLen);
3689
+ this.view = createView(this.buffer);
3690
+ }
3691
+ update(data) {
3692
+ aexists(this);
3693
+ abytes(data);
3694
+ const { view, buffer, blockLen } = this;
3695
+ const len = data.length;
3696
+ let processed = false;
3697
+ for (let pos = 0; pos < len;) {
3698
+ const take = Math.min(blockLen - this.pos, len - pos);
3699
+ // Fast path only when there is no buffered partial block: `take === blockLen` implies
3700
+ // `this.pos === 0`, so we can process full blocks directly from the input view.
3701
+ if (take === blockLen) {
3702
+ const dataView = createView(data);
3703
+ for (; blockLen <= len - pos; pos += blockLen)
3704
+ this.process(dataView, pos);
3705
+ processed = true;
3706
+ continue;
3707
+ }
3708
+ // When the whole input is buffered in one go (common for short messages), passing `data`
3709
+ // directly avoids allocating a subarray view.
3710
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
3711
+ this.pos += take;
3712
+ pos += take;
3713
+ if (this.pos === blockLen) {
3714
+ this.process(view, 0);
3715
+ this.pos = 0;
3716
+ processed = true;
3717
+ }
3718
+ }
3719
+ this.length += data.length;
3720
+ // Shared schedule buffers only pick up input-derived words inside process(); if everything
3721
+ // was buffered without processing, there is nothing to zero.
3722
+ if (processed)
3723
+ this.roundClean();
3724
+ return this;
3725
+ }
3726
+ digestInto(out) {
3727
+ aexists(this);
3728
+ aoutput(out, this);
3729
+ this.finished = true;
3730
+ // Padding
3731
+ // We can avoid allocation of buffer for padding completely if it
3732
+ // was previously not allocated here. But it won't change performance.
3733
+ const { buffer, view, blockLen, isLE } = this;
3734
+ let { pos } = this;
3735
+ // append the bit '1' to the message, then zero-pad the rest of the block
3736
+ buffer[pos++] = 0b10000000;
3737
+ buffer.fill(0, pos);
3738
+ // we have less than padOffset left in buffer, so we cannot put length in
3739
+ // current block, need process it and pad again
3740
+ if (this.padOffset > blockLen - pos) {
3741
+ this.process(view, 0);
3742
+ buffer.fill(0);
3743
+ }
3744
+ // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from
3745
+ // the padding fill above, and JS will overflow before user input can make that half non-zero.
3746
+ // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an
3747
+ // integer below 2**53, so the split inside the helper stays exact).
3748
+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
3749
+ this.process(view, 0);
3750
+ // The final block above is processed outside update(), so the shared message-schedule
3751
+ // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().
3752
+ this.roundClean();
3753
+ // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.
3754
+ const oview = out === buffer ? view : createView(out);
3755
+ const len = this.outputLen;
3756
+ // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT
3757
+ const outLen = len / 4;
3758
+ const state = this.get();
3759
+ // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.
3760
+ if (len % 4 || outLen > state.length)
3761
+ throw new Error('invalid outputLen');
3762
+ for (let i = 0; i < outLen; i++)
3763
+ oview.setUint32(4 * i, state[i], isLE);
3764
+ }
3765
+ digest() {
3766
+ const { buffer, outputLen } = this;
3767
+ this.digestInto(buffer);
3768
+ // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return
3769
+ // fresh bytes to the caller.
3770
+ const res = buffer.slice(0, outputLen);
3771
+ this.destroy();
3772
+ return res;
3773
+ }
3774
+ _cloneIntoMeta(to) {
3775
+ const { buffer, length, finished, destroyed, pos } = this;
3776
+ to.destroyed = destroyed;
3777
+ to.finished = finished;
3778
+ to.length = length;
3779
+ to.pos = pos;
3780
+ // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and
3781
+ // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.
3782
+ if (pos)
3783
+ to.buffer.set(buffer); // Avoid a hot modulo guard.
3784
+ return to;
3785
+ }
3786
+ clone() {
3787
+ return this._cloneInto();
3788
+ }
3789
+ }
3790
+ /**
3791
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
3792
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
3793
+ */
3794
+ /** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
3795
+ * square roots of the first eight prime numbers. Exported as a shared table; callers must treat
3796
+ * it as read-only because constructors copy words from it by index. */
3797
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
3798
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
3799
+ ]);
3800
+
3801
+ /**
3802
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
3803
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
3804
+ * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
3805
+ * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
3806
+ * @module
3807
+ */
3808
+ /**
3809
+ * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits
3810
+ * of the cube roots of the first 64 primes (2..311).
3811
+ */
3812
+ // prettier-ignore
3813
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
3814
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
3815
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
3816
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
3817
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
3818
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
3819
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
3820
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
3821
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
3822
+ ]);
3823
+ /** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */
3824
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
3825
+ /** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */
3826
+ class SHA2_32B extends HashMD {
3827
+ // We cannot use array here since array allows indexing by variable
3828
+ // which means optimizer/compiler cannot use registers.
3829
+ // Numeric initializers matter: starting the fields as `undefined` changes
3830
+ // V8's field representation and makes sha256 3x slower (measured).
3831
+ A = 0;
3832
+ B = 0;
3833
+ C = 0;
3834
+ D = 0;
3835
+ E = 0;
3836
+ F = 0;
3837
+ G = 0;
3838
+ H = 0;
3839
+ constructor(outputLen, IV) {
3840
+ super(64, outputLen, 8, false);
3841
+ this.A = IV[0] | 0;
3842
+ this.B = IV[1] | 0;
3843
+ this.C = IV[2] | 0;
3844
+ this.D = IV[3] | 0;
3845
+ this.E = IV[4] | 0;
3846
+ this.F = IV[5] | 0;
3847
+ this.G = IV[6] | 0;
3848
+ this.H = IV[7] | 0;
3849
+ }
3850
+ get() {
3851
+ const { A, B, C, D, E, F, G, H } = this;
3852
+ return [A, B, C, D, E, F, G, H];
3853
+ }
3854
+ // prettier-ignore
3855
+ set(A, B, C, D, E, F, G, H) {
3856
+ this.A = A | 0;
3857
+ this.B = B | 0;
3858
+ this.C = C | 0;
3859
+ this.D = D | 0;
3860
+ this.E = E | 0;
3861
+ this.F = F | 0;
3862
+ this.G = G | 0;
3863
+ this.H = H | 0;
3864
+ }
3865
+ _cloneInto(to) {
3866
+ (to ||= new this.constructor()).set(...this.get());
3867
+ return this._cloneIntoMeta(to);
3868
+ }
3869
+ process(view, offset) {
3870
+ // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
3871
+ for (let i = 0; i < 16; i++, offset += 4)
3872
+ SHA256_W[i] = view.getUint32(offset, false);
3873
+ for (let i = 16; i < 64; i++) {
3874
+ const W15 = SHA256_W[i - 15];
3875
+ const W2 = SHA256_W[i - 2];
3876
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
3877
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
3878
+ SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
3879
+ }
3880
+ // Compression function main loop, 64 rounds
3881
+ let { A, B, C, D, E, F, G, H } = this;
3882
+ for (let i = 0; i < 64; i++) {
3883
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
3884
+ const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
3885
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
3886
+ const T2 = (sigma0 + Maj(A, B, C)) | 0;
3887
+ H = G;
3888
+ G = F;
3889
+ F = E;
3890
+ E = (D + T1) | 0;
3891
+ D = C;
3892
+ C = B;
3893
+ B = A;
3894
+ A = (T1 + T2) | 0;
3895
+ }
3896
+ // Add the compressed chunk to the current hash value
3897
+ A = (A + this.A) | 0;
3898
+ B = (B + this.B) | 0;
3899
+ C = (C + this.C) | 0;
3900
+ D = (D + this.D) | 0;
3901
+ E = (E + this.E) | 0;
3902
+ F = (F + this.F) | 0;
3903
+ G = (G + this.G) | 0;
3904
+ H = (H + this.H) | 0;
3905
+ this.set(A, B, C, D, E, F, G, H);
3906
+ }
3907
+ roundClean() {
3908
+ clean(SHA256_W);
3909
+ }
3910
+ destroy() {
3911
+ // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves
3912
+ // update()/digest() callable on reused instances.
3913
+ this.destroyed = true;
3914
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
3915
+ clean(this.buffer);
3916
+ }
3917
+ }
3918
+ /** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
3919
+ class _SHA256 extends SHA2_32B {
3920
+ constructor() {
3921
+ super(32, SHA256_IV);
3922
+ }
3923
+ }
3924
+ /**
3925
+ * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
3926
+ *
3927
+ * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
3928
+ * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
3929
+ * - Each sha256 hash is executing 2^18 bit operations.
3930
+ * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
3931
+ * @param msg - message bytes to hash
3932
+ * @param opts - Reserved hash options.
3933
+ * @returns Digest bytes.
3934
+ * @example
3935
+ * Hash a message with SHA2-256.
3936
+ * ```ts
3937
+ * sha256(new Uint8Array([97, 98, 99]));
3938
+ * ```
3939
+ */
3940
+ const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(),
3941
+ /* @__PURE__ */ oidNist(0x01));
3942
+
3943
+ /**
3944
+ * NIP-054 proposal hash H, the message a vote carries.
3945
+ *
3946
+ * H = TaggedHash("NeuraiAssetAuthProposal", m)
3947
+ * m = chainId (u8) || nVersion (i32) || nLockTime (u32) || T (u32)
3948
+ * || compact(c) || compact(a) || compact(b)
3949
+ * || (outpoint, nSequence) of inputs 0..c-1
3950
+ * || outputs 0..a-1 || the last b outputs
3951
+ * || compact(#refs) || reference inputs (version 3 only)
3952
+ *
3953
+ * Inputs from index c on and the outputs between the prefix and the suffix
3954
+ * (approvals, returns, fees, change) are left to the executor, so a skeleton
3955
+ * transaction with only the proposal inputs and outputs gives the same H as
3956
+ * the execution. Votes carry H as is, as the 32-byte (64-hex) message of
3957
+ * their owner-token transfer: `bytesToHex(hash)`.
3958
+ */
3959
+ /** The chain identifier the node commits to (OP_CHAINCONTEXT selector 0x03). */
3960
+ const ASSETAUTH_CHAIN_IDS = Object.freeze({
3961
+ mainnet: 0,
3962
+ testnet: 1,
3963
+ regtest: 2
3964
+ });
3965
+ const PROPOSAL_TAG = new TextEncoder().encode('NeuraiAssetAuthProposal');
3966
+ function u32(value) {
3967
+ const out = new Uint8Array(4);
3968
+ new DataView(out.buffer).setUint32(0, value >>> 0, true);
3969
+ return out;
3970
+ }
3971
+ function compactSize(value) {
3972
+ if (value < 0xfd)
3973
+ return Uint8Array.of(value);
3974
+ if (value <= 0xffff)
3975
+ return Uint8Array.of(0xfd, value & 0xff, value >> 8);
3976
+ return concatBytes$1(Uint8Array.of(0xfe), u32(value));
3977
+ }
3978
+ /** A display-order txid and vout as the node serializes a COutPoint. */
3979
+ function outpoint(txid, vout) {
3980
+ return concatBytes$1(hexToBytes$1(txid).reverse(), u32(vout));
3981
+ }
3982
+ function buildAssetAuthProposalMessage(proposal) {
3983
+ const { c, a, b, T } = proposal;
3984
+ const chainId = ASSETAUTH_CHAIN_IDS[proposal.chain];
3985
+ if (chainId === undefined) {
3986
+ throw new Error(`unknown chain ${JSON.stringify(proposal.chain)}`);
3987
+ }
3988
+ for (const [name, value] of Object.entries({ c, a, b, T })) {
3989
+ if (!Number.isInteger(value) || value < 0 || value > 0x7fffffff) {
3990
+ throw new Error(`${name} must be an integer from 0 to ${0x7fffffff}`);
3991
+ }
3992
+ }
3993
+ const tx = parseTransaction(proposal.rawTx);
3994
+ if (c > tx.inputs.length) {
3995
+ throw new Error(`c (${c}) exceeds the ${tx.inputs.length} inputs of the transaction`);
3996
+ }
3997
+ if (a + b > tx.outputs.length) {
3998
+ throw new Error(`a + b (${a + b}) exceeds the ${tx.outputs.length} outputs of the transaction`);
3999
+ }
4000
+ const version = new Uint8Array(4);
4001
+ new DataView(version.buffer).setInt32(0, tx.version, true);
4002
+ const parts = [Uint8Array.of(chainId), version, u32(tx.locktime), u32(T), compactSize(c), compactSize(a), compactSize(b)];
4003
+ for (const input of tx.inputs.slice(0, c)) {
4004
+ parts.push(outpoint(input.txid, input.vout), u32(input.sequence));
4005
+ }
4006
+ for (const output of [...tx.outputs.slice(0, a), ...tx.outputs.slice(tx.outputs.length - b)]) {
4007
+ parts.push(serializeOutput(output));
4008
+ }
4009
+ const refs = tx.version === 3 ? tx.vrefin : [];
4010
+ parts.push(compactSize(refs.length));
4011
+ for (const ref of refs)
4012
+ parts.push(outpoint(ref.txid, ref.vout));
4013
+ return concatBytes$1(...parts);
4014
+ }
4015
+ /** H: 32 bytes, in the order a vote carries it. */
4016
+ function assetAuthProposalHash(proposal) {
4017
+ const tag = sha256(PROPOSAL_TAG);
4018
+ return sha256(concatBytes$1(tag, tag, buildAssetAuthProposalMessage(proposal)));
4019
+ }
4020
+
4021
+ /**
4022
+ * NIP-054 vote lock: a wallet template (not part of the opcode) that holds a
4023
+ * role's owner token while it votes for a proposal.
4024
+ *
4025
+ * The holder sends the owner token, with the proposal hash H as its transfer
4026
+ * message, to the generic AuthScript v1 (NoAuth) address of this script:
4027
+ *
4028
+ * OP_IF execute, up to height T
4029
+ * OP_1 OP_CHAINCONTEXT <T> OP_LESSTHANOREQUAL OP_VERIFY
4030
+ * OP_SWAP OP_4 OP_INPUTFIELD <0x01 || C> OP_EQUALVERIFY
4031
+ * OP_OUTPUTSCRIPT <return> OP_EQUAL
4032
+ * OP_ELSE give it back, after T
4033
+ * OP_1 OP_CHAINCONTEXT <T> OP_GREATERTHAN OP_VERIFY
4034
+ * OP_NIP OP_OUTPUTSCRIPT <return> OP_EQUAL
4035
+ * OP_ENDIF
4036
+ *
4037
+ * Both branches send the token back to its owner (`return`, the full output
4038
+ * script). The execute branch also needs the custody, commitment C, at the
4039
+ * input it names. It must use OP_INPUTFIELD selector 04, the full
4040
+ * version-plus-commitment: selector 02 only reads the first 34 bytes of the
4041
+ * spent script, which a forged anyone-can-spend custody can match.
4042
+ */
4043
+ /** OP_INPUTFIELD selector: the full version-plus-commitment of the spent script. */
4044
+ const INPUTFIELD_AUTHSCRIPT_DESTINATION = 0x04;
4045
+ const AUTHSCRIPT_V1 = 0x01;
4046
+ function asBytes(value) {
4047
+ return typeof value === 'string' ? hexToBytes$1(value) : value;
4048
+ }
4049
+ function assertIndex(name, value) {
4050
+ if (!Number.isInteger(value) || value < 0 || value > 0x7fffffff) {
4051
+ throw new Error(`${name} must be an integer from 0 to ${0x7fffffff}`);
4052
+ }
4053
+ }
4054
+ function buildAssetAuthVoteLockScript(params) {
4055
+ assertIndex('T', params.T);
4056
+ const commitment = asBytes(params.custodyCommitment);
4057
+ if (commitment.length !== 32) {
4058
+ throw new Error(`custodyCommitment must be 32 bytes (got ${commitment.length})`);
4059
+ }
4060
+ const returnScript = asBytes(params.returnScriptPubKey);
4061
+ if (returnScript.length === 0) {
4062
+ throw new Error('returnScriptPubKey must not be empty');
4063
+ }
4064
+ return new ScriptBuilder()
4065
+ .op(OP_IF)
4066
+ .pushInt(CHAINCONTEXT_HEIGHT).op(OP_CHAINCONTEXT).pushInt(params.T).op(OP_LESSTHANOREQUAL, OP_VERIFY)
4067
+ .op(OP_SWAP).pushInt(INPUTFIELD_AUTHSCRIPT_DESTINATION).op(OP_INPUTFIELD)
4068
+ .pushBytes(concatBytes$1(Uint8Array.of(AUTHSCRIPT_V1), commitment)).op(OP_EQUALVERIFY)
4069
+ .op(OP_OUTPUTSCRIPT).pushBytes(returnScript).op(OP_EQUAL)
4070
+ .op(OP_ELSE)
4071
+ .pushInt(CHAINCONTEXT_HEIGHT).op(OP_CHAINCONTEXT).pushInt(params.T).op(OP_GREATERTHAN, OP_VERIFY)
4072
+ .op(OP_NIP, OP_OUTPUTSCRIPT).pushBytes(returnScript).op(OP_EQUAL)
4073
+ .op(OP_ENDIF)
4074
+ .build();
4075
+ }
4076
+ /**
4077
+ * Witness `args` of the execute branch: the index of the custody input and
4078
+ * the index of the output that returns the token.
4079
+ */
4080
+ function buildAssetAuthVoteExecuteArgs(params) {
4081
+ assertIndex('custodyInput', params.custodyInput);
4082
+ assertIndex('returnOutput', params.returnOutput);
4083
+ return [encodeScriptNum(params.custodyInput), encodeScriptNum(params.returnOutput), encodeScriptNum(1)];
4084
+ }
4085
+ /** Witness `args` of the return branch, after T. */
4086
+ function buildAssetAuthVoteReturnArgs(params) {
4087
+ assertIndex('returnOutput', params.returnOutput);
4088
+ return [encodeScriptNum(0), encodeScriptNum(params.returnOutput), encodeScriptNum(0)];
4089
+ }
4090
+
4091
+ exports.ASSETAUTH_CHAIN_IDS = ASSETAUTH_CHAIN_IDS;
4092
+ exports.ASSETAUTH_MAX_ROLES = ASSETAUTH_MAX_ROLES;
4093
+ exports.ASSETAUTH_POLICY_VERSION = ASSETAUTH_POLICY_VERSION;
2986
4094
  exports.AUTHSCRIPT_LEGACY = AUTHSCRIPT_LEGACY;
2987
4095
  exports.AUTHSCRIPT_NOAUTH = AUTHSCRIPT_NOAUTH;
2988
4096
  exports.AUTHSCRIPT_PQ = AUTHSCRIPT_PQ;
@@ -2993,6 +4101,13 @@ exports.NULLDATA_STANDARD_MAX_SIZE = NULLDATA_STANDARD_MAX_SIZE;
2993
4101
  exports.PQ_PUBKEY_PREFIX = PQ_PUBKEY_PREFIX;
2994
4102
  exports.STRICT_PQ_PUBKEY_LENGTH = STRICT_PQ_PUBKEY_LENGTH;
2995
4103
  exports.ScriptBuilder = ScriptBuilder;
4104
+ exports.assetAuthProposalHash = assetAuthProposalHash;
4105
+ exports.buildAssetAuthArgs = buildAssetAuthArgs;
4106
+ exports.buildAssetAuthPolicyScript = buildAssetAuthPolicyScript;
4107
+ exports.buildAssetAuthProposalMessage = buildAssetAuthProposalMessage;
4108
+ exports.buildAssetAuthVoteExecuteArgs = buildAssetAuthVoteExecuteArgs;
4109
+ exports.buildAssetAuthVoteLockScript = buildAssetAuthVoteLockScript;
4110
+ exports.buildAssetAuthVoteReturnArgs = buildAssetAuthVoteReturnArgs;
2996
4111
  exports.buildAuthScriptWitnessLegacy = buildAuthScriptWitnessLegacy;
2997
4112
  exports.buildAuthScriptWitnessNoAuth = buildAuthScriptWitnessNoAuth;
2998
4113
  exports.buildAuthScriptWitnessPQ = buildAuthScriptWitnessPQ;
@@ -3013,8 +4128,8 @@ exports.buildPartialFillScriptPQHex = buildPartialFillScriptPQHex;
3013
4128
  exports.buildStrictWitnessECDSA = buildStrictWitnessECDSA;
3014
4129
  exports.buildStrictWitnessPQ = buildStrictWitnessPQ;
3015
4130
  exports.bytesEqual = bytesEqual;
3016
- exports.bytesToHex = bytesToHex;
3017
- exports.concatBytes = concatBytes;
4131
+ exports.bytesToHex = bytesToHex$1;
4132
+ exports.concatBytes = concatBytes$1;
3018
4133
  exports.encodeAuthScriptScriptPubKey = encodeAuthScriptScriptPubKey;
3019
4134
  exports.encodeMultisigRedeemScript = encodeMultisigRedeemScript;
3020
4135
  exports.encodeMultisigRedeemScriptHex = encodeMultisigRedeemScriptHex;
@@ -3025,10 +4140,11 @@ exports.encodeP2WPKHScriptPubKey = encodeP2WPKHScriptPubKey;
3025
4140
  exports.encodeP2WSHScriptPubKey = encodeP2WSHScriptPubKey;
3026
4141
  exports.encodeScriptNum = encodeScriptNum;
3027
4142
  exports.encodeSellerScriptPubKey = encodeSellerScriptPubKey;
3028
- exports.ensureHex = ensureHex;
3029
- exports.hexToBytes = hexToBytes;
4143
+ exports.ensureHex = ensureHex$1;
4144
+ exports.hexToBytes = hexToBytes$1;
3030
4145
  exports.isPartialFillScriptPQ = isPartialFillScriptPQ;
3031
4146
  exports.opcodes = opcodes;
4147
+ exports.parseAssetAuthPolicyScript = parseAssetAuthPolicyScript;
3032
4148
  exports.parsePartialFillScript = parsePartialFillScript;
3033
4149
  exports.parsePartialFillScriptPQ = parsePartialFillScriptPQ;
3034
4150
  exports.pushBytes = pushBytes;