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