@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.
@@ -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,192 @@ 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: reference inputs sit between vout and witness, announced by flag
1990
+ // 0x02. Without the flag a version 3 transaction reads as 1.0.7 reads it.
1991
+ const vrefin = [];
1992
+ const hasRefInputs = (flags & 2) !== 0;
1993
+ if (hasRefInputs) {
1994
+ flags ^= 2;
1995
+ const refCount = reader.readCount(36, 'refinput');
1996
+ for (let i = 0; i < refCount; i += 1)
1997
+ vrefin.push(readOutpoint(reader));
1998
+ if (vrefin.length === 0) {
1999
+ // One encoding per transaction: the flag means some.
2000
+ throw new Error('Superfluous reference inputs record (flag 0x02 with no reference inputs)');
2001
+ }
2002
+ }
2003
+ if (flags & 1) {
2004
+ flags ^= 1;
2005
+ for (const input of inputs) {
2006
+ const stackSize = reader.readCount(1, 'witness element');
2007
+ const stack = [];
2008
+ for (let i = 0; i < stackSize; i += 1) {
2009
+ const elementLength = reader.readCount(1, 'witness bytes');
2010
+ stack.push(bytesToHex(reader.readBytes(elementLength)));
2011
+ }
2012
+ input.witness = stack;
2013
+ }
2014
+ if (hasRefInputs && !inputs.some(inputHasWitness)) {
2015
+ // With reference inputs the witness flag means some witness; 1.0.7 reads
2016
+ // an empty witness record without them, and so does the node.
2017
+ throw new Error('Superfluous witness record (flag 0x01 with no witness data)');
2018
+ }
2019
+ }
2020
+ if (flags) {
2021
+ throw new Error(`Unknown transaction optional data (flags 0x${flags.toString(16)})`);
2022
+ }
2023
+ const locktime = reader.readU32();
2024
+ if (!reader.finished) {
2025
+ throw new Error(`Trailing bytes after transaction (offset ${reader.position})`);
2026
+ }
2027
+ return { version, inputs, outputs, vrefin, locktime };
2028
+ }
2029
+ function inputHasWitness(input) {
2030
+ return (input.witness?.length ?? 0) > 0;
2031
+ }
1753
2032
 
1754
2033
  /**
1755
2034
  * Address helpers. Wraps `decodeAddress` from
@@ -1975,8 +2254,8 @@ var NeuraiScriptsBundle = (function (exports) {
1975
2254
  * missing OP_DROP after payload, bad magic, unsupported pushdata width).
1976
2255
  */
1977
2256
  function splitAssetWrappedScriptPubKey(spkHex) {
1978
- const normalized = ensureHex(spkHex, 'scriptPubKey');
1979
- const bytes = hexToBytes(normalized);
2257
+ const normalized = ensureHex$1(spkHex, 'scriptPubKey');
2258
+ const bytes = hexToBytes$1(normalized);
1980
2259
  const assetOpAt = findTopLevelAssetOpcode(bytes);
1981
2260
  if (assetOpAt < 0) {
1982
2261
  return { prefixHex: normalized, assetTransfer: null };
@@ -1994,12 +2273,12 @@ var NeuraiScriptsBundle = (function (exports) {
1994
2273
  }
1995
2274
  const { assetName, amountRaw, marker } = parseAssetTransferPayload(payload);
1996
2275
  return {
1997
- prefixHex: bytesToHex(prefix),
2276
+ prefixHex: bytesToHex$1(prefix),
1998
2277
  assetTransfer: {
1999
2278
  assetName,
2000
2279
  amountRaw,
2001
2280
  marker,
2002
- payloadHex: bytesToHex(payload),
2281
+ payloadHex: bytesToHex$1(payload),
2003
2282
  },
2004
2283
  };
2005
2284
  }
@@ -2261,7 +2540,7 @@ var NeuraiScriptsBundle = (function (exports) {
2261
2540
  * `OP_TXHASH(0x0080)` evaluated at input 0:
2262
2541
  * `SHA256(tag || tag || 80 00 || 00 00 00 00)` with `tag = SHA256("NeuraiTxHash")`.
2263
2542
  */
2264
- const INPUT_ZERO_TXHASH = hexToBytes('419632cabaf8bb70b96a8c92c4601a9c2ba11e96841daebc9d98f4835eeb0e36');
2543
+ const INPUT_ZERO_TXHASH = hexToBytes$1('419632cabaf8bb70b96a8c92c4601a9c2ba11e96841daebc9d98f4835eeb0e36');
2265
2544
  function appendPaymentAndBuyerChecks(b, p) {
2266
2545
  // output[0].value >= N * unitPriceSats [ N ]
2267
2546
  b.op(OP_DUP)
@@ -2554,7 +2833,7 @@ var NeuraiScriptsBundle = (function (exports) {
2554
2833
  }
2555
2834
  /** Hex convenience wrapper for `buildPartialFillScript`. */
2556
2835
  function buildPartialFillScriptHex(params) {
2557
- return bytesToHex(buildPartialFillScript(params));
2836
+ return bytesToHex$1(buildPartialFillScript(params));
2558
2837
  }
2559
2838
 
2560
2839
  /**
@@ -2661,7 +2940,7 @@ var NeuraiScriptsBundle = (function (exports) {
2661
2940
  return b.build();
2662
2941
  }
2663
2942
  function buildPartialFillScriptPQHex(params) {
2664
- return bytesToHex(buildPartialFillScriptPQ(params));
2943
+ return bytesToHex$1(buildPartialFillScriptPQ(params));
2665
2944
  }
2666
2945
 
2667
2946
  /**
@@ -2718,7 +2997,7 @@ var NeuraiScriptsBundle = (function (exports) {
2718
2997
  return b.build();
2719
2998
  }
2720
2999
  function buildFillScriptSigHex(amount, total) {
2721
- return bytesToHex(buildFillScriptSig(amount, total));
3000
+ return bytesToHex$1(buildFillScriptSig(amount, total));
2722
3001
  }
2723
3002
  /**
2724
3003
  * Unlock the covenant via the seller's cancel branch.
@@ -2748,7 +3027,7 @@ var NeuraiScriptsBundle = (function (exports) {
2748
3027
  .build();
2749
3028
  }
2750
3029
  function buildCancelScriptSigHex(signatureDer, pubKey) {
2751
- return bytesToHex(buildCancelScriptSig(signatureDer, pubKey));
3030
+ return bytesToHex$1(buildCancelScriptSig(signatureDer, pubKey));
2752
3031
  }
2753
3032
 
2754
3033
  /**
@@ -2792,7 +3071,7 @@ var NeuraiScriptsBundle = (function (exports) {
2792
3071
  .build();
2793
3072
  }
2794
3073
  function buildCancelScriptSigPQHex(sigPQ, pubKey) {
2795
- return bytesToHex(buildCancelScriptSigPQ(sigPQ, pubKey));
3074
+ return bytesToHex$1(buildCancelScriptSigPQ(sigPQ, pubKey));
2796
3075
  }
2797
3076
 
2798
3077
  /**
@@ -2894,7 +3173,7 @@ var NeuraiScriptsBundle = (function (exports) {
2894
3173
  * descriptive message if the bytes don't match the partial-fill template.
2895
3174
  */
2896
3175
  function parsePartialFillScript(script, network = 'xna-test') {
2897
- const bytes = typeof script === 'string' ? hexToBytes(script) : script;
3176
+ const bytes = typeof script === 'string' ? hexToBytes$1(script) : script;
2898
3177
  const c = makeCursor(bytes);
2899
3178
  // ═════ Outer IF — Cancel branch ═════
2900
3179
  expectByte(c, OP_IF, 'OP_IF (outer cancel)');
@@ -2918,7 +3197,7 @@ var NeuraiScriptsBundle = (function (exports) {
2918
3197
  unitPriceSats: fill.unitPriceSats,
2919
3198
  tokenId: fill.tokenId,
2920
3199
  expiration: fill.expiration,
2921
- scriptHex: bytesToHex(bytes)
3200
+ scriptHex: bytesToHex$1(bytes)
2922
3201
  };
2923
3202
  }
2924
3203
 
@@ -2933,7 +3212,7 @@ var NeuraiScriptsBundle = (function (exports) {
2933
3212
  */
2934
3213
  /** Quick discriminator without throwing — useful for indexers. */
2935
3214
  function isPartialFillScriptPQ(script) {
2936
- const bytes = typeof script === 'string' ? hexToBytes(script) : script;
3215
+ const bytes = typeof script === 'string' ? hexToBytes$1(script) : script;
2937
3216
  // PQ cancel starts with: OP_IF OP_DUP OP_SHA256
2938
3217
  return (bytes.length > 3 &&
2939
3218
  bytes[0] === OP_IF &&
@@ -2945,7 +3224,7 @@ var NeuraiScriptsBundle = (function (exports) {
2945
3224
  * exact layout produced by `buildPartialFillScriptPQ`.
2946
3225
  */
2947
3226
  function parsePartialFillScriptPQ(script, network = 'xna-test') {
2948
- const bytes = typeof script === 'string' ? hexToBytes(script) : script;
3227
+ const bytes = typeof script === 'string' ? hexToBytes$1(script) : script;
2949
3228
  const c = makeCursor(bytes);
2950
3229
  // ═════ Outer IF — Cancel branch (PQ) ═════
2951
3230
  expectByte(c, OP_IF, 'OP_IF (outer cancel)');
@@ -2980,14 +3259,843 @@ var NeuraiScriptsBundle = (function (exports) {
2980
3259
  txHashSelector,
2981
3260
  expiration: fill.expiration,
2982
3261
  paymentScriptPubKey: fill.paymentScriptPubKey,
2983
- scriptHex: bytesToHex(bytes)
3262
+ scriptHex: bytesToHex$1(bytes)
2984
3263
  };
2985
3264
  }
2986
3265
 
3266
+ /**
3267
+ * NIP-054 P2AH custody policy (`OP_CHECKASSETAUTH`, AuthScript only).
3268
+ *
3269
+ * The policy is the witnessScript of a generic AuthScript v1 (NoAuth)
3270
+ * address. A spend of that address needs M of the N owner-token roles of the
3271
+ * list to approve it (G of them when an owner token held by the custody
3272
+ * leaves it):
3273
+ *
3274
+ * policy: <1> <M> <G> <role_1> ... <role_n> <n> OP_CHECKASSETAUTH
3275
+ * witness: [0x00, <c>, <a>, <b>, <T>, policy]
3276
+ *
3277
+ * Build the four arguments with `buildAssetAuthArgs` and wrap them with
3278
+ * `buildAuthScriptWitnessNoAuth({ args, witnessScript: policy })`. A role
3279
+ * approves either by spending its owner token from P2PKH or a strict
3280
+ * AuthScript address with a SIGHASH_ALL signature (synchronous spend, every
3281
+ * argument 0), or by a vote (see `vote.ts` and `proposal.ts`).
3282
+ */
3283
+ /** The only policy version defined by NIP-054. */
3284
+ const ASSETAUTH_POLICY_VERSION = 1;
3285
+ /** Highest number of roles in one policy. */
3286
+ const ASSETAUTH_MAX_ROLES = 16;
3287
+ /** c, a, b and T are script numbers of at most 4 bytes. */
3288
+ const MAX_ARGUMENT = 0x7fffffff;
3289
+ const encoder = new TextEncoder();
3290
+ const decoder = new TextDecoder();
3291
+ function compareBytes(x, y) {
3292
+ const n = Math.min(x.length, y.length);
3293
+ for (let i = 0; i < n; i += 1) {
3294
+ if (x[i] !== y[i])
3295
+ return x[i] - y[i];
3296
+ }
3297
+ return x.length - y.length;
3298
+ }
3299
+ /** Role names as the node checks them: sorted by bytes, no duplicates. */
3300
+ function sortedRoles(roles) {
3301
+ if (!Array.isArray(roles) || roles.length < 1 || roles.length > ASSETAUTH_MAX_ROLES) {
3302
+ throw new Error(`roles must list 1 to ${ASSETAUTH_MAX_ROLES} owner tokens`);
3303
+ }
3304
+ const names = roles.map((role) => {
3305
+ if (typeof role !== 'string' || !role.endsWith('!')) {
3306
+ throw new Error(`role ${JSON.stringify(role)} is not an owner token name (NAME!)`);
3307
+ }
3308
+ return encoder.encode(role);
3309
+ });
3310
+ names.sort(compareBytes);
3311
+ for (let i = 1; i < names.length; i += 1) {
3312
+ if (compareBytes(names[i - 1], names[i]) === 0) {
3313
+ throw new Error(`role ${decoder.decode(names[i])} is listed twice`);
3314
+ }
3315
+ }
3316
+ return names;
3317
+ }
3318
+ function assertThresholds(M, G, n) {
3319
+ if (!Number.isInteger(M) || !Number.isInteger(G) || M < 1 || M > G || G > n) {
3320
+ throw new Error(`thresholds must satisfy 1 <= M <= G <= ${n} (got M=${M}, G=${G})`);
3321
+ }
3322
+ }
3323
+ function buildAssetAuthPolicyScript(policy) {
3324
+ const roles = sortedRoles(policy.roles);
3325
+ assertThresholds(policy.M, policy.G, roles.length);
3326
+ const b = new ScriptBuilder()
3327
+ .pushInt(ASSETAUTH_POLICY_VERSION)
3328
+ .pushInt(policy.M)
3329
+ .pushInt(policy.G);
3330
+ for (const role of roles)
3331
+ b.pushBytes(role);
3332
+ return b.pushInt(roles.length).op(OP_CHECKASSETAUTH).build();
3333
+ }
3334
+ /** Inverse of `buildAssetAuthPolicyScript`; rejects any other script. */
3335
+ function parseAssetAuthPolicyScript(script) {
3336
+ const end = script.length - 2;
3337
+ const nOp = script[end];
3338
+ if (script.length < 6 || script[end + 1] !== OP_CHECKASSETAUTH || nOp < OP_1 || nOp > OP_16) {
3339
+ throw new Error('parse: not an OP_CHECKASSETAUTH policy script');
3340
+ }
3341
+ const c = makeCursor(script);
3342
+ if (readPushUint8(c, 'version') !== ASSETAUTH_POLICY_VERSION) {
3343
+ throw new Error(`parse: policy version must be ${ASSETAUTH_POLICY_VERSION}`);
3344
+ }
3345
+ const M = readPushUint8(c, 'M');
3346
+ const G = readPushUint8(c, 'G');
3347
+ const names = [];
3348
+ while (c.pos < end)
3349
+ names.push(readPush(c, `role ${names.length + 1}`));
3350
+ if (c.pos !== end || names.length !== nOp - OP_1 + 1) {
3351
+ throw new Error('parse: role count does not match n');
3352
+ }
3353
+ const roles = names.map((name) => decoder.decode(name));
3354
+ const policy = { M, G, roles };
3355
+ // Strictly increasing as written: a re-sorted list would be another script.
3356
+ const rebuilt = buildAssetAuthPolicyScript(policy);
3357
+ if (compareBytes(rebuilt, script) !== 0) {
3358
+ throw new Error('parse: roles are not owner names in strictly increasing byte order');
3359
+ }
3360
+ return policy;
3361
+ }
3362
+ /**
3363
+ * Witness `args` [<c>, <a>, <b>, <T>] for the custody input: minimal script
3364
+ * numbers, 0 as the empty element. All default to 0, the synchronous spend.
3365
+ */
3366
+ function buildAssetAuthArgs({ c = 0, a = 0, b = 0, T = 0 } = {}) {
3367
+ for (const [name, value] of Object.entries({ c, a, b, T })) {
3368
+ if (!Number.isInteger(value) || value < 0 || value > MAX_ARGUMENT) {
3369
+ throw new Error(`${name} must be an integer from 0 to ${MAX_ARGUMENT}`);
3370
+ }
3371
+ }
3372
+ return [c, a, b, T].map((value) => encodeScriptNum(value));
3373
+ }
3374
+
3375
+ // Split a JS number into u32 halves without a BigInt allocation. Exact only for integers
3376
+ // `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below
3377
+ // that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).
3378
+ const fromNumH = (n) => (n / 2 ** 32) | 0;
3379
+ const fromNumL = (n) => n >>> 0;
3380
+ // Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call
3381
+ // BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.
3382
+ function setU64FromNum(view, byteOffset, n, isLE) {
3383
+ const h = fromNumH(n);
3384
+ const l = fromNumL(n);
3385
+ view.setUint32(byteOffset, isLE ? l : h, isLE);
3386
+ view.setUint32(byteOffset + 4, isLE ? h : l, isLE);
3387
+ }
3388
+
3389
+ /**
3390
+ * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
3391
+ * @param a - value to test
3392
+ * @returns `true` when the value is a Uint8Array-compatible view.
3393
+ * @example
3394
+ * Check whether a value is a Uint8Array-compatible view.
3395
+ * ```ts
3396
+ * isBytes(new Uint8Array([1, 2, 3]));
3397
+ * ```
3398
+ */
3399
+ function isBytes(a) {
3400
+ // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.
3401
+ // The fallback still requires a real ArrayBuffer view, so plain
3402
+ // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and
3403
+ // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
3404
+ return (a instanceof Uint8Array ||
3405
+ (ArrayBuffer.isView(a) &&
3406
+ a.constructor.name === 'Uint8Array' &&
3407
+ 'BYTES_PER_ELEMENT' in a &&
3408
+ a.BYTES_PER_ELEMENT === 1));
3409
+ }
3410
+ // Shared error-message prefix builder. Only called on throw paths, so assert
3411
+ // success paths never pay for the string concatenation.
3412
+ const atitle = (title) => (title ? `"${title}" ` : '');
3413
+ /**
3414
+ * Asserts something is Uint8Array.
3415
+ * @param value - value to validate
3416
+ * @param length - optional exact length constraint
3417
+ * @param title - label included in thrown errors
3418
+ * @returns The validated byte array.
3419
+ * @throws On wrong argument types. {@link TypeError}
3420
+ * @throws On wrong argument ranges or values. {@link RangeError}
3421
+ * @example
3422
+ * Validate that a value is a byte array.
3423
+ * ```ts
3424
+ * abytes(new Uint8Array([1, 2, 3]));
3425
+ * ```
3426
+ */
3427
+ function abytes(value, length, title = '') {
3428
+ // Success path first: this runs at the start of every update() / digestInto(), and the
3429
+ // common `abytes(data)` form must not pay for length handling it does not use.
3430
+ if (isBytes(value) && (length === undefined))
3431
+ return value;
3432
+ const bytes = isBytes(value);
3433
+ const ofLen = '';
3434
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
3435
+ const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;
3436
+ if (!bytes)
3437
+ throw new TypeError(message);
3438
+ throw new RangeError(message);
3439
+ }
3440
+ const aobject = (value, label) => {
3441
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
3442
+ throw new TypeError((label === 'object' ? '' : `"${label}" `) + 'expected object, got type=' + typeof value);
3443
+ };
3444
+ const aopts = (value, label) => {
3445
+ aobject(value, label);
3446
+ const proto = Object.getPrototypeOf(value);
3447
+ if (proto !== Object.prototype && proto !== null)
3448
+ throw new TypeError(`"${label}" expected plain object`);
3449
+ // Object.assign() treats an own "__proto__" source key as a write to the target's legacy
3450
+ // prototype setter. Reject it before merging so inherited option values cannot be injected.
3451
+ if (Object.hasOwn(value, '__proto__'))
3452
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
3453
+ };
3454
+ /**
3455
+ * Asserts a hash instance has not been destroyed or finished.
3456
+ * @param instance - hash instance to validate
3457
+ * @param checkFinished - whether to reject finalized instances
3458
+ * @throws If the hash instance has already been destroyed or finalized. {@link Error}
3459
+ * @example
3460
+ * Validate that a hash instance is still usable.
3461
+ * ```ts
3462
+ * import { aexists } from '@noble/hashes/utils.js';
3463
+ * import { sha256 } from '@noble/hashes/sha2.js';
3464
+ * const hash = sha256.create();
3465
+ * aexists(hash);
3466
+ * ```
3467
+ */
3468
+ function aexists(instance, checkFinished = true) {
3469
+ // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their
3470
+ // truthiness is checked - re-validating their type per call was pure hot-path overhead.
3471
+ if (instance.destroyed)
3472
+ throw new Error('hash was destroyed');
3473
+ if (checkFinished && instance.finished)
3474
+ throw new Error('digest() was already called');
3475
+ }
3476
+ /**
3477
+ * Asserts output is a sufficiently-sized byte array.
3478
+ * @param out - destination buffer
3479
+ * @param instance - hash instance providing output length
3480
+ * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
3481
+ * @throws On wrong argument types. {@link TypeError}
3482
+ * @throws On wrong argument ranges or values. {@link RangeError}
3483
+ * @example
3484
+ * Validate a caller-provided digest buffer.
3485
+ * ```ts
3486
+ * import { aoutput } from '@noble/hashes/utils.js';
3487
+ * import { sha256 } from '@noble/hashes/sha2.js';
3488
+ * const hash = sha256.create();
3489
+ * aoutput(new Uint8Array(hash.outputLen), hash);
3490
+ * ```
3491
+ */
3492
+ function aoutput(out, instance) {
3493
+ abytes(out, undefined, 'output');
3494
+ // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast
3495
+ // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.
3496
+ const min = instance.outputLen;
3497
+ if (!(out.length >= min)) {
3498
+ throw new RangeError('"output" expected length >= ' + min);
3499
+ }
3500
+ }
3501
+ /**
3502
+ * Zeroizes typed arrays in place. Warning: JS provides no guarantees.
3503
+ * @param arrays - arrays to overwrite with zeros
3504
+ * @example
3505
+ * Zeroize sensitive buffers in place.
3506
+ * ```ts
3507
+ * clean(new Uint8Array([1, 2, 3]));
3508
+ * ```
3509
+ */
3510
+ function clean(...arrays) {
3511
+ for (let i = 0; i < arrays.length; i++) {
3512
+ arrays[i].fill(0);
3513
+ }
3514
+ }
3515
+ /**
3516
+ * Creates a DataView for byte-level manipulation.
3517
+ * @param arr - source typed array
3518
+ * @returns DataView over the same buffer region.
3519
+ * @example
3520
+ * Create a DataView over an existing buffer.
3521
+ * ```ts
3522
+ * createView(new Uint8Array(4));
3523
+ * ```
3524
+ */
3525
+ function createView(arr) {
3526
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
3527
+ }
3528
+ /**
3529
+ * Rotate-right operation for uint32 values.
3530
+ * @param word - source word
3531
+ * @param shift - shift amount in bits
3532
+ * @returns Rotated word.
3533
+ * @example
3534
+ * Rotate a 32-bit word to the right.
3535
+ * ```ts
3536
+ * rotr(0x12345678, 8);
3537
+ * ```
3538
+ */
3539
+ function rotr(word, shift) {
3540
+ return (word << (32 - shift)) | (word >>> shift);
3541
+ }
3542
+ /**
3543
+ * Merges default options and passed options.
3544
+ * @param defaults - base option object
3545
+ * @param opts - user overrides
3546
+ * @param title - label included in thrown override errors
3547
+ * @returns Fresh merged option object with a null prototype.
3548
+ * @throws On wrong argument types. {@link TypeError}
3549
+ * @example
3550
+ * Merge user overrides onto default options.
3551
+ * ```ts
3552
+ * checkOpts({ dkLen: 32 }, { asyncTick: 10 });
3553
+ * ```
3554
+ */
3555
+ function checkOpts(defaults, opts, title = 'opts') {
3556
+ aopts(defaults, 'defaults');
3557
+ if (opts !== undefined)
3558
+ aopts(opts, title);
3559
+ // Callers read optional fields directly, so omitted values must not fall through to ambient
3560
+ // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).
3561
+ const merged = Object.assign(Object.create(null), defaults, opts);
3562
+ return merged;
3563
+ }
3564
+ /**
3565
+ * Creates a callable hash function from a stateful class constructor.
3566
+ * @param hashCons - hash constructor or factory
3567
+ * @param info - optional metadata such as DER OID
3568
+ * @returns Frozen callable hash wrapper with `.create()`.
3569
+ * Wrapper construction eagerly calls `hashCons(undefined)` once to read
3570
+ * `outputLen` / `blockLen`, so constructor side effects happen at module
3571
+ * init time.
3572
+ * @throws On wrong argument types. {@link TypeError}
3573
+ * @example
3574
+ * Wrap a stateful hash constructor into a callable helper.
3575
+ * ```ts
3576
+ * import { createHasher } from '@noble/hashes/utils.js';
3577
+ * import { sha256 } from '@noble/hashes/sha2.js';
3578
+ * const wrapped = createHasher(sha256.create, { oid: sha256.oid });
3579
+ * wrapped(new Uint8Array([1]));
3580
+ * ```
3581
+ */
3582
+ function createHasher(hashCons, info = {}) {
3583
+ if (typeof hashCons !== 'function')
3584
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
3585
+ info = checkOpts({}, info, 'info');
3586
+ const hashC = (msg, opts) => hashCons(opts)
3587
+ .update(msg)
3588
+ .digest();
3589
+ const tmp = hashCons(undefined);
3590
+ hashC.outputLen = tmp.outputLen;
3591
+ hashC.blockLen = tmp.blockLen;
3592
+ hashC.canXOF = tmp.canXOF;
3593
+ hashC.create = (opts) => hashCons(opts);
3594
+ Object.assign(hashC, info);
3595
+ return Object.freeze(hashC);
3596
+ }
3597
+ /**
3598
+ * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
3599
+ * @param suffix - final OID byte for the selected hash.
3600
+ * The helper accepts any byte even though only the documented NIST hash
3601
+ * suffixes are meaningful downstream.
3602
+ * @returns Object containing the DER-encoded OID.
3603
+ * @example
3604
+ * Build OID metadata for a NIST hash.
3605
+ * ```ts
3606
+ * oidNist(0x01);
3607
+ * ```
3608
+ */
3609
+ const oidNist = (suffix) => ({
3610
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
3611
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
3612
+ oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),
3613
+ });
3614
+
3615
+ /**
3616
+ * Internal Merkle-Damgard hash utils.
3617
+ * @module
3618
+ */
3619
+ /**
3620
+ * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
3621
+ * Returns bits from `b` when `a` is set, otherwise from `c`.
3622
+ * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
3623
+ * set the same bit.
3624
+ * @param a - selector word
3625
+ * @param b - word chosen when selector bit is set
3626
+ * @param c - word chosen when selector bit is clear
3627
+ * @returns Mixed 32-bit word.
3628
+ * @example
3629
+ * Combine three words with the shared 32-bit choice primitive.
3630
+ * ```ts
3631
+ * Chi(0xffffffff, 0x12345678, 0x87654321);
3632
+ * ```
3633
+ */
3634
+ function Chi(a, b, c) {
3635
+ return (a & b) ^ (~a & c);
3636
+ }
3637
+ /**
3638
+ * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
3639
+ * Returns bits shared by at least two inputs.
3640
+ * @param a - first input word
3641
+ * @param b - second input word
3642
+ * @param c - third input word
3643
+ * @returns Mixed 32-bit word.
3644
+ * @example
3645
+ * Combine three words with the shared 32-bit majority primitive.
3646
+ * ```ts
3647
+ * Maj(0xffffffff, 0x12345678, 0x87654321);
3648
+ * ```
3649
+ */
3650
+ function Maj(a, b, c) {
3651
+ return (a & b) ^ (a & c) ^ (b & c);
3652
+ }
3653
+ /**
3654
+ * Merkle-Damgard hash construction base class.
3655
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
3656
+ * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
3657
+ * strings with partial-byte tails.
3658
+ * @param blockLen - internal block size in bytes
3659
+ * @param outputLen - digest size in bytes
3660
+ * @param padOffset - trailing length field size in bytes
3661
+ * @param isLE - whether length and state words are encoded in little-endian
3662
+ * @example
3663
+ * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
3664
+ * ```ts
3665
+ * import { _SHA1 } from '@noble/hashes/legacy.js';
3666
+ * const hash = new _SHA1();
3667
+ * hash.update(new Uint8Array([97, 98, 99]));
3668
+ * hash.digest();
3669
+ * ```
3670
+ */
3671
+ class HashMD {
3672
+ blockLen;
3673
+ outputLen;
3674
+ canXOF = false;
3675
+ padOffset;
3676
+ isLE;
3677
+ // For partial updates less than block size
3678
+ buffer;
3679
+ view;
3680
+ finished = false;
3681
+ length = 0;
3682
+ pos = 0;
3683
+ destroyed = false;
3684
+ constructor(blockLen, outputLen, padOffset, isLE) {
3685
+ this.blockLen = blockLen;
3686
+ this.outputLen = outputLen;
3687
+ this.padOffset = padOffset;
3688
+ this.isLE = isLE;
3689
+ this.buffer = new Uint8Array(blockLen);
3690
+ this.view = createView(this.buffer);
3691
+ }
3692
+ update(data) {
3693
+ aexists(this);
3694
+ abytes(data);
3695
+ const { view, buffer, blockLen } = this;
3696
+ const len = data.length;
3697
+ let processed = false;
3698
+ for (let pos = 0; pos < len;) {
3699
+ const take = Math.min(blockLen - this.pos, len - pos);
3700
+ // Fast path only when there is no buffered partial block: `take === blockLen` implies
3701
+ // `this.pos === 0`, so we can process full blocks directly from the input view.
3702
+ if (take === blockLen) {
3703
+ const dataView = createView(data);
3704
+ for (; blockLen <= len - pos; pos += blockLen)
3705
+ this.process(dataView, pos);
3706
+ processed = true;
3707
+ continue;
3708
+ }
3709
+ // When the whole input is buffered in one go (common for short messages), passing `data`
3710
+ // directly avoids allocating a subarray view.
3711
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
3712
+ this.pos += take;
3713
+ pos += take;
3714
+ if (this.pos === blockLen) {
3715
+ this.process(view, 0);
3716
+ this.pos = 0;
3717
+ processed = true;
3718
+ }
3719
+ }
3720
+ this.length += data.length;
3721
+ // Shared schedule buffers only pick up input-derived words inside process(); if everything
3722
+ // was buffered without processing, there is nothing to zero.
3723
+ if (processed)
3724
+ this.roundClean();
3725
+ return this;
3726
+ }
3727
+ digestInto(out) {
3728
+ aexists(this);
3729
+ aoutput(out, this);
3730
+ this.finished = true;
3731
+ // Padding
3732
+ // We can avoid allocation of buffer for padding completely if it
3733
+ // was previously not allocated here. But it won't change performance.
3734
+ const { buffer, view, blockLen, isLE } = this;
3735
+ let { pos } = this;
3736
+ // append the bit '1' to the message, then zero-pad the rest of the block
3737
+ buffer[pos++] = 0b10000000;
3738
+ buffer.fill(0, pos);
3739
+ // we have less than padOffset left in buffer, so we cannot put length in
3740
+ // current block, need process it and pad again
3741
+ if (this.padOffset > blockLen - pos) {
3742
+ this.process(view, 0);
3743
+ buffer.fill(0);
3744
+ }
3745
+ // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from
3746
+ // the padding fill above, and JS will overflow before user input can make that half non-zero.
3747
+ // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an
3748
+ // integer below 2**53, so the split inside the helper stays exact).
3749
+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
3750
+ this.process(view, 0);
3751
+ // The final block above is processed outside update(), so the shared message-schedule
3752
+ // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().
3753
+ this.roundClean();
3754
+ // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.
3755
+ const oview = out === buffer ? view : createView(out);
3756
+ const len = this.outputLen;
3757
+ // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT
3758
+ const outLen = len / 4;
3759
+ const state = this.get();
3760
+ // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.
3761
+ if (len % 4 || outLen > state.length)
3762
+ throw new Error('invalid outputLen');
3763
+ for (let i = 0; i < outLen; i++)
3764
+ oview.setUint32(4 * i, state[i], isLE);
3765
+ }
3766
+ digest() {
3767
+ const { buffer, outputLen } = this;
3768
+ this.digestInto(buffer);
3769
+ // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return
3770
+ // fresh bytes to the caller.
3771
+ const res = buffer.slice(0, outputLen);
3772
+ this.destroy();
3773
+ return res;
3774
+ }
3775
+ _cloneIntoMeta(to) {
3776
+ const { buffer, length, finished, destroyed, pos } = this;
3777
+ to.destroyed = destroyed;
3778
+ to.finished = finished;
3779
+ to.length = length;
3780
+ to.pos = pos;
3781
+ // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and
3782
+ // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.
3783
+ if (pos)
3784
+ to.buffer.set(buffer); // Avoid a hot modulo guard.
3785
+ return to;
3786
+ }
3787
+ clone() {
3788
+ return this._cloneInto();
3789
+ }
3790
+ }
3791
+ /**
3792
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
3793
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
3794
+ */
3795
+ /** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
3796
+ * square roots of the first eight prime numbers. Exported as a shared table; callers must treat
3797
+ * it as read-only because constructors copy words from it by index. */
3798
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
3799
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
3800
+ ]);
3801
+
3802
+ /**
3803
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
3804
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
3805
+ * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
3806
+ * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
3807
+ * @module
3808
+ */
3809
+ /**
3810
+ * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits
3811
+ * of the cube roots of the first 64 primes (2..311).
3812
+ */
3813
+ // prettier-ignore
3814
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
3815
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
3816
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
3817
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
3818
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
3819
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
3820
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
3821
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
3822
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
3823
+ ]);
3824
+ /** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */
3825
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
3826
+ /** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */
3827
+ class SHA2_32B extends HashMD {
3828
+ // We cannot use array here since array allows indexing by variable
3829
+ // which means optimizer/compiler cannot use registers.
3830
+ // Numeric initializers matter: starting the fields as `undefined` changes
3831
+ // V8's field representation and makes sha256 3x slower (measured).
3832
+ A = 0;
3833
+ B = 0;
3834
+ C = 0;
3835
+ D = 0;
3836
+ E = 0;
3837
+ F = 0;
3838
+ G = 0;
3839
+ H = 0;
3840
+ constructor(outputLen, IV) {
3841
+ super(64, outputLen, 8, false);
3842
+ this.A = IV[0] | 0;
3843
+ this.B = IV[1] | 0;
3844
+ this.C = IV[2] | 0;
3845
+ this.D = IV[3] | 0;
3846
+ this.E = IV[4] | 0;
3847
+ this.F = IV[5] | 0;
3848
+ this.G = IV[6] | 0;
3849
+ this.H = IV[7] | 0;
3850
+ }
3851
+ get() {
3852
+ const { A, B, C, D, E, F, G, H } = this;
3853
+ return [A, B, C, D, E, F, G, H];
3854
+ }
3855
+ // prettier-ignore
3856
+ set(A, B, C, D, E, F, G, H) {
3857
+ this.A = A | 0;
3858
+ this.B = B | 0;
3859
+ this.C = C | 0;
3860
+ this.D = D | 0;
3861
+ this.E = E | 0;
3862
+ this.F = F | 0;
3863
+ this.G = G | 0;
3864
+ this.H = H | 0;
3865
+ }
3866
+ _cloneInto(to) {
3867
+ (to ||= new this.constructor()).set(...this.get());
3868
+ return this._cloneIntoMeta(to);
3869
+ }
3870
+ process(view, offset) {
3871
+ // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
3872
+ for (let i = 0; i < 16; i++, offset += 4)
3873
+ SHA256_W[i] = view.getUint32(offset, false);
3874
+ for (let i = 16; i < 64; i++) {
3875
+ const W15 = SHA256_W[i - 15];
3876
+ const W2 = SHA256_W[i - 2];
3877
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
3878
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
3879
+ SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
3880
+ }
3881
+ // Compression function main loop, 64 rounds
3882
+ let { A, B, C, D, E, F, G, H } = this;
3883
+ for (let i = 0; i < 64; i++) {
3884
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
3885
+ const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
3886
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
3887
+ const T2 = (sigma0 + Maj(A, B, C)) | 0;
3888
+ H = G;
3889
+ G = F;
3890
+ F = E;
3891
+ E = (D + T1) | 0;
3892
+ D = C;
3893
+ C = B;
3894
+ B = A;
3895
+ A = (T1 + T2) | 0;
3896
+ }
3897
+ // Add the compressed chunk to the current hash value
3898
+ A = (A + this.A) | 0;
3899
+ B = (B + this.B) | 0;
3900
+ C = (C + this.C) | 0;
3901
+ D = (D + this.D) | 0;
3902
+ E = (E + this.E) | 0;
3903
+ F = (F + this.F) | 0;
3904
+ G = (G + this.G) | 0;
3905
+ H = (H + this.H) | 0;
3906
+ this.set(A, B, C, D, E, F, G, H);
3907
+ }
3908
+ roundClean() {
3909
+ clean(SHA256_W);
3910
+ }
3911
+ destroy() {
3912
+ // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves
3913
+ // update()/digest() callable on reused instances.
3914
+ this.destroyed = true;
3915
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
3916
+ clean(this.buffer);
3917
+ }
3918
+ }
3919
+ /** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
3920
+ class _SHA256 extends SHA2_32B {
3921
+ constructor() {
3922
+ super(32, SHA256_IV);
3923
+ }
3924
+ }
3925
+ /**
3926
+ * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
3927
+ *
3928
+ * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
3929
+ * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
3930
+ * - Each sha256 hash is executing 2^18 bit operations.
3931
+ * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
3932
+ * @param msg - message bytes to hash
3933
+ * @param opts - Reserved hash options.
3934
+ * @returns Digest bytes.
3935
+ * @example
3936
+ * Hash a message with SHA2-256.
3937
+ * ```ts
3938
+ * sha256(new Uint8Array([97, 98, 99]));
3939
+ * ```
3940
+ */
3941
+ const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(),
3942
+ /* @__PURE__ */ oidNist(0x01));
3943
+
3944
+ /**
3945
+ * NIP-054 proposal hash H, the message a vote carries.
3946
+ *
3947
+ * H = TaggedHash("NeuraiAssetAuthProposal", m)
3948
+ * m = chainId (u8) || nVersion (i32) || nLockTime (u32) || T (u32)
3949
+ * || compact(c) || compact(a) || compact(b)
3950
+ * || (outpoint, nSequence) of inputs 0..c-1
3951
+ * || outputs 0..a-1 || the last b outputs
3952
+ * || compact(#refs) || reference inputs (version 3 only)
3953
+ *
3954
+ * Inputs from index c on and the outputs between the prefix and the suffix
3955
+ * (approvals, returns, fees, change) are left to the executor, so a skeleton
3956
+ * transaction with only the proposal inputs and outputs gives the same H as
3957
+ * the execution. Votes carry H as is, as the 32-byte (64-hex) message of
3958
+ * their owner-token transfer: `bytesToHex(hash)`.
3959
+ */
3960
+ /** The chain identifier the node commits to (OP_CHAINCONTEXT selector 0x03). */
3961
+ const ASSETAUTH_CHAIN_IDS = Object.freeze({
3962
+ mainnet: 0,
3963
+ testnet: 1,
3964
+ regtest: 2
3965
+ });
3966
+ const PROPOSAL_TAG = new TextEncoder().encode('NeuraiAssetAuthProposal');
3967
+ function u32(value) {
3968
+ const out = new Uint8Array(4);
3969
+ new DataView(out.buffer).setUint32(0, value >>> 0, true);
3970
+ return out;
3971
+ }
3972
+ function compactSize(value) {
3973
+ if (value < 0xfd)
3974
+ return Uint8Array.of(value);
3975
+ if (value <= 0xffff)
3976
+ return Uint8Array.of(0xfd, value & 0xff, value >> 8);
3977
+ return concatBytes$1(Uint8Array.of(0xfe), u32(value));
3978
+ }
3979
+ /** A display-order txid and vout as the node serializes a COutPoint. */
3980
+ function outpoint(txid, vout) {
3981
+ return concatBytes$1(hexToBytes$1(txid).reverse(), u32(vout));
3982
+ }
3983
+ function buildAssetAuthProposalMessage(proposal) {
3984
+ const { c, a, b, T } = proposal;
3985
+ const chainId = ASSETAUTH_CHAIN_IDS[proposal.chain];
3986
+ if (chainId === undefined) {
3987
+ throw new Error(`unknown chain ${JSON.stringify(proposal.chain)}`);
3988
+ }
3989
+ for (const [name, value] of Object.entries({ c, a, b, T })) {
3990
+ if (!Number.isInteger(value) || value < 0 || value > 0x7fffffff) {
3991
+ throw new Error(`${name} must be an integer from 0 to ${0x7fffffff}`);
3992
+ }
3993
+ }
3994
+ const tx = parseTransaction(proposal.rawTx);
3995
+ if (c > tx.inputs.length) {
3996
+ throw new Error(`c (${c}) exceeds the ${tx.inputs.length} inputs of the transaction`);
3997
+ }
3998
+ if (a + b > tx.outputs.length) {
3999
+ throw new Error(`a + b (${a + b}) exceeds the ${tx.outputs.length} outputs of the transaction`);
4000
+ }
4001
+ const version = new Uint8Array(4);
4002
+ new DataView(version.buffer).setInt32(0, tx.version, true);
4003
+ const parts = [Uint8Array.of(chainId), version, u32(tx.locktime), u32(T), compactSize(c), compactSize(a), compactSize(b)];
4004
+ for (const input of tx.inputs.slice(0, c)) {
4005
+ parts.push(outpoint(input.txid, input.vout), u32(input.sequence));
4006
+ }
4007
+ for (const output of [...tx.outputs.slice(0, a), ...tx.outputs.slice(tx.outputs.length - b)]) {
4008
+ parts.push(serializeOutput(output));
4009
+ }
4010
+ const refs = tx.version === 3 ? tx.vrefin : [];
4011
+ parts.push(compactSize(refs.length));
4012
+ for (const ref of refs)
4013
+ parts.push(outpoint(ref.txid, ref.vout));
4014
+ return concatBytes$1(...parts);
4015
+ }
4016
+ /** H: 32 bytes, in the order a vote carries it. */
4017
+ function assetAuthProposalHash(proposal) {
4018
+ const tag = sha256(PROPOSAL_TAG);
4019
+ return sha256(concatBytes$1(tag, tag, buildAssetAuthProposalMessage(proposal)));
4020
+ }
4021
+
4022
+ /**
4023
+ * NIP-054 vote lock: a wallet template (not part of the opcode) that holds a
4024
+ * role's owner token while it votes for a proposal.
4025
+ *
4026
+ * The holder sends the owner token, with the proposal hash H as its transfer
4027
+ * message, to the generic AuthScript v1 (NoAuth) address of this script:
4028
+ *
4029
+ * OP_IF execute, up to height T
4030
+ * OP_1 OP_CHAINCONTEXT <T> OP_LESSTHANOREQUAL OP_VERIFY
4031
+ * OP_SWAP OP_4 OP_INPUTFIELD <0x01 || C> OP_EQUALVERIFY
4032
+ * OP_OUTPUTSCRIPT <return> OP_EQUAL
4033
+ * OP_ELSE give it back, after T
4034
+ * OP_1 OP_CHAINCONTEXT <T> OP_GREATERTHAN OP_VERIFY
4035
+ * OP_NIP OP_OUTPUTSCRIPT <return> OP_EQUAL
4036
+ * OP_ENDIF
4037
+ *
4038
+ * Both branches send the token back to its owner (`return`, the full output
4039
+ * script). The execute branch also needs the custody, commitment C, at the
4040
+ * input it names. It must use OP_INPUTFIELD selector 04, the full
4041
+ * version-plus-commitment: selector 02 only reads the first 34 bytes of the
4042
+ * spent script, which a forged anyone-can-spend custody can match.
4043
+ */
4044
+ /** OP_INPUTFIELD selector: the full version-plus-commitment of the spent script. */
4045
+ const INPUTFIELD_AUTHSCRIPT_DESTINATION = 0x04;
4046
+ const AUTHSCRIPT_V1 = 0x01;
4047
+ function asBytes(value) {
4048
+ return typeof value === 'string' ? hexToBytes$1(value) : value;
4049
+ }
4050
+ function assertIndex(name, value) {
4051
+ if (!Number.isInteger(value) || value < 0 || value > 0x7fffffff) {
4052
+ throw new Error(`${name} must be an integer from 0 to ${0x7fffffff}`);
4053
+ }
4054
+ }
4055
+ function buildAssetAuthVoteLockScript(params) {
4056
+ assertIndex('T', params.T);
4057
+ const commitment = asBytes(params.custodyCommitment);
4058
+ if (commitment.length !== 32) {
4059
+ throw new Error(`custodyCommitment must be 32 bytes (got ${commitment.length})`);
4060
+ }
4061
+ const returnScript = asBytes(params.returnScriptPubKey);
4062
+ if (returnScript.length === 0) {
4063
+ throw new Error('returnScriptPubKey must not be empty');
4064
+ }
4065
+ return new ScriptBuilder()
4066
+ .op(OP_IF)
4067
+ .pushInt(CHAINCONTEXT_HEIGHT).op(OP_CHAINCONTEXT).pushInt(params.T).op(OP_LESSTHANOREQUAL, OP_VERIFY)
4068
+ .op(OP_SWAP).pushInt(INPUTFIELD_AUTHSCRIPT_DESTINATION).op(OP_INPUTFIELD)
4069
+ .pushBytes(concatBytes$1(Uint8Array.of(AUTHSCRIPT_V1), commitment)).op(OP_EQUALVERIFY)
4070
+ .op(OP_OUTPUTSCRIPT).pushBytes(returnScript).op(OP_EQUAL)
4071
+ .op(OP_ELSE)
4072
+ .pushInt(CHAINCONTEXT_HEIGHT).op(OP_CHAINCONTEXT).pushInt(params.T).op(OP_GREATERTHAN, OP_VERIFY)
4073
+ .op(OP_NIP, OP_OUTPUTSCRIPT).pushBytes(returnScript).op(OP_EQUAL)
4074
+ .op(OP_ENDIF)
4075
+ .build();
4076
+ }
4077
+ /**
4078
+ * Witness `args` of the execute branch: the index of the custody input and
4079
+ * the index of the output that returns the token.
4080
+ */
4081
+ function buildAssetAuthVoteExecuteArgs(params) {
4082
+ assertIndex('custodyInput', params.custodyInput);
4083
+ assertIndex('returnOutput', params.returnOutput);
4084
+ return [encodeScriptNum(params.custodyInput), encodeScriptNum(params.returnOutput), encodeScriptNum(1)];
4085
+ }
4086
+ /** Witness `args` of the return branch, after T. */
4087
+ function buildAssetAuthVoteReturnArgs(params) {
4088
+ assertIndex('returnOutput', params.returnOutput);
4089
+ return [encodeScriptNum(0), encodeScriptNum(params.returnOutput), encodeScriptNum(0)];
4090
+ }
4091
+
2987
4092
  // ---------- Core primitives ----------
2988
4093
 
2989
4094
  var NeuraiScripts = /*#__PURE__*/Object.freeze({
2990
4095
  __proto__: null,
4096
+ ASSETAUTH_CHAIN_IDS: ASSETAUTH_CHAIN_IDS,
4097
+ ASSETAUTH_MAX_ROLES: ASSETAUTH_MAX_ROLES,
4098
+ ASSETAUTH_POLICY_VERSION: ASSETAUTH_POLICY_VERSION,
2991
4099
  AUTHSCRIPT_LEGACY: AUTHSCRIPT_LEGACY,
2992
4100
  AUTHSCRIPT_NOAUTH: AUTHSCRIPT_NOAUTH,
2993
4101
  AUTHSCRIPT_PQ: AUTHSCRIPT_PQ,
@@ -2998,6 +4106,13 @@ var NeuraiScriptsBundle = (function (exports) {
2998
4106
  PQ_PUBKEY_PREFIX: PQ_PUBKEY_PREFIX,
2999
4107
  STRICT_PQ_PUBKEY_LENGTH: STRICT_PQ_PUBKEY_LENGTH,
3000
4108
  ScriptBuilder: ScriptBuilder,
4109
+ assetAuthProposalHash: assetAuthProposalHash,
4110
+ buildAssetAuthArgs: buildAssetAuthArgs,
4111
+ buildAssetAuthPolicyScript: buildAssetAuthPolicyScript,
4112
+ buildAssetAuthProposalMessage: buildAssetAuthProposalMessage,
4113
+ buildAssetAuthVoteExecuteArgs: buildAssetAuthVoteExecuteArgs,
4114
+ buildAssetAuthVoteLockScript: buildAssetAuthVoteLockScript,
4115
+ buildAssetAuthVoteReturnArgs: buildAssetAuthVoteReturnArgs,
3001
4116
  buildAuthScriptWitnessLegacy: buildAuthScriptWitnessLegacy,
3002
4117
  buildAuthScriptWitnessNoAuth: buildAuthScriptWitnessNoAuth,
3003
4118
  buildAuthScriptWitnessPQ: buildAuthScriptWitnessPQ,
@@ -3018,8 +4133,8 @@ var NeuraiScriptsBundle = (function (exports) {
3018
4133
  buildStrictWitnessECDSA: buildStrictWitnessECDSA,
3019
4134
  buildStrictWitnessPQ: buildStrictWitnessPQ,
3020
4135
  bytesEqual: bytesEqual,
3021
- bytesToHex: bytesToHex,
3022
- concatBytes: concatBytes,
4136
+ bytesToHex: bytesToHex$1,
4137
+ concatBytes: concatBytes$1,
3023
4138
  encodeAuthScriptScriptPubKey: encodeAuthScriptScriptPubKey,
3024
4139
  encodeMultisigRedeemScript: encodeMultisigRedeemScript,
3025
4140
  encodeMultisigRedeemScriptHex: encodeMultisigRedeemScriptHex,
@@ -3030,10 +4145,11 @@ var NeuraiScriptsBundle = (function (exports) {
3030
4145
  encodeP2WSHScriptPubKey: encodeP2WSHScriptPubKey,
3031
4146
  encodeScriptNum: encodeScriptNum,
3032
4147
  encodeSellerScriptPubKey: encodeSellerScriptPubKey,
3033
- ensureHex: ensureHex,
3034
- hexToBytes: hexToBytes,
4148
+ ensureHex: ensureHex$1,
4149
+ hexToBytes: hexToBytes$1,
3035
4150
  isPartialFillScriptPQ: isPartialFillScriptPQ,
3036
4151
  opcodes: opcodes,
4152
+ parseAssetAuthPolicyScript: parseAssetAuthPolicyScript,
3037
4153
  parsePartialFillScript: parsePartialFillScript,
3038
4154
  parsePartialFillScriptPQ: parsePartialFillScriptPQ,
3039
4155
  pushBytes: pushBytes,