@neuraiproject/neurai-scripts 0.10.0 → 0.12.0

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