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