@neuraiproject/neurai-scripts 0.9.2 → 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/index.cjs CHANGED
@@ -5,25 +5,25 @@
5
5
  * duplicated here to keep this package free of runtime coupling beyond its
6
6
  * declared `dependencies` field. All sizes are little-endian, per Neurai.
7
7
  */
8
- function ensureHex(hex, label = 'hex') {
8
+ function ensureHex$1(hex, label = 'hex') {
9
9
  const normalized = String(hex || '').trim().toLowerCase();
10
10
  if (!/^[0-9a-f]*$/.test(normalized) || normalized.length % 2 !== 0) {
11
11
  throw new Error(`Invalid ${label}: expected even-length hex string`);
12
12
  }
13
13
  return normalized;
14
14
  }
15
- function hexToBytes(hex) {
16
- const normalized = ensureHex(hex);
15
+ function hexToBytes$1(hex) {
16
+ const normalized = ensureHex$1(hex);
17
17
  const bytes = new Uint8Array(normalized.length / 2);
18
18
  for (let i = 0; i < normalized.length; i += 2) {
19
19
  bytes[i / 2] = Number.parseInt(normalized.slice(i, i + 2), 16);
20
20
  }
21
21
  return bytes;
22
22
  }
23
- function bytesToHex(bytes) {
23
+ function bytesToHex$1(bytes) {
24
24
  return Array.from(bytes, (value) => value.toString(16).padStart(2, '0')).join('');
25
25
  }
26
- function concatBytes(...parts) {
26
+ function concatBytes$1(...parts) {
27
27
  const total = parts.reduce((sum, part) => sum + part.length, 0);
28
28
  const out = new Uint8Array(total);
29
29
  let offset = 0;
@@ -45,7 +45,7 @@ function bytesEqual(a, b) {
45
45
 
46
46
  /** Exact monetary primitives. This module has no runtime dependencies. */
47
47
  /** Normalize a raw integer without preserving an already rounded number. */
48
- function toRawInteger(value, label = 'amount') {
48
+ function toRawInteger$1(value, label = 'amount') {
49
49
  if (typeof value === 'bigint')
50
50
  return value;
51
51
  if (typeof value === 'number' && Number.isSafeInteger(value))
@@ -187,6 +187,10 @@ const OP_CHECKSIG_ED25519 = 0xdd;
187
187
  // 0xde. Stack contract: (sig, count, pubkey -- count + 0|1). Works with
188
188
  // both legacy secp256k1 and PQ ML-DSA-44 keys via CPubKey::Verify().
189
189
  const OP_CHECKSIGADD = 0xde;
190
+ // NIP-054 (P2AH): M-of-N authorization by owner-token roles in slot 0xdf,
191
+ // AuthScript only. Stack contract: (c a b T 1 M G role_1 .. role_n n -- 1),
192
+ // failing the script instead of pushing 0. See covenants/asset-auth.
193
+ const OP_CHECKASSETAUTH = 0xdf;
190
194
  // ---------- Expansion / NOPs ----------
191
195
  // Only the NOPs not aliased by DePIN-Test opcodes are exported as NOPs.
192
196
  // OP_NOP2 == OP_CHECKLOCKTIMEVERIFY (0xb1)
@@ -345,6 +349,7 @@ var opcodes = /*#__PURE__*/Object.freeze({
345
349
  OP_BOOLOR: OP_BOOLOR,
346
350
  OP_CAT: OP_CAT,
347
351
  OP_CHAINCONTEXT: OP_CHAINCONTEXT,
352
+ OP_CHECKASSETAUTH: OP_CHECKASSETAUTH,
348
353
  OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY,
349
354
  OP_CHECKMERKLEINCLUSION: OP_CHECKMERKLEINCLUSION,
350
355
  OP_CHECKMULTISIG: OP_CHECKMULTISIG,
@@ -459,7 +464,7 @@ var opcodes = /*#__PURE__*/Object.freeze({
459
464
  * - otherwise: sign-magnitude little-endian, with a sign bit on the last byte
460
465
  */
461
466
  function encodeScriptNum(value) {
462
- let n = toRawInteger(value, 'ScriptNum');
467
+ let n = toRawInteger$1(value, 'ScriptNum');
463
468
  if (n === 0n)
464
469
  return new Uint8Array();
465
470
  const negative = n < 0n;
@@ -498,13 +503,13 @@ function pushBytes(data) {
498
503
  return Uint8Array.of(OP_0);
499
504
  }
500
505
  if (data.length <= 75) {
501
- return concatBytes(Uint8Array.of(data.length), data);
506
+ return concatBytes$1(Uint8Array.of(data.length), data);
502
507
  }
503
508
  if (data.length <= 0xff) {
504
- return concatBytes(Uint8Array.of(0x4c, data.length), data);
509
+ return concatBytes$1(Uint8Array.of(0x4c, data.length), data);
505
510
  }
506
511
  if (data.length <= 3072) {
507
- return concatBytes(Uint8Array.of(0x4d, data.length & 0xff, (data.length >> 8) & 0xff), data);
512
+ return concatBytes$1(Uint8Array.of(0x4d, data.length & 0xff, (data.length >> 8) & 0xff), data);
508
513
  }
509
514
  throw new Error(`pushBytes: element of ${data.length} bytes exceeds MAX_PQ_SCRIPT_ELEMENT_SIZE (3072)`);
510
515
  }
@@ -513,7 +518,7 @@ function pushBytes(data) {
513
518
  * when available to match how the node's own templates look on the wire.
514
519
  */
515
520
  function pushInt(value) {
516
- const n = toRawInteger(value, 'ScriptNum');
521
+ const n = toRawInteger$1(value, 'ScriptNum');
517
522
  if (n === -1n)
518
523
  return Uint8Array.of(OP_1NEGATE);
519
524
  if (n === 0n)
@@ -524,7 +529,7 @@ function pushInt(value) {
524
529
  return pushBytes(encodeScriptNum(n));
525
530
  }
526
531
  function pushHex(hex) {
527
- return pushBytes(hexToBytes(hex));
532
+ return pushBytes(hexToBytes$1(hex));
528
533
  }
529
534
  /** Fluent assembler for readable script definitions. */
530
535
  class ScriptBuilder {
@@ -555,10 +560,10 @@ class ScriptBuilder {
555
560
  return this;
556
561
  }
557
562
  build() {
558
- return concatBytes(...this.parts);
563
+ return concatBytes$1(...this.parts);
559
564
  }
560
565
  buildHex() {
561
- return bytesToHex(this.build());
566
+ return bytesToHex$1(this.build());
562
567
  }
563
568
  }
564
569
 
@@ -570,7 +575,7 @@ function encodeP2PKHScriptPubKey(pubKeyHash) {
570
575
  if (!(pubKeyHash instanceof Uint8Array) || pubKeyHash.length !== 20) {
571
576
  throw new Error('P2PKH pubKeyHash must be a 20-byte Uint8Array');
572
577
  }
573
- return concatBytes(Uint8Array.of(OP_DUP, OP_HASH160, 0x14), pubKeyHash, Uint8Array.of(OP_EQUALVERIFY, OP_CHECKSIG));
578
+ return concatBytes$1(Uint8Array.of(OP_DUP, OP_HASH160, 0x14), pubKeyHash, Uint8Array.of(OP_EQUALVERIFY, OP_CHECKSIG));
574
579
  }
575
580
 
576
581
  /**
@@ -584,7 +589,7 @@ function encodeP2WPKHScriptPubKey(pubKeyHash) {
584
589
  if (!(pubKeyHash instanceof Uint8Array) || pubKeyHash.length !== 20) {
585
590
  throw new Error('P2WPKH pubKeyHash must be a 20-byte Uint8Array');
586
591
  }
587
- return concatBytes(Uint8Array.of(OP_0, 0x14), pubKeyHash);
592
+ return concatBytes$1(Uint8Array.of(OP_0, 0x14), pubKeyHash);
588
593
  }
589
594
 
590
595
  /**
@@ -599,7 +604,7 @@ function encodeP2WSHScriptPubKey(witnessScriptSha256) {
599
604
  if (!(witnessScriptSha256 instanceof Uint8Array) || witnessScriptSha256.length !== 32) {
600
605
  throw new Error('P2WSH witnessScriptSha256 must be a 32-byte Uint8Array');
601
606
  }
602
- return concatBytes(Uint8Array.of(OP_0, 0x20), witnessScriptSha256);
607
+ return concatBytes$1(Uint8Array.of(OP_0, 0x20), witnessScriptSha256);
603
608
  }
604
609
 
605
610
  /**
@@ -657,7 +662,7 @@ function encodeAuthScriptScriptPubKey(program, witnessVersion = 1) {
657
662
  if (opcode === undefined) {
658
663
  throw new Error(`AuthScript witness version must be 1, 2 or 3, got ${String(witnessVersion)}`);
659
664
  }
660
- return concatBytes(Uint8Array.of(opcode, 0x20), program);
665
+ return concatBytes$1(Uint8Array.of(opcode, 0x20), program);
661
666
  }
662
667
  function assertWitnessScript(ws) {
663
668
  if (!(ws instanceof Uint8Array) || ws.length === 0) {
@@ -835,7 +840,7 @@ function encodeNullDataScript(payload, options = {}) {
835
840
  const parts = [Uint8Array.of(OP_RETURN)];
836
841
  for (const p of payloads)
837
842
  parts.push(pushBytes(p));
838
- return concatBytes(...parts);
843
+ return concatBytes$1(...parts);
839
844
  }
840
845
 
841
846
  /**
@@ -872,10 +877,10 @@ function encodeMultisigRedeemScript({ m, pubKeys }) {
872
877
  parts.push(pushBytes(pk));
873
878
  parts.push(pushInt(pubKeys.length));
874
879
  parts.push(Uint8Array.of(OP_CHECKMULTISIG));
875
- return concatBytes(...parts);
880
+ return concatBytes$1(...parts);
876
881
  }
877
882
  function encodeMultisigRedeemScriptHex(params) {
878
- return bytesToHex(encodeMultisigRedeemScript(params));
883
+ return bytesToHex$1(encodeMultisigRedeemScript(params));
879
884
  }
880
885
  /**
881
886
  * P2SH scriptPubKey wrapping any redeem script. Pass the 20-byte HASH160 of
@@ -886,10 +891,98 @@ function encodeP2SHScriptPubKey(redeemScriptHash160) {
886
891
  if (!(redeemScriptHash160 instanceof Uint8Array) || redeemScriptHash160.length !== 20) {
887
892
  throw new Error('redeemScriptHash160 must be a 20-byte Uint8Array');
888
893
  }
889
- return concatBytes(Uint8Array.of(OP_HASH160, 0x14), redeemScriptHash160, Uint8Array.of(OP_EQUAL));
894
+ return concatBytes$1(Uint8Array.of(OP_HASH160, 0x14), redeemScriptHash160, Uint8Array.of(OP_EQUAL));
890
895
  }
891
896
 
892
897
  /** Exact monetary primitives. This module has no runtime dependencies. */
898
+ /** Normalize a raw integer without preserving an already rounded number. */
899
+ function toRawInteger(value, label = 'amount') {
900
+ if (typeof value === 'bigint')
901
+ return value;
902
+ if (typeof value === 'number' && Number.isSafeInteger(value))
903
+ return BigInt(value);
904
+ if (typeof value === 'string' && /^-?\d+$/.test(value) && value.length <= 100)
905
+ return BigInt(value);
906
+ throw new Error(`${label}: expected an exact integer; use bigint or an integer string for large values`);
907
+ }
908
+
909
+ function ensureHex(hex, label = 'hex') {
910
+ const normalized = String(hex || '').trim().toLowerCase();
911
+ if (!/^[0-9a-f]*$/.test(normalized) || normalized.length % 2 !== 0) {
912
+ throw new Error(`Invalid ${label}: expected even-length hex string`);
913
+ }
914
+ return normalized;
915
+ }
916
+ function hexToBytes(hex) {
917
+ const normalized = ensureHex(hex);
918
+ const bytes = new Uint8Array(normalized.length / 2);
919
+ for (let i = 0; i < normalized.length; i += 2) {
920
+ bytes[i / 2] = Number.parseInt(normalized.slice(i, i + 2), 16);
921
+ }
922
+ return bytes;
923
+ }
924
+ function bytesToHex(bytes) {
925
+ return Array.from(bytes, (value) => value.toString(16).padStart(2, '0')).join('');
926
+ }
927
+ function concatBytes(...parts) {
928
+ const total = parts.reduce((sum, part) => sum + part.length, 0);
929
+ const out = new Uint8Array(total);
930
+ let offset = 0;
931
+ for (const part of parts) {
932
+ out.set(part, offset);
933
+ offset += part.length;
934
+ }
935
+ return out;
936
+ }
937
+ function reverseBytes(bytes) {
938
+ return Uint8Array.from(Array.from(bytes).reverse());
939
+ }
940
+ function u32LE(value) {
941
+ if (!Number.isInteger(value) || value < 0 || value > 0xffffffff) {
942
+ throw new Error(`uint32 out of range: ${value}`);
943
+ }
944
+ const out = new Uint8Array(4);
945
+ const view = new DataView(out.buffer);
946
+ view.setUint32(0, value, true);
947
+ return out;
948
+ }
949
+ function u64LE(value) {
950
+ const bigintValue = toRawInteger(value);
951
+ if (bigintValue < 0n || bigintValue > 0xffffffffffffffffn) {
952
+ throw new Error(`uint64 out of range: ${bigintValue}`);
953
+ }
954
+ const out = new Uint8Array(8);
955
+ let remaining = bigintValue;
956
+ for (let i = 0; i < 8; i += 1) {
957
+ out[i] = Number(remaining & 0xffn);
958
+ remaining >>= 8n;
959
+ }
960
+ return out;
961
+ }
962
+ function compactSize$1(value) {
963
+ const bigintValue = toRawInteger(value);
964
+ if (bigintValue < 0n)
965
+ throw new Error('CompactSize cannot encode negative numbers');
966
+ if (bigintValue < 253n) {
967
+ return Uint8Array.of(Number(bigintValue));
968
+ }
969
+ if (bigintValue <= 0xffffn) {
970
+ return concatBytes(Uint8Array.of(0xfd), u16LE(Number(bigintValue)));
971
+ }
972
+ if (bigintValue <= 0xffffffffn) {
973
+ return concatBytes(Uint8Array.of(0xfe), u32LE(Number(bigintValue)));
974
+ }
975
+ return concatBytes(Uint8Array.of(0xff), u64LE(bigintValue));
976
+ }
977
+ function u16LE(value) {
978
+ if (!Number.isInteger(value) || value < 0 || value > 0xffff) {
979
+ throw new Error(`uint16 out of range: ${value}`);
980
+ }
981
+ const out = new Uint8Array(2);
982
+ const view = new DataView(out.buffer);
983
+ view.setUint16(0, value, true);
984
+ return out;
985
+ }
893
986
 
894
987
  // base-x encoding / decoding
895
988
  // Copyright (c) 2018 base-x contributors
@@ -1749,6 +1842,177 @@ function decodeAddress(address) {
1749
1842
  throw legacyError;
1750
1843
  }
1751
1844
  }
1845
+ function serializeOutput(output) {
1846
+ const scriptPubKey = hexToBytes(ensureHex(output.scriptPubKeyHex, 'scriptPubKeyHex'));
1847
+ return concatBytes(u64LE(output.valueSats), compactSize$1(scriptPubKey.length), scriptPubKey);
1848
+ }
1849
+
1850
+ // Hard deserialization bound, mirroring the node (serialize.h MAX_SIZE):
1851
+ // ReadCompactSize rejects anything above it, canonical or not.
1852
+ const MAX_SIZE = 0x02000000;
1853
+ class ByteReader {
1854
+ bytes;
1855
+ offset = 0;
1856
+ constructor(bytes) {
1857
+ this.bytes = bytes;
1858
+ }
1859
+ need(count) {
1860
+ if (count > this.bytes.length - this.offset) {
1861
+ throw new Error(`Transaction hex truncated: need ${count} more byte(s) at offset ${this.offset}, ` +
1862
+ `${this.bytes.length - this.offset} remaining`);
1863
+ }
1864
+ }
1865
+ readBytes(count) {
1866
+ this.need(count);
1867
+ const slice = this.bytes.subarray(this.offset, this.offset + count);
1868
+ this.offset += count;
1869
+ return slice;
1870
+ }
1871
+ readU8() {
1872
+ return this.readBytes(1)[0];
1873
+ }
1874
+ readU32() {
1875
+ const slice = this.readBytes(4);
1876
+ return (slice[0] | (slice[1] << 8) | (slice[2] << 16) | (slice[3] << 24)) >>> 0;
1877
+ }
1878
+ readU64() {
1879
+ const slice = this.readBytes(8);
1880
+ let value = 0n;
1881
+ for (let i = 7; i >= 0; i -= 1) {
1882
+ value = (value << 8n) | BigInt(slice[i]);
1883
+ }
1884
+ return value;
1885
+ }
1886
+ // Canonical CompactSize with the node's range bound: the shortest encoding
1887
+ // is mandatory and anything above MAX_SIZE throws, exactly like
1888
+ // ReadCompactSize. Lengths are validated against the remaining bytes by the
1889
+ // callers BEFORE any allocation or iteration.
1890
+ readCompactSize() {
1891
+ const first = this.readU8();
1892
+ let value;
1893
+ if (first < 0xfd) {
1894
+ value = first;
1895
+ }
1896
+ else if (first === 0xfd) {
1897
+ const slice = this.readBytes(2);
1898
+ value = slice[0] | (slice[1] << 8);
1899
+ if (value < 0xfd)
1900
+ throw new Error('Non-canonical CompactSize (0xfd form for value < 253)');
1901
+ }
1902
+ else if (first === 0xfe) {
1903
+ value = this.readU32();
1904
+ if (value < 0x10000)
1905
+ throw new Error('Non-canonical CompactSize (0xfe form for value < 0x10000)');
1906
+ }
1907
+ else {
1908
+ const big = this.readU64();
1909
+ if (big < 0x100000000n)
1910
+ throw new Error('Non-canonical CompactSize (0xff form for value < 2^32)');
1911
+ if (big > BigInt(MAX_SIZE))
1912
+ throw new Error(`CompactSize exceeds MAX_SIZE: ${big}`);
1913
+ value = Number(big);
1914
+ }
1915
+ if (value > MAX_SIZE) {
1916
+ throw new Error(`CompactSize exceeds MAX_SIZE: ${value}`);
1917
+ }
1918
+ return value;
1919
+ }
1920
+ /** Read a length prefix that must fit in the remaining bytes at `bytesPerItem`. */
1921
+ readCount(bytesPerItem, label) {
1922
+ const count = this.readCompactSize();
1923
+ if (count * bytesPerItem > this.bytes.length - this.offset) {
1924
+ throw new Error(`Declared ${label} count ${count} does not fit in the remaining ` +
1925
+ `${this.bytes.length - this.offset} byte(s)`);
1926
+ }
1927
+ return count;
1928
+ }
1929
+ get finished() {
1930
+ return this.offset === this.bytes.length;
1931
+ }
1932
+ get position() {
1933
+ return this.offset;
1934
+ }
1935
+ }
1936
+ function readOutpoint(reader) {
1937
+ const txid = bytesToHex(reverseBytes(reader.readBytes(32)));
1938
+ const vout = reader.readU32();
1939
+ return { txid, vout };
1940
+ }
1941
+ function readInput(reader) {
1942
+ const { txid, vout } = readOutpoint(reader);
1943
+ const scriptLength = reader.readCount(1, 'scriptSig');
1944
+ const scriptSigHex = bytesToHex(reader.readBytes(scriptLength));
1945
+ const sequence = reader.readU32();
1946
+ return { txid, vout, scriptSigHex, sequence };
1947
+ }
1948
+ function readOutput(reader) {
1949
+ const valueSats = reader.readU64();
1950
+ const scriptLength = reader.readCount(1, 'scriptPubKey');
1951
+ const scriptPubKeyHex = bytesToHex(reader.readBytes(scriptLength));
1952
+ return { valueSats, scriptPubKeyHex };
1953
+ }
1954
+ // Minimum serialized size per item, used only to bound counts before reading:
1955
+ // input = outpoint(36) + compactSize(1) + sequence(4); output = value(8) +
1956
+ // compactSize(1); witness element = compactSize(1).
1957
+ const MIN_INPUT_SIZE = 41;
1958
+ const MIN_OUTPUT_SIZE = 9;
1959
+ function parseTransaction(hex) {
1960
+ const reader = new ByteReader(hexToBytes(ensureHex(hex, 'transaction hex')));
1961
+ // nVersion is a signed int32 (negative versions exist on-chain historically).
1962
+ const version = reader.readU32() | 0;
1963
+ const inputs = [];
1964
+ const outputs = [];
1965
+ let flags = 0;
1966
+ const vinCount = reader.readCount(MIN_INPUT_SIZE, 'input');
1967
+ if (vinCount === 0) {
1968
+ // Either a dummy marker for the extended (witness) format, or a genuinely
1969
+ // empty vin. Mirrors UnserializeTransaction: a flags byte follows; when it
1970
+ // is non-zero the real vin/vout follow, when zero the vout is NOT read.
1971
+ flags = reader.readU8();
1972
+ if (flags !== 0) {
1973
+ const realVinCount = reader.readCount(MIN_INPUT_SIZE, 'input');
1974
+ for (let i = 0; i < realVinCount; i += 1)
1975
+ inputs.push(readInput(reader));
1976
+ const voutCount = reader.readCount(MIN_OUTPUT_SIZE, 'output');
1977
+ for (let i = 0; i < voutCount; i += 1)
1978
+ outputs.push(readOutput(reader));
1979
+ }
1980
+ }
1981
+ else {
1982
+ for (let i = 0; i < vinCount; i += 1)
1983
+ inputs.push(readInput(reader));
1984
+ const voutCount = reader.readCount(MIN_OUTPUT_SIZE, 'output');
1985
+ for (let i = 0; i < voutCount; i += 1)
1986
+ outputs.push(readOutput(reader));
1987
+ }
1988
+ // NIP-014: vrefin sits between vout and witness, v3 only (even when empty).
1989
+ const vrefin = [];
1990
+ if (version === 3) {
1991
+ const refCount = reader.readCount(36, 'refinput');
1992
+ for (let i = 0; i < refCount; i += 1)
1993
+ vrefin.push(readOutpoint(reader));
1994
+ }
1995
+ if (flags & 1) {
1996
+ flags ^= 1;
1997
+ for (const input of inputs) {
1998
+ const stackSize = reader.readCount(1, 'witness element');
1999
+ const stack = [];
2000
+ for (let i = 0; i < stackSize; i += 1) {
2001
+ const elementLength = reader.readCount(1, 'witness bytes');
2002
+ stack.push(bytesToHex(reader.readBytes(elementLength)));
2003
+ }
2004
+ input.witness = stack;
2005
+ }
2006
+ }
2007
+ if (flags) {
2008
+ throw new Error(`Unknown transaction optional data (flags 0x${flags.toString(16)})`);
2009
+ }
2010
+ const locktime = reader.readU32();
2011
+ if (!reader.finished) {
2012
+ throw new Error(`Trailing bytes after transaction (offset ${reader.position})`);
2013
+ }
2014
+ return { version, inputs, outputs, vrefin, locktime };
2015
+ }
1752
2016
 
1753
2017
  /**
1754
2018
  * Address helpers. Wraps `decodeAddress` from
@@ -1974,8 +2238,8 @@ function parseAssetTransferPayload(payload) {
1974
2238
  * missing OP_DROP after payload, bad magic, unsupported pushdata width).
1975
2239
  */
1976
2240
  function splitAssetWrappedScriptPubKey(spkHex) {
1977
- const normalized = ensureHex(spkHex, 'scriptPubKey');
1978
- const bytes = hexToBytes(normalized);
2241
+ const normalized = ensureHex$1(spkHex, 'scriptPubKey');
2242
+ const bytes = hexToBytes$1(normalized);
1979
2243
  const assetOpAt = findTopLevelAssetOpcode(bytes);
1980
2244
  if (assetOpAt < 0) {
1981
2245
  return { prefixHex: normalized, assetTransfer: null };
@@ -1993,12 +2257,12 @@ function splitAssetWrappedScriptPubKey(spkHex) {
1993
2257
  }
1994
2258
  const { assetName, amountRaw, marker } = parseAssetTransferPayload(payload);
1995
2259
  return {
1996
- prefixHex: bytesToHex(prefix),
2260
+ prefixHex: bytesToHex$1(prefix),
1997
2261
  assetTransfer: {
1998
2262
  assetName,
1999
2263
  amountRaw,
2000
2264
  marker,
2001
- payloadHex: bytesToHex(payload),
2265
+ payloadHex: bytesToHex$1(payload),
2002
2266
  },
2003
2267
  };
2004
2268
  }
@@ -2211,7 +2475,224 @@ function assertSameExpiration(a, b, label) {
2211
2475
  }
2212
2476
 
2213
2477
  /**
2214
- * Partial-Fill Sell Order covenant script (three-branch).
2478
+ * Buyer fill branches shared by both Partial-Fill Sell Order variants
2479
+ * (ECDSA cancel in `./script.ts`, ML-DSA-44 cancel in `./script-pq.ts`).
2480
+ * The variants only differ in their cancel branch; everything after the
2481
+ * outer `OP_ELSE` is emitted and parsed here.
2482
+ *
2483
+ * Input-0 binding. The fill branches read the order's asset amount with
2484
+ * `<0> OP_INPUTASSETFIELD` and constrain outputs 0..2 by fixed index. Input
2485
+ * indices are absolute and Script cannot ask for the index of the input
2486
+ * being evaluated, so without a binding a buyer could:
2487
+ * - put a foreign asset UTXO at input 0 and the order at input 1: the
2488
+ * order then prices the fill by the foreign amount and the rest of the
2489
+ * order leaves through an unconstrained output;
2490
+ * - spend several identical orders together, every one of them satisfied
2491
+ * by the same payment output.
2492
+ * The fill block therefore opens with
2493
+ *
2494
+ * <0x80 0x00> OP_TXHASH <INPUT_ZERO_TXHASH> OP_EQUALVERIFY
2495
+ *
2496
+ * NIP-042 mask 0x0080 commits only to the index of the input being
2497
+ * evaluated, so the digest equals the constant exactly when this covenant
2498
+ * is spent as input 0. At most one order per transaction can take a fill
2499
+ * branch; the seller's cancel branch is not bound.
2500
+ *
2501
+ * Layout (after the variant's `OP_IF <cancel> OP_ELSE`):
2502
+ *
2503
+ * <0x80 0x00> OP_TXHASH <INPUT_ZERO_TXHASH> OP_EQUALVERIFY
2504
+ * OP_IF ← full fill, unlock <1> <0>
2505
+ * [expiration gate]
2506
+ * <0> <2> OP_INPUTASSETFIELD (N = order amount)
2507
+ * DUP <price> MUL <0> OUTPUTVALUE SWAP GE VERIFY (payment value)
2508
+ * <0> OUTPUTSCRIPT <paymentSpk> EQUALVERIFY (payment destination)
2509
+ * DUP <1> <2> OUTPUTASSETFIELD EQUALVERIFY (buyer amount == N)
2510
+ * <1> <1> OUTPUTASSETFIELD <tokenId> EQUALVERIFY (buyer asset name)
2511
+ * DROP <1>
2512
+ * OP_ELSE ← partial fill, unlock <N> <0> <0>
2513
+ * [expiration gate]
2514
+ * payment value, payment destination, buyer amount, buyer name (as above)
2515
+ * <2> OUTPUTAUTHCOMMITMENT <2> TXFIELD EQUALVERIFY (continuation, NIP-023)
2516
+ * <2> <1> OUTPUTASSETFIELD <tokenId> EQUALVERIFY (continuation name)
2517
+ * <2> <2> OUTPUTASSETFIELD OVER <0> <2> INPUTASSETFIELD SWAP SUB EQUALVERIFY
2518
+ * DROP <1>
2519
+ * OP_ENDIF
2520
+ */
2521
+ /** NIP-042 mask (two bytes, little-endian) selecting only the current input index. */
2522
+ const INPUT_INDEX_TXHASH_SELECTOR = Uint8Array.of(TXHASH_CURRENT_INDEX, 0x00);
2523
+ /**
2524
+ * `OP_TXHASH(0x0080)` evaluated at input 0:
2525
+ * `SHA256(tag || tag || 80 00 || 00 00 00 00)` with `tag = SHA256("NeuraiTxHash")`.
2526
+ */
2527
+ const INPUT_ZERO_TXHASH = hexToBytes$1('419632cabaf8bb70b96a8c92c4601a9c2ba11e96841daebc9d98f4835eeb0e36');
2528
+ function appendPaymentAndBuyerChecks(b, p) {
2529
+ // output[0].value >= N * unitPriceSats [ N ]
2530
+ b.op(OP_DUP)
2531
+ .pushInt(p.unitPriceSats)
2532
+ .op(OP_MUL)
2533
+ .pushInt(0)
2534
+ .op(OP_OUTPUTVALUE)
2535
+ .op(OP_SWAP)
2536
+ .op(OP_GREATERTHANOREQUAL)
2537
+ .op(OP_VERIFY);
2538
+ // output[0].scriptPubKey == paymentScriptPubKey [ N ]
2539
+ b.pushInt(0)
2540
+ .op(OP_OUTPUTSCRIPT)
2541
+ .pushBytes(p.paymentScriptPubKey)
2542
+ .op(OP_EQUALVERIFY);
2543
+ // output[1].asset.amount == N [ N ]
2544
+ b.op(OP_DUP)
2545
+ .pushInt(1)
2546
+ .pushInt(ASSETFIELD_AMOUNT)
2547
+ .op(OP_OUTPUTASSETFIELD)
2548
+ .op(OP_EQUALVERIFY);
2549
+ // output[1].asset.name == tokenId [ N ]
2550
+ b.pushInt(1)
2551
+ .pushInt(ASSETFIELD_NAME)
2552
+ .op(OP_OUTPUTASSETFIELD)
2553
+ .pushBytes(p.tokenIdBytes)
2554
+ .op(OP_EQUALVERIFY);
2555
+ }
2556
+ /** Emit the input-0 binding and both fill branches, ending with the inner `OP_ENDIF`. */
2557
+ function appendFillBranches(b, p) {
2558
+ b.pushBytes(INPUT_INDEX_TXHASH_SELECTOR)
2559
+ .op(OP_TXHASH)
2560
+ .pushBytes(INPUT_ZERO_TXHASH)
2561
+ .op(OP_EQUALVERIFY);
2562
+ // ──────── Full fill: N is the whole order, no continuation ────────
2563
+ b.op(OP_IF);
2564
+ appendExpirationGate(b, p.expiration);
2565
+ b.pushInt(0)
2566
+ .pushInt(ASSETFIELD_AMOUNT)
2567
+ .op(OP_INPUTASSETFIELD); // [ N ]
2568
+ appendPaymentAndBuyerChecks(b, p);
2569
+ b.op(OP_DROP).pushInt(1);
2570
+ // ──────── Partial fill: buyer pushes N, remainder continues at output 2 ────────
2571
+ b.op(OP_ELSE);
2572
+ appendExpirationGate(b, p.expiration);
2573
+ appendPaymentAndBuyerChecks(b, p);
2574
+ // Continuation keeps the spent order's AuthScript commitment (NIP-023).
2575
+ b.pushInt(2)
2576
+ .op(OP_OUTPUTAUTHCOMMITMENT)
2577
+ .pushInt(TXFIELD_AUTHSCRIPT_COMMITMENT)
2578
+ .op(OP_TXFIELD)
2579
+ .op(OP_EQUALVERIFY);
2580
+ b.pushInt(2)
2581
+ .pushInt(ASSETFIELD_NAME)
2582
+ .op(OP_OUTPUTASSETFIELD)
2583
+ .pushBytes(p.tokenIdBytes)
2584
+ .op(OP_EQUALVERIFY);
2585
+ // output[2].asset.amount == orderAmount - N
2586
+ b.pushInt(2)
2587
+ .pushInt(ASSETFIELD_AMOUNT)
2588
+ .op(OP_OUTPUTASSETFIELD) // [ N, rem ]
2589
+ .op(OP_OVER) // [ N, rem, N ]
2590
+ .pushInt(0)
2591
+ .pushInt(ASSETFIELD_AMOUNT)
2592
+ .op(OP_INPUTASSETFIELD) // [ N, rem, N, in ]
2593
+ .op(OP_SWAP) // [ N, rem, in, N ]
2594
+ .op(OP_SUB) // [ N, rem, in - N ]
2595
+ .op(OP_EQUALVERIFY);
2596
+ b.op(OP_DROP).pushInt(1);
2597
+ b.op(OP_ENDIF);
2598
+ }
2599
+ function readPaymentAndBuyerChecks(c, label) {
2600
+ expectByte(c, OP_DUP, `OP_DUP (price, ${label})`);
2601
+ const unitPriceSats = readPushPositiveInt(c, `unitPriceSats (${label})`);
2602
+ expectByte(c, OP_MUL, `OP_MUL (${label})`);
2603
+ expectByte(c, OP_0, `OP_0 (payment idx, ${label})`);
2604
+ expectByte(c, OP_OUTPUTVALUE, `OP_OUTPUTVALUE (${label})`);
2605
+ expectByte(c, OP_SWAP, `OP_SWAP (${label})`);
2606
+ expectByte(c, OP_GREATERTHANOREQUAL, `OP_GREATERTHANOREQUAL (${label})`);
2607
+ expectByte(c, OP_VERIFY, `OP_VERIFY (payment, ${label})`);
2608
+ expectByte(c, OP_0, `OP_0 (spk idx, ${label})`);
2609
+ expectByte(c, OP_OUTPUTSCRIPT, `OP_OUTPUTSCRIPT (${label})`);
2610
+ const paymentScriptPubKey = readPush(c, `paymentScriptPubKey (${label})`);
2611
+ expectByte(c, OP_EQUALVERIFY, `OP_EQUALVERIFY (payment spk, ${label})`);
2612
+ expectByte(c, OP_DUP, `OP_DUP (buyer amount, ${label})`);
2613
+ expectByte(c, OP_1, `OP_1 (buyer idx, ${label})`);
2614
+ expectByte(c, OP_2, `OP_2 (AMOUNT sel, ${label})`);
2615
+ expectByte(c, OP_OUTPUTASSETFIELD, `OP_OUTPUTASSETFIELD (buyer amount, ${label})`);
2616
+ expectByte(c, OP_EQUALVERIFY, `OP_EQUALVERIFY (buyer amount, ${label})`);
2617
+ expectByte(c, OP_1, `OP_1 (buyer idx, ${label})`);
2618
+ expectByte(c, OP_1, `OP_1 (NAME sel, ${label})`);
2619
+ expectByte(c, OP_OUTPUTASSETFIELD, `OP_OUTPUTASSETFIELD (buyer name, ${label})`);
2620
+ const tokenId = readPush(c, `tokenId (${label})`);
2621
+ expectByte(c, OP_EQUALVERIFY, `OP_EQUALVERIFY (buyer name, ${label})`);
2622
+ return { unitPriceSats, paymentScriptPubKey, tokenId };
2623
+ }
2624
+ /**
2625
+ * Parse what `appendFillBranches` emits. Both branches must agree on price,
2626
+ * payment destination, tokenId and expiration; any deviation throws.
2627
+ */
2628
+ function readFillBranches(c) {
2629
+ const selector = readPush(c, 'input-0 binding selector');
2630
+ if (!bytesEqual(selector, INPUT_INDEX_TXHASH_SELECTOR)) {
2631
+ throw new Error('parse: fill branches must open with the input-0 binding <0x8000> OP_TXHASH (covenants without it ' +
2632
+ 'can be drained through a foreign input 0 and are not supported)');
2633
+ }
2634
+ expectByte(c, OP_TXHASH, 'OP_TXHASH (input-0 binding)');
2635
+ const digest = readPush(c, 'input-0 binding digest');
2636
+ if (!bytesEqual(digest, INPUT_ZERO_TXHASH)) {
2637
+ throw new Error('parse: input-0 binding digest is not OP_TXHASH(0x0080) at input 0');
2638
+ }
2639
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (input-0 binding)');
2640
+ // ═════ Full fill ═════
2641
+ expectByte(c, OP_IF, 'OP_IF (full fill)');
2642
+ const expirationFull = readOptionalExpirationGate(c, OP_0, 'full');
2643
+ expectByte(c, OP_0, 'OP_0 (input idx, full)');
2644
+ expectByte(c, OP_2, 'OP_2 (AMOUNT sel, full)');
2645
+ expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD (full)');
2646
+ const full = readPaymentAndBuyerChecks(c, 'full');
2647
+ expectByte(c, OP_DROP, 'OP_DROP (full)');
2648
+ expectByte(c, OP_1, 'OP_1 (true, full)');
2649
+ // ═════ Partial fill ═════
2650
+ expectByte(c, OP_ELSE, 'OP_ELSE (partial fill)');
2651
+ const expirationPartial = readOptionalExpirationGate(c, OP_DUP, 'partial');
2652
+ const partial = readPaymentAndBuyerChecks(c, 'partial');
2653
+ expectByte(c, OP_2, 'OP_2 (remainder idx)');
2654
+ expectByte(c, OP_OUTPUTAUTHCOMMITMENT, 'OP_OUTPUTAUTHCOMMITMENT (remainder)');
2655
+ expectByte(c, OP_2, 'OP_2 (TXFIELD sel: AUTHSCRIPT_COMMITMENT)');
2656
+ expectByte(c, OP_TXFIELD, 'OP_TXFIELD');
2657
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder auth)');
2658
+ expectByte(c, OP_2, 'OP_2 (remainder idx)');
2659
+ expectByte(c, OP_1, 'OP_1 (NAME sel)');
2660
+ expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder name)');
2661
+ const remainderTokenId = readPush(c, 'tokenId (remainder)');
2662
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder name)');
2663
+ expectByte(c, OP_2, 'OP_2 (remainder idx)');
2664
+ expectByte(c, OP_2, 'OP_2 (AMOUNT sel)');
2665
+ expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder amount)');
2666
+ expectByte(c, OP_OVER, 'OP_OVER');
2667
+ expectByte(c, OP_0, 'OP_0 (input idx)');
2668
+ expectByte(c, OP_2, 'OP_2 (AMOUNT sel)');
2669
+ expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD');
2670
+ expectByte(c, OP_SWAP, 'OP_SWAP');
2671
+ expectByte(c, OP_SUB, 'OP_SUB');
2672
+ expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder amount)');
2673
+ expectByte(c, OP_DROP, 'OP_DROP (partial)');
2674
+ expectByte(c, OP_1, 'OP_1 (true, partial)');
2675
+ expectByte(c, OP_ENDIF, 'OP_ENDIF (fill branches)');
2676
+ if (!bytesEqual(full.tokenId, partial.tokenId) || !bytesEqual(partial.tokenId, remainderTokenId)) {
2677
+ throw new Error('parse: tokenId differs between the fill checks');
2678
+ }
2679
+ if (full.unitPriceSats !== partial.unitPriceSats) {
2680
+ throw new Error('parse: unitPriceSats differs between full-fill and partial-fill branches');
2681
+ }
2682
+ if (!bytesEqual(full.paymentScriptPubKey, partial.paymentScriptPubKey)) {
2683
+ throw new Error('parse: payment scriptPubKey differs between full-fill and partial-fill branches');
2684
+ }
2685
+ assertSameExpiration(expirationFull, expirationPartial, 'full-fill and partial-fill branches');
2686
+ return {
2687
+ paymentScriptPubKey: full.paymentScriptPubKey,
2688
+ tokenId: new TextDecoder('utf-8', { fatal: true }).decode(full.tokenId),
2689
+ unitPriceSats: full.unitPriceSats,
2690
+ expiration: expirationFull
2691
+ };
2692
+ }
2693
+
2694
+ /**
2695
+ * Partial-Fill Sell Order covenant script (three-branch), ECDSA cancel.
2215
2696
  *
2216
2697
  * The covenant has three branches selected by the top of the unlock stack:
2217
2698
  *
@@ -2231,11 +2712,8 @@ function assertSameExpiration(a, b, label) {
2231
2712
  * amount == inputAmount - N)
2232
2713
  * output[3+] = optional buyer change (not constrained by the covenant)
2233
2714
  *
2234
- * Continuity — the remainder UTXO reuses the spent covenant's AuthScript v1
2235
- * commitment via `OP_OUTPUTAUTHCOMMITMENT(2) == OP_TXFIELD(0x02)` (NIP-023).
2236
- * Comparing commitments rather than full scriptPubKeys is mandatory because
2237
- * the remainder's asset wrapper carries a different `amountRaw` than the
2238
- * spent UTXO's wrapper.
2715
+ * The order must be input 0 for either fill branch to succeed: see the
2716
+ * input-0 binding in `./fill-branches.ts`.
2239
2717
  *
2240
2718
  * Unlock stack shapes (scriptSig pushes, top → bottom):
2241
2719
  *
@@ -2243,10 +2721,12 @@ function assertSameExpiration(a, b, label) {
2243
2721
  * Full fill: <1> <0> (full-flag=1, cancel-flag=0)
2244
2722
  * Partial fill: <N> <0> <0> (N, full-flag=0, cancel-flag=0)
2245
2723
  *
2246
- * The cancel branch uses classical ECDSA (`OP_HASH160 + OP_CHECKSIG`) and
2247
- * commits to a 20-byte PKH — this variant only accepts legacy P2PKH
2248
- * addresses as the seller destination. For AuthScript bech32m destinations
2249
- * and post-quantum signing, use `buildPartialFillScriptPQ`.
2724
+ * The cancel branch uses classical ECDSA (`OP_HASH160 + OP_CHECKSIG`)
2725
+ * against a 20-byte key hash. The payment destination is independent of
2726
+ * that key: a legacy P2PKH seller passes `sellerAddress` (both at once),
2727
+ * any other seller with a secp256k1 key — typically a strict ECDSA v3
2728
+ * `nq1r…` wallet — passes `paymentAddress` and `sellerPubKeyHash`. For
2729
+ * post-quantum cancellation use `buildPartialFillScriptPQ`.
2250
2730
  */
2251
2731
  const ASSET_NAME_MAX$1 = 32;
2252
2732
  function decodeSellerAddress(sellerAddress) {
@@ -2255,8 +2735,8 @@ function decodeSellerAddress(sellerAddress) {
2255
2735
  }
2256
2736
  const decoded = decodeAddress(sellerAddress);
2257
2737
  if (decoded.type !== 'p2pkh') {
2258
- throw new Error(`sellerAddress must be a legacy P2PKH address (the legacy partial-fill covenant uses OP_HASH160 + OP_CHECKSIG); ` +
2259
- `got ${decoded.type}. Use buildPartialFillScriptPQ for AuthScript destinations.`);
2738
+ throw new Error(`sellerAddress must be a legacy P2PKH address; got ${decoded.type}. A seller with another address ` +
2739
+ `type passes paymentAddress and sellerPubKeyHash, or uses buildPartialFillScriptPQ for a PQ key.`);
2260
2740
  }
2261
2741
  const pkh = Uint8Array.from(decoded.hash);
2262
2742
  if (pkh.length !== 20) {
@@ -2264,6 +2744,27 @@ function decodeSellerAddress(sellerAddress) {
2264
2744
  }
2265
2745
  return pkh;
2266
2746
  }
2747
+ /** Cancel key hash and payment scriptPubKey from either form of seller params. */
2748
+ function resolveSeller(params) {
2749
+ const { sellerAddress, paymentAddress, sellerPubKeyHash } = params;
2750
+ if (sellerAddress !== undefined) {
2751
+ if (paymentAddress !== undefined || sellerPubKeyHash !== undefined) {
2752
+ throw new Error('pass either sellerAddress, or paymentAddress with sellerPubKeyHash, not both');
2753
+ }
2754
+ const pkh = decodeSellerAddress(sellerAddress);
2755
+ return { sellerPubKeyHash: pkh, paymentScriptPubKey: encodeP2PKHScriptPubKey(pkh) };
2756
+ }
2757
+ if (paymentAddress === undefined || sellerPubKeyHash === undefined) {
2758
+ throw new Error('sellerAddress, or paymentAddress with sellerPubKeyHash, is required');
2759
+ }
2760
+ if (!(sellerPubKeyHash instanceof Uint8Array) || sellerPubKeyHash.length !== 20) {
2761
+ throw new Error('sellerPubKeyHash must be a 20-byte Uint8Array (HASH160 of the compressed public key)');
2762
+ }
2763
+ return {
2764
+ sellerPubKeyHash: Uint8Array.from(sellerPubKeyHash),
2765
+ paymentScriptPubKey: encodeSellerScriptPubKey(paymentAddress).bytes
2766
+ };
2767
+ }
2267
2768
  function assertTokenId$1(tokenId) {
2268
2769
  if (typeof tokenId !== 'string' || tokenId.length === 0) {
2269
2770
  throw new Error('tokenId is required');
@@ -2291,13 +2792,11 @@ function assertPrice$1(priceSats) {
2291
2792
  * Returns raw bytes; wrap with `bytesToHex` for wire format.
2292
2793
  */
2293
2794
  function buildPartialFillScript(params) {
2294
- const { sellerAddress, tokenId, unitPriceSats } = params;
2295
- const sellerPubKeyHash = decodeSellerAddress(sellerAddress);
2795
+ const { tokenId, unitPriceSats } = params;
2796
+ const { sellerPubKeyHash, paymentScriptPubKey } = resolveSeller(params);
2296
2797
  assertTokenId$1(tokenId);
2297
2798
  assertPrice$1(unitPriceSats);
2298
2799
  const expiration = assertExpiration(params.expiration);
2299
- const sellerScriptPubKey = encodeP2PKHScriptPubKey(sellerPubKeyHash);
2300
- const tokenIdBytes = new TextEncoder().encode(tokenId);
2301
2800
  const b = new ScriptBuilder();
2302
2801
  // ════════ Cancel branch (outer IF) ════════
2303
2802
  // scriptSig: <sig> <pubkey> <1>
@@ -2306,113 +2805,19 @@ function buildPartialFillScript(params) {
2306
2805
  .pushBytes(sellerPubKeyHash)
2307
2806
  .op(OP_EQUALVERIFY, OP_CHECKSIG)
2308
2807
  .op(OP_ELSE);
2309
- // ════════ Fill branches (outer ELSE: inner IF/ELSE) ════════
2310
- b.op(OP_IF);
2311
- // ──────── Full-fill branch (inner IF) ────────
2312
- // scriptSig: <1> <0> ( full-flag=1, cancel-flag=0 )
2313
- // Stack entering: [ ]
2314
- //
2315
- // N is derived from the spent UTXO's asset amount, so the buyer does not
2316
- // push N. The entire covenant is drained to vout[1]; no vout[2] is
2317
- // constrained and none is required (consensus forbids zero-amount asset
2318
- // transfers, so the partial-fill continuity check is simply skipped).
2319
- appendExpirationGate(b, expiration);
2320
- // 1. N = inputAmount
2321
- b.pushInt(0)
2322
- .pushInt(ASSETFIELD_AMOUNT)
2323
- .op(OP_INPUTASSETFIELD); // [ N ]
2324
- // 2. output[0].value >= N * unitPriceSats
2325
- b.op(OP_DUP) // [ N, N ]
2326
- .pushInt(unitPriceSats) // [ N, N, price ]
2327
- .op(OP_MUL) // [ N, N*price ]
2328
- .pushInt(0) // [ N, N*price, 0 ]
2329
- .op(OP_OUTPUTVALUE) // [ N, N*price, value ]
2330
- .op(OP_SWAP) // [ N, value, N*price ]
2331
- .op(OP_GREATERTHANOREQUAL)
2332
- .op(OP_VERIFY); // [ N ]
2333
- // 3. output[0].scriptPubKey == sellerScriptPubKey
2334
- b.pushInt(0)
2335
- .op(OP_OUTPUTSCRIPT) // [ N, spk_out0 ]
2336
- .pushBytes(sellerScriptPubKey)
2337
- .op(OP_EQUALVERIFY); // [ N ]
2338
- // 4. output[1].asset.amount == N
2339
- b.op(OP_DUP) // [ N, N ]
2340
- .pushInt(1)
2341
- .pushInt(ASSETFIELD_AMOUNT)
2342
- .op(OP_OUTPUTASSETFIELD) // [ N, N, amount_out1 ]
2343
- .op(OP_EQUALVERIFY); // [ N ]
2344
- // 5. output[1].asset.name == tokenId
2345
- b.pushInt(1)
2346
- .pushInt(ASSETFIELD_NAME)
2347
- .op(OP_OUTPUTASSETFIELD) // [ N, name_out1 ]
2348
- .pushBytes(tokenIdBytes)
2349
- .op(OP_EQUALVERIFY); // [ N ]
2350
- // 6. Drop N, leave TRUE on the stack.
2351
- b.op(OP_DROP).pushInt(1);
2352
- // ──────── Partial-fill branch (inner ELSE) ────────
2353
- // scriptSig: <N> <0> <0> ( N, full-flag=0, cancel-flag=0 )
2354
- // Stack entering: [ N ]
2355
- b.op(OP_ELSE);
2356
- appendExpirationGate(b, expiration);
2357
- // 1. Payment value (output 0) >= N * unitPriceSats
2358
- b.op(OP_DUP) // [ N, N ]
2359
- .pushInt(unitPriceSats) // [ N, N, price ]
2360
- .op(OP_MUL) // [ N, N*price ]
2361
- .pushInt(0) // [ N, N*price, 0 ]
2362
- .op(OP_OUTPUTVALUE) // [ N, N*price, value ]
2363
- .op(OP_SWAP) // [ N, value, N*price ]
2364
- .op(OP_GREATERTHANOREQUAL)
2365
- .op(OP_VERIFY); // [ N ]
2366
- // 2. Payment scriptPubKey (output 0)
2367
- b.pushInt(0)
2368
- .op(OP_OUTPUTSCRIPT) // [ N, spk_out0 ]
2369
- .pushBytes(sellerScriptPubKey)
2370
- .op(OP_EQUALVERIFY); // [ N ]
2371
- // 3. Asset to buyer (output 1) amount == N
2372
- b.op(OP_DUP) // [ N, N ]
2373
- .pushInt(1)
2374
- .pushInt(ASSETFIELD_AMOUNT)
2375
- .op(OP_OUTPUTASSETFIELD)
2376
- .op(OP_EQUALVERIFY); // [ N ]
2377
- // 4. Asset to buyer (output 1) name == tokenId
2378
- b.pushInt(1)
2379
- .pushInt(ASSETFIELD_NAME)
2380
- .op(OP_OUTPUTASSETFIELD)
2381
- .pushBytes(tokenIdBytes)
2382
- .op(OP_EQUALVERIFY); // [ N ]
2383
- // 5. Continuation (output 2): same AuthScript commitment as spent UTXO
2384
- // (NIP-023 — see file-level comment).
2385
- b.pushInt(2)
2386
- .op(OP_OUTPUTAUTHCOMMITMENT)
2387
- .pushInt(TXFIELD_AUTHSCRIPT_COMMITMENT)
2388
- .op(OP_TXFIELD)
2389
- .op(OP_EQUALVERIFY); // [ N ]
2390
- // 6. Continuation name == tokenId
2391
- b.pushInt(2)
2392
- .pushInt(ASSETFIELD_NAME)
2393
- .op(OP_OUTPUTASSETFIELD)
2394
- .pushBytes(tokenIdBytes)
2395
- .op(OP_EQUALVERIFY); // [ N ]
2396
- // 7. Continuation amount == inputAmount - N
2397
- b.pushInt(2)
2398
- .pushInt(ASSETFIELD_AMOUNT)
2399
- .op(OP_OUTPUTASSETFIELD) // [ N, rem_amount ]
2400
- .op(OP_OVER) // [ N, rem_amount, N ]
2401
- .pushInt(0) // [ N, rem_amount, N, 0 ]
2402
- .pushInt(ASSETFIELD_AMOUNT)
2403
- .op(OP_INPUTASSETFIELD) // [ N, rem_amount, N, in_amount ]
2404
- .op(OP_SWAP) // [ N, rem_amount, in_amount, N ]
2405
- .op(OP_SUB) // [ N, rem_amount, in_amount - N ]
2406
- .op(OP_EQUALVERIFY); // [ N ]
2407
- // 8. Drop N, leave TRUE on the stack.
2408
- b.op(OP_DROP).pushInt(1);
2409
- b.op(OP_ENDIF); // closes full/partial inner IF
2808
+ // ════════ Fill branches (outer ELSE) ════════
2809
+ appendFillBranches(b, {
2810
+ paymentScriptPubKey,
2811
+ tokenIdBytes: new TextEncoder().encode(tokenId),
2812
+ unitPriceSats,
2813
+ expiration
2814
+ });
2410
2815
  b.op(OP_ENDIF); // closes outer cancel/fill IF
2411
2816
  return b.build();
2412
2817
  }
2413
2818
  /** Hex convenience wrapper for `buildPartialFillScript`. */
2414
2819
  function buildPartialFillScriptHex(params) {
2415
- return bytesToHex(buildPartialFillScript(params));
2820
+ return bytesToHex$1(buildPartialFillScript(params));
2416
2821
  }
2417
2822
 
2418
2823
  /**
@@ -2436,11 +2841,11 @@ function buildPartialFillScriptHex(params) {
2436
2841
  *
2437
2842
  * The message that gets signed is **SHA256(OP_TXHASH(selector))** — CSFS
2438
2843
  * single-SHA256s its message argument before verification, and OP_TXHASH
2439
- * produces its own 32-byte hash, so the seller computes:
2440
- * `sign(pqSeckey, SHA256(doubleSHA256(selected_tx_fields)))`
2844
+ * produces its own 32-byte NIP-042 tagged hash, so the seller computes:
2845
+ * `sign(pqSeckey, SHA256(TaggedHash("NeuraiTxHash", mask || selected_tx_fields)))`
2441
2846
  *
2442
- * Fill branches are identical in structure to the legacy variant — see
2443
- * `./script.ts` for the three-branch layout description.
2847
+ * The fill branches, including the input-0 binding, are shared with the
2848
+ * ECDSA variant — see `./fill-branches.ts`.
2444
2849
  */
2445
2850
  const ASSET_NAME_MAX = 32;
2446
2851
  const DEFAULT_PQ_TXHASH_SELECTOR = 0x1ff;
@@ -2508,104 +2913,18 @@ function buildPartialFillScriptPQ(params) {
2508
2913
  .op(OP_SWAP) // [ sig, txHash, pubKey ]
2509
2914
  .op(OP_CHECKSIGFROMSTACK) // [ 1 | 0 ]
2510
2915
  .op(OP_ELSE);
2511
- // ════════ Fill branches (inner IF: full / ELSE: partial) ════════
2512
- b.op(OP_IF);
2513
- // ──────── Full-fill branch ────────
2514
- // scriptSig: <1> <0>
2515
- // Stack entering: [ ]
2516
- // 1. N = inputAmount
2517
- appendExpirationGate(b, expiration);
2518
- b.pushInt(0)
2519
- .pushInt(ASSETFIELD_AMOUNT)
2520
- .op(OP_INPUTASSETFIELD);
2521
- // 2. Payment value (output 0) >= N * unitPriceSats
2522
- b.op(OP_DUP)
2523
- .pushInt(unitPriceSats)
2524
- .op(OP_MUL)
2525
- .pushInt(0)
2526
- .op(OP_OUTPUTVALUE)
2527
- .op(OP_SWAP)
2528
- .op(OP_GREATERTHANOREQUAL)
2529
- .op(OP_VERIFY);
2530
- // 3. Payment scriptPubKey (output 0)
2531
- b.pushInt(0)
2532
- .op(OP_OUTPUTSCRIPT)
2533
- .pushBytes(payment.bytes)
2534
- .op(OP_EQUALVERIFY);
2535
- // 4. Asset to buyer (output 1) amount == N
2536
- b.op(OP_DUP)
2537
- .pushInt(1)
2538
- .pushInt(ASSETFIELD_AMOUNT)
2539
- .op(OP_OUTPUTASSETFIELD)
2540
- .op(OP_EQUALVERIFY);
2541
- // 5. Asset to buyer (output 1) name == tokenId
2542
- b.pushInt(1)
2543
- .pushInt(ASSETFIELD_NAME)
2544
- .op(OP_OUTPUTASSETFIELD)
2545
- .pushBytes(tokenIdBytes)
2546
- .op(OP_EQUALVERIFY);
2547
- b.op(OP_DROP).pushInt(1);
2548
- // ──────── Partial-fill branch ────────
2549
- // scriptSig: <N> <0> <0>
2550
- // Stack entering: [ N ]
2551
- b.op(OP_ELSE);
2552
- appendExpirationGate(b, expiration);
2553
- // 1. Payment value (output 0) >= N * unitPriceSats
2554
- b.op(OP_DUP)
2555
- .pushInt(unitPriceSats)
2556
- .op(OP_MUL)
2557
- .pushInt(0)
2558
- .op(OP_OUTPUTVALUE)
2559
- .op(OP_SWAP)
2560
- .op(OP_GREATERTHANOREQUAL)
2561
- .op(OP_VERIFY);
2562
- // 2. Payment scriptPubKey (output 0)
2563
- b.pushInt(0)
2564
- .op(OP_OUTPUTSCRIPT)
2565
- .pushBytes(payment.bytes)
2566
- .op(OP_EQUALVERIFY);
2567
- // 3. Asset to buyer (output 1) amount == N
2568
- b.op(OP_DUP)
2569
- .pushInt(1)
2570
- .pushInt(ASSETFIELD_AMOUNT)
2571
- .op(OP_OUTPUTASSETFIELD)
2572
- .op(OP_EQUALVERIFY);
2573
- // 4. Asset to buyer (output 1) name == tokenId
2574
- b.pushInt(1)
2575
- .pushInt(ASSETFIELD_NAME)
2576
- .op(OP_OUTPUTASSETFIELD)
2577
- .pushBytes(tokenIdBytes)
2578
- .op(OP_EQUALVERIFY);
2579
- // 5. Continuation (output 2): same AuthScript commitment as spent (NIP-023)
2580
- b.pushInt(2)
2581
- .op(OP_OUTPUTAUTHCOMMITMENT)
2582
- .pushInt(TXFIELD_AUTHSCRIPT_COMMITMENT)
2583
- .op(OP_TXFIELD)
2584
- .op(OP_EQUALVERIFY);
2585
- // 6. Continuation name == tokenId
2586
- b.pushInt(2)
2587
- .pushInt(ASSETFIELD_NAME)
2588
- .op(OP_OUTPUTASSETFIELD)
2589
- .pushBytes(tokenIdBytes)
2590
- .op(OP_EQUALVERIFY);
2591
- // 7. Continuation amount == inputAmount - N
2592
- b.pushInt(2)
2593
- .pushInt(ASSETFIELD_AMOUNT)
2594
- .op(OP_OUTPUTASSETFIELD)
2595
- .op(OP_OVER)
2596
- .pushInt(0)
2597
- .pushInt(ASSETFIELD_AMOUNT)
2598
- .op(OP_INPUTASSETFIELD)
2599
- .op(OP_SWAP)
2600
- .op(OP_SUB)
2601
- .op(OP_EQUALVERIFY);
2602
- b.op(OP_DROP).pushInt(1);
2603
- b.op(OP_ENDIF); // full / partial
2916
+ // ════════ Fill branches (outer ELSE) ════════
2917
+ appendFillBranches(b, {
2918
+ paymentScriptPubKey: payment.bytes,
2919
+ tokenIdBytes,
2920
+ unitPriceSats,
2921
+ expiration
2922
+ });
2604
2923
  b.op(OP_ENDIF); // cancel / fill
2605
2924
  return b.build();
2606
2925
  }
2607
2926
  function buildPartialFillScriptPQHex(params) {
2608
- return bytesToHex(buildPartialFillScriptPQ(params));
2927
+ return bytesToHex$1(buildPartialFillScriptPQ(params));
2609
2928
  }
2610
2929
 
2611
2930
  /**
@@ -2662,7 +2981,7 @@ function buildFillScriptSig(amount, total) {
2662
2981
  return b.build();
2663
2982
  }
2664
2983
  function buildFillScriptSigHex(amount, total) {
2665
- return bytesToHex(buildFillScriptSig(amount, total));
2984
+ return bytesToHex$1(buildFillScriptSig(amount, total));
2666
2985
  }
2667
2986
  /**
2668
2987
  * Unlock the covenant via the seller's cancel branch.
@@ -2692,7 +3011,7 @@ function buildCancelScriptSig(signatureDer, pubKey) {
2692
3011
  .build();
2693
3012
  }
2694
3013
  function buildCancelScriptSigHex(signatureDer, pubKey) {
2695
- return bytesToHex(buildCancelScriptSig(signatureDer, pubKey));
3014
+ return bytesToHex$1(buildCancelScriptSig(signatureDer, pubKey));
2696
3015
  }
2697
3016
 
2698
3017
  /**
@@ -2736,7 +3055,7 @@ function buildCancelScriptSigPQ(sigPQ, pubKey) {
2736
3055
  .build();
2737
3056
  }
2738
3057
  function buildCancelScriptSigPQHex(sigPQ, pubKey) {
2739
- return bytesToHex(buildCancelScriptSigPQ(sigPQ, pubKey));
3058
+ return bytesToHex$1(buildCancelScriptSigPQ(sigPQ, pubKey));
2740
3059
  }
2741
3060
 
2742
3061
  /**
@@ -2823,24 +3142,22 @@ function buildCancelWitnessStackPQ(sigPQ, pubKey) {
2823
3142
  }
2824
3143
 
2825
3144
  /**
2826
- * Parser for the Partial-Fill Sell Order covenant (three-branch).
2827
- *
2828
- * Extracts `(sellerPubKeyHash, unitPriceSats, tokenId)` from a scriptPubKey
2829
- * that was produced by `buildPartialFillScript`. Walks the exact byte
2830
- * layout emitted by the builder and fails on any deviation — this is
2831
- * deliberate, so a downstream indexer can unambiguously classify a UTXO as
2832
- * "partial-fill order" or "unknown script" with no false positives.
3145
+ * Parser for the Partial-Fill Sell Order covenant (three-branch, ECDSA cancel).
2833
3146
  *
2834
- * The full-fill and partial-fill branches share `(sellerScriptPubKey,
2835
- * unitPriceSats, tokenId)`. The parser reads both branches and verifies
2836
- * consistency; inconsistency throws.
3147
+ * Extracts `(sellerPubKeyHash, paymentScriptPubKey, unitPriceSats, tokenId)`
3148
+ * from a scriptPubKey that was produced by `buildPartialFillScript`. Walks
3149
+ * the exact byte layout emitted by the builder and fails on any deviation —
3150
+ * this is deliberate, so a downstream indexer can unambiguously classify a
3151
+ * UTXO as "partial-fill order" or "unknown script" with no false positives.
3152
+ * Covenants built before the input-0 binding (neurai-scripts < 0.10.0) are
3153
+ * rejected: their fill branches can be drained through a foreign input 0.
2837
3154
  */
2838
3155
  /**
2839
3156
  * Parse a covenant scriptPubKey and extract its parameters. Throws with a
2840
3157
  * descriptive message if the bytes don't match the partial-fill template.
2841
3158
  */
2842
3159
  function parsePartialFillScript(script, network = 'xna-test') {
2843
- const bytes = typeof script === 'string' ? hexToBytes(script) : script;
3160
+ const bytes = typeof script === 'string' ? hexToBytes$1(script) : script;
2844
3161
  const c = makeCursor(bytes);
2845
3162
  // ═════ Outer IF — Cancel branch ═════
2846
3163
  expectByte(c, OP_IF, 'OP_IF (outer cancel)');
@@ -2853,130 +3170,18 @@ function parsePartialFillScript(script, network = 'xna-test') {
2853
3170
  expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (cancel)');
2854
3171
  expectByte(c, OP_CHECKSIG, 'OP_CHECKSIG (cancel)');
2855
3172
  expectByte(c, OP_ELSE, 'OP_ELSE (outer → fill)');
2856
- // ═════ Inner IF — Full-fill branch ═════
2857
- expectByte(c, OP_IF, 'OP_IF (inner full-fill)');
2858
- const expirationFull = readOptionalExpirationGate(c, OP_0, 'full');
2859
- // N = inputAmount
2860
- expectByte(c, OP_0, 'OP_0 (input idx, full)');
2861
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel, full)');
2862
- expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD (full)');
2863
- // payment value check
2864
- expectByte(c, OP_DUP, 'OP_DUP (price, full)');
2865
- const unitPriceSatsFull = readPushPositiveInt(c, 'unitPriceSats (full)');
2866
- expectByte(c, OP_MUL, 'OP_MUL (full)');
2867
- expectByte(c, OP_0, 'OP_0 (payment idx, full)');
2868
- expectByte(c, OP_OUTPUTVALUE, 'OP_OUTPUTVALUE (full)');
2869
- expectByte(c, OP_SWAP, 'OP_SWAP (full)');
2870
- expectByte(c, OP_GREATERTHANOREQUAL, 'OP_GREATERTHANOREQUAL (full)');
2871
- expectByte(c, OP_VERIFY, 'OP_VERIFY (payment full)');
2872
- // payment spk
2873
- expectByte(c, OP_0, 'OP_0 (spk idx, full)');
2874
- expectByte(c, OP_OUTPUTSCRIPT, 'OP_OUTPUTSCRIPT (payment full)');
2875
- const sellerSpkFull = readPush(c, 'sellerScriptPubKey (full)');
2876
- const expectedSpk = new Uint8Array([
2877
- OP_DUP, OP_HASH160, 0x14, ...sellerPubKeyHash, OP_EQUALVERIFY, OP_CHECKSIG
2878
- ]);
2879
- if (!bytesEqual(sellerSpkFull, expectedSpk)) {
2880
- throw new Error('parse: full-fill seller scriptPubKey does not match the cancel PKH');
2881
- }
2882
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (payment spk full)');
2883
- // buyer amount == N (full)
2884
- expectByte(c, OP_DUP, 'OP_DUP (buyer amount, full)');
2885
- expectByte(c, OP_1, 'OP_1 (buyer idx, full)');
2886
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel, full)');
2887
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer amount, full)');
2888
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer amount, full)');
2889
- // buyer name == tokenId (full)
2890
- expectByte(c, OP_1, 'OP_1 (buyer idx, full)');
2891
- expectByte(c, OP_1, 'OP_1 (NAME sel, full)');
2892
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer name, full)');
2893
- const tokenIdFull = readPush(c, 'tokenId (full)');
2894
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer name, full)');
2895
- // tail (full)
2896
- expectByte(c, OP_DROP, 'OP_DROP (full)');
2897
- expectByte(c, OP_1, 'OP_1 (true, full)');
2898
- expectByte(c, OP_ELSE, 'OP_ELSE (inner → partial fill)');
2899
- // ═════ Inner ELSE — Partial-fill branch ═════
2900
- const expirationPartial = readOptionalExpirationGate(c, OP_DUP, 'partial');
2901
- // Payment value
2902
- expectByte(c, OP_DUP, 'OP_DUP (price, partial)');
2903
- const unitPriceSatsPartial = readPushPositiveInt(c, 'unitPriceSats (partial)');
2904
- expectByte(c, OP_MUL, 'OP_MUL (partial)');
2905
- expectByte(c, OP_0, 'OP_0 (pay idx, partial)');
2906
- expectByte(c, OP_OUTPUTVALUE, 'OP_OUTPUTVALUE (partial)');
2907
- expectByte(c, OP_SWAP, 'OP_SWAP (partial)');
2908
- expectByte(c, OP_GREATERTHANOREQUAL, 'OP_GREATERTHANOREQUAL (partial)');
2909
- expectByte(c, OP_VERIFY, 'OP_VERIFY (payment partial)');
2910
- // Payment spk
2911
- expectByte(c, OP_0, 'OP_0 (spk idx, partial)');
2912
- expectByte(c, OP_OUTPUTSCRIPT, 'OP_OUTPUTSCRIPT (payment partial)');
2913
- const sellerSpkPartial = readPush(c, 'sellerScriptPubKey (partial)');
2914
- if (!bytesEqual(sellerSpkPartial, expectedSpk)) {
2915
- throw new Error('parse: partial-fill seller scriptPubKey does not match the cancel PKH');
2916
- }
2917
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (payment spk partial)');
2918
- // Buyer amount
2919
- expectByte(c, OP_DUP, 'OP_DUP (buyer amount, partial)');
2920
- expectByte(c, OP_1, 'OP_1 (buyer idx, partial)');
2921
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel, partial)');
2922
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer amount, partial)');
2923
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer amount, partial)');
2924
- // Buyer name
2925
- expectByte(c, OP_1, 'OP_1 (buyer idx, partial)');
2926
- expectByte(c, OP_1, 'OP_1 (NAME sel, partial)');
2927
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer name, partial)');
2928
- const tokenIdPartial1 = readPush(c, 'tokenId partial #1');
2929
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer name, partial)');
2930
- // Continuation commitment
2931
- expectByte(c, OP_2, 'OP_2 (remainder idx)');
2932
- expectByte(c, OP_OUTPUTAUTHCOMMITMENT, 'OP_OUTPUTAUTHCOMMITMENT (remainder)');
2933
- expectByte(c, OP_2, 'OP_2 (TXFIELD sel: AUTHSCRIPT_COMMITMENT)');
2934
- expectByte(c, OP_TXFIELD, 'OP_TXFIELD');
2935
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder auth)');
2936
- // Continuation name
2937
- expectByte(c, OP_2, 'OP_2 (remainder idx)');
2938
- expectByte(c, OP_1, 'OP_1 (NAME sel)');
2939
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder name)');
2940
- const tokenIdPartial2 = readPush(c, 'tokenId partial #2');
2941
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder name)');
2942
- // Continuation amount
2943
- expectByte(c, OP_2, 'OP_2 (remainder idx)');
2944
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel)');
2945
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder amount)');
2946
- expectByte(c, OP_OVER, 'OP_OVER');
2947
- expectByte(c, OP_0, 'OP_0 (input idx)');
2948
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel)');
2949
- expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD');
2950
- expectByte(c, OP_SWAP, 'OP_SWAP');
2951
- expectByte(c, OP_SUB, 'OP_SUB');
2952
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder amount)');
2953
- // Tail (partial)
2954
- expectByte(c, OP_DROP, 'OP_DROP (partial)');
2955
- expectByte(c, OP_1, 'OP_1 (true, partial)');
2956
- // Close the nested structure
2957
- expectByte(c, OP_ENDIF, 'OP_ENDIF (inner)');
3173
+ // ═════ Outer ELSE — input-0 binding + fill branches ═════
3174
+ const fill = readFillBranches(c);
2958
3175
  expectByte(c, OP_ENDIF, 'OP_ENDIF (outer)');
2959
3176
  assertTrailing(c);
2960
- // Cross-branch consistency: all three (full token, partial name #1,
2961
- // partial name #2) must agree, and the two unit prices must match.
2962
- if (!bytesEqual(tokenIdFull, tokenIdPartial1)) {
2963
- throw new Error('parse: tokenId differs between full-fill and partial-fill branches');
2964
- }
2965
- if (!bytesEqual(tokenIdPartial1, tokenIdPartial2)) {
2966
- throw new Error('parse: tokenId bytes differ between buyer and remainder partial checks');
2967
- }
2968
- if (unitPriceSatsFull !== unitPriceSatsPartial) {
2969
- throw new Error('parse: unitPriceSats differs between full-fill and partial-fill branches');
2970
- }
2971
- assertSameExpiration(expirationFull, expirationPartial, 'full-fill and partial-fill branches');
2972
- const tokenId = new TextDecoder('utf-8', { fatal: true }).decode(tokenIdFull);
2973
3177
  return {
2974
3178
  network,
2975
3179
  sellerPubKeyHash,
2976
- unitPriceSats: unitPriceSatsFull,
2977
- tokenId,
2978
- expiration: expirationFull,
2979
- scriptHex: bytesToHex(bytes)
3180
+ paymentScriptPubKey: fill.paymentScriptPubKey,
3181
+ unitPriceSats: fill.unitPriceSats,
3182
+ tokenId: fill.tokenId,
3183
+ expiration: fill.expiration,
3184
+ scriptHex: bytesToHex$1(bytes)
2980
3185
  };
2981
3186
  }
2982
3187
 
@@ -2986,13 +3191,12 @@ function parsePartialFillScript(script, network = 'xna-test') {
2986
3191
  * payment scriptPubKey bytes (which may be P2PKH or AuthScript) and the
2987
3192
  * configured TXHASH selector.
2988
3193
  *
2989
- * The full-fill and partial-fill branches share `(paymentScriptPubKey,
2990
- * unitPriceSats, tokenId)`. The parser reads both branches and verifies
2991
- * consistency; inconsistency throws.
3194
+ * The fill branches (and their input-0 binding) are read by the shared
3195
+ * `readFillBranches`; covenants built before the binding are rejected.
2992
3196
  */
2993
3197
  /** Quick discriminator without throwing — useful for indexers. */
2994
3198
  function isPartialFillScriptPQ(script) {
2995
- const bytes = typeof script === 'string' ? hexToBytes(script) : script;
3199
+ const bytes = typeof script === 'string' ? hexToBytes$1(script) : script;
2996
3200
  // PQ cancel starts with: OP_IF OP_DUP OP_SHA256
2997
3201
  return (bytes.length > 3 &&
2998
3202
  bytes[0] === OP_IF &&
@@ -3004,7 +3208,7 @@ function isPartialFillScriptPQ(script) {
3004
3208
  * exact layout produced by `buildPartialFillScriptPQ`.
3005
3209
  */
3006
3210
  function parsePartialFillScriptPQ(script, network = 'xna-test') {
3007
- const bytes = typeof script === 'string' ? hexToBytes(script) : script;
3211
+ const bytes = typeof script === 'string' ? hexToBytes$1(script) : script;
3008
3212
  const c = makeCursor(bytes);
3009
3213
  // ═════ Outer IF — Cancel branch (PQ) ═════
3010
3214
  expectByte(c, OP_IF, 'OP_IF (outer cancel)');
@@ -3027,114 +3231,851 @@ function parsePartialFillScriptPQ(script, network = 'xna-test') {
3027
3231
  expectByte(c, OP_SWAP, 'OP_SWAP');
3028
3232
  expectByte(c, OP_CHECKSIGFROMSTACK, 'OP_CHECKSIGFROMSTACK');
3029
3233
  expectByte(c, OP_ELSE, 'OP_ELSE (outer → fill)');
3030
- // ═════ Inner IF — Full-fill branch ═════
3031
- expectByte(c, OP_IF, 'OP_IF (inner full-fill)');
3032
- const expirationFull = readOptionalExpirationGate(c, OP_0, 'full');
3033
- expectByte(c, OP_0, 'OP_0 (input idx, full)');
3034
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel, full)');
3035
- expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD (full)');
3036
- expectByte(c, OP_DUP, 'OP_DUP (price, full)');
3037
- const unitPriceSatsFull = readPushPositiveInt(c, 'unitPriceSats (full)');
3038
- expectByte(c, OP_MUL, 'OP_MUL (full)');
3039
- expectByte(c, OP_0, 'OP_0 (payment idx, full)');
3040
- expectByte(c, OP_OUTPUTVALUE, 'OP_OUTPUTVALUE (full)');
3041
- expectByte(c, OP_SWAP, 'OP_SWAP (full)');
3042
- expectByte(c, OP_GREATERTHANOREQUAL, 'OP_GE (full)');
3043
- expectByte(c, OP_VERIFY, 'OP_VERIFY (full)');
3044
- expectByte(c, OP_0, 'OP_0 (payment spk idx, full)');
3045
- expectByte(c, OP_OUTPUTSCRIPT, 'OP_OUTPUTSCRIPT (payment full)');
3046
- const paymentScriptPubKeyFull = readPush(c, 'paymentScriptPubKey (full)');
3047
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (payment full)');
3048
- expectByte(c, OP_DUP, 'OP_DUP (buyer amount, full)');
3049
- expectByte(c, OP_1, 'OP_1 (buyer idx, full)');
3050
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel, full)');
3051
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer amount, full)');
3052
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer amount, full)');
3053
- expectByte(c, OP_1, 'OP_1 (buyer idx, full)');
3054
- expectByte(c, OP_1, 'OP_1 (NAME sel, full)');
3055
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer name, full)');
3056
- const tokenIdFull = readPush(c, 'tokenId (full)');
3057
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer name, full)');
3058
- expectByte(c, OP_DROP, 'OP_DROP (full)');
3059
- expectByte(c, OP_1, 'OP_1 (true, full)');
3060
- expectByte(c, OP_ELSE, 'OP_ELSE (inner → partial fill)');
3061
- // ═════ Inner ELSE — Partial-fill branch ═════
3062
- const expirationPartial = readOptionalExpirationGate(c, OP_DUP, 'partial');
3063
- expectByte(c, OP_DUP, 'OP_DUP (price, partial)');
3064
- const unitPriceSatsPartial = readPushPositiveInt(c, 'unitPriceSats (partial)');
3065
- expectByte(c, OP_MUL, 'OP_MUL (partial)');
3066
- expectByte(c, OP_0, 'OP_0 (payment idx, partial)');
3067
- expectByte(c, OP_OUTPUTVALUE, 'OP_OUTPUTVALUE (partial)');
3068
- expectByte(c, OP_SWAP, 'OP_SWAP (partial)');
3069
- expectByte(c, OP_GREATERTHANOREQUAL, 'OP_GE (partial)');
3070
- expectByte(c, OP_VERIFY, 'OP_VERIFY (partial)');
3071
- expectByte(c, OP_0, 'OP_0 (payment spk idx, partial)');
3072
- expectByte(c, OP_OUTPUTSCRIPT, 'OP_OUTPUTSCRIPT (payment partial)');
3073
- const paymentScriptPubKeyPartial = readPush(c, 'paymentScriptPubKey (partial)');
3074
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (payment partial)');
3075
- expectByte(c, OP_DUP, 'OP_DUP (buyer amount, partial)');
3076
- expectByte(c, OP_1, 'OP_1 (buyer idx, partial)');
3077
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel, partial)');
3078
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer amount, partial)');
3079
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer amount, partial)');
3080
- expectByte(c, OP_1, 'OP_1 (buyer idx, partial)');
3081
- expectByte(c, OP_1, 'OP_1 (NAME sel, partial)');
3082
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer name, partial)');
3083
- const tokenIdPartial1 = readPush(c, 'tokenId partial #1');
3084
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer name, partial)');
3085
- // Continuation commitment
3086
- expectByte(c, OP_2, 'OP_2 (remainder idx)');
3087
- expectByte(c, OP_OUTPUTAUTHCOMMITMENT, 'OP_OUTPUTAUTHCOMMITMENT (remainder)');
3088
- expectByte(c, OP_2, 'OP_2 (TXFIELD sel: AUTHSCRIPT_COMMITMENT)');
3089
- expectByte(c, OP_TXFIELD, 'OP_TXFIELD');
3090
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder auth)');
3091
- expectByte(c, OP_2, 'OP_2 (remainder idx)');
3092
- expectByte(c, OP_1, 'OP_1 (NAME sel)');
3093
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder name)');
3094
- const tokenIdPartial2 = readPush(c, 'tokenId partial #2');
3095
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder name)');
3096
- expectByte(c, OP_2, 'OP_2 (remainder idx)');
3097
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel)');
3098
- expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder amount)');
3099
- expectByte(c, OP_OVER, 'OP_OVER');
3100
- expectByte(c, OP_0, 'OP_0 (input idx)');
3101
- expectByte(c, OP_2, 'OP_2 (AMOUNT sel)');
3102
- expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD');
3103
- expectByte(c, OP_SWAP, 'OP_SWAP');
3104
- expectByte(c, OP_SUB, 'OP_SUB');
3105
- expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder amount)');
3106
- expectByte(c, OP_DROP, 'OP_DROP (partial)');
3107
- expectByte(c, OP_1, 'OP_1 (true, partial)');
3108
- expectByte(c, OP_ENDIF, 'OP_ENDIF (inner)');
3234
+ // ═════ Outer ELSE — input-0 binding + fill branches ═════
3235
+ const fill = readFillBranches(c);
3109
3236
  expectByte(c, OP_ENDIF, 'OP_ENDIF (outer)');
3110
3237
  assertTrailing(c);
3111
- // Cross-branch consistency.
3112
- if (!bytesEqual(paymentScriptPubKeyFull, paymentScriptPubKeyPartial)) {
3113
- throw new Error('parse-pq: paymentScriptPubKey differs between full-fill and partial-fill branches');
3114
- }
3115
- if (!bytesEqual(tokenIdFull, tokenIdPartial1)) {
3116
- throw new Error('parse-pq: tokenId differs between full-fill and partial-fill branches');
3117
- }
3118
- if (!bytesEqual(tokenIdPartial1, tokenIdPartial2)) {
3119
- throw new Error('parse-pq: tokenId differs between buyer and remainder partial checks');
3120
- }
3121
- if (unitPriceSatsFull !== unitPriceSatsPartial) {
3122
- throw new Error('parse-pq: unitPriceSats differs between full-fill and partial-fill branches');
3123
- }
3124
- assertSameExpiration(expirationFull, expirationPartial, 'full-fill and partial-fill branches');
3125
- const tokenId = new TextDecoder('utf-8', { fatal: true }).decode(tokenIdFull);
3126
3238
  return {
3127
3239
  network,
3128
3240
  pubKeyCommitment,
3129
- tokenId,
3130
- unitPriceSats: unitPriceSatsFull,
3241
+ tokenId: fill.tokenId,
3242
+ unitPriceSats: fill.unitPriceSats,
3131
3243
  txHashSelector,
3132
- expiration: expirationFull,
3133
- paymentScriptPubKey: paymentScriptPubKeyFull,
3134
- scriptHex: bytesToHex(bytes)
3244
+ expiration: fill.expiration,
3245
+ paymentScriptPubKey: fill.paymentScriptPubKey,
3246
+ scriptHex: bytesToHex$1(bytes)
3135
3247
  };
3136
3248
  }
3137
3249
 
3250
+ /**
3251
+ * NIP-054 P2AH custody policy (`OP_CHECKASSETAUTH`, AuthScript only).
3252
+ *
3253
+ * The policy is the witnessScript of a generic AuthScript v1 (NoAuth)
3254
+ * address. A spend of that address needs M of the N owner-token roles of the
3255
+ * list to approve it (G of them when an owner token held by the custody
3256
+ * leaves it):
3257
+ *
3258
+ * policy: <1> <M> <G> <role_1> ... <role_n> <n> OP_CHECKASSETAUTH
3259
+ * witness: [0x00, <c>, <a>, <b>, <T>, policy]
3260
+ *
3261
+ * Build the four arguments with `buildAssetAuthArgs` and wrap them with
3262
+ * `buildAuthScriptWitnessNoAuth({ args, witnessScript: policy })`. A role
3263
+ * approves either by spending its owner token from P2PKH or a strict
3264
+ * AuthScript address with a SIGHASH_ALL signature (synchronous spend, every
3265
+ * argument 0), or by a vote (see `vote.ts` and `proposal.ts`).
3266
+ */
3267
+ /** The only policy version defined by NIP-054. */
3268
+ const ASSETAUTH_POLICY_VERSION = 1;
3269
+ /** Highest number of roles in one policy. */
3270
+ const ASSETAUTH_MAX_ROLES = 16;
3271
+ /** c, a, b and T are script numbers of at most 4 bytes. */
3272
+ const MAX_ARGUMENT = 0x7fffffff;
3273
+ const encoder = new TextEncoder();
3274
+ const decoder = new TextDecoder();
3275
+ function compareBytes(x, y) {
3276
+ const n = Math.min(x.length, y.length);
3277
+ for (let i = 0; i < n; i += 1) {
3278
+ if (x[i] !== y[i])
3279
+ return x[i] - y[i];
3280
+ }
3281
+ return x.length - y.length;
3282
+ }
3283
+ /** Role names as the node checks them: sorted by bytes, no duplicates. */
3284
+ function sortedRoles(roles) {
3285
+ if (!Array.isArray(roles) || roles.length < 1 || roles.length > ASSETAUTH_MAX_ROLES) {
3286
+ throw new Error(`roles must list 1 to ${ASSETAUTH_MAX_ROLES} owner tokens`);
3287
+ }
3288
+ const names = roles.map((role) => {
3289
+ if (typeof role !== 'string' || !role.endsWith('!')) {
3290
+ throw new Error(`role ${JSON.stringify(role)} is not an owner token name (NAME!)`);
3291
+ }
3292
+ return encoder.encode(role);
3293
+ });
3294
+ names.sort(compareBytes);
3295
+ for (let i = 1; i < names.length; i += 1) {
3296
+ if (compareBytes(names[i - 1], names[i]) === 0) {
3297
+ throw new Error(`role ${decoder.decode(names[i])} is listed twice`);
3298
+ }
3299
+ }
3300
+ return names;
3301
+ }
3302
+ function assertThresholds(M, G, n) {
3303
+ if (!Number.isInteger(M) || !Number.isInteger(G) || M < 1 || M > G || G > n) {
3304
+ throw new Error(`thresholds must satisfy 1 <= M <= G <= ${n} (got M=${M}, G=${G})`);
3305
+ }
3306
+ }
3307
+ function buildAssetAuthPolicyScript(policy) {
3308
+ const roles = sortedRoles(policy.roles);
3309
+ assertThresholds(policy.M, policy.G, roles.length);
3310
+ const b = new ScriptBuilder()
3311
+ .pushInt(ASSETAUTH_POLICY_VERSION)
3312
+ .pushInt(policy.M)
3313
+ .pushInt(policy.G);
3314
+ for (const role of roles)
3315
+ b.pushBytes(role);
3316
+ return b.pushInt(roles.length).op(OP_CHECKASSETAUTH).build();
3317
+ }
3318
+ /** Inverse of `buildAssetAuthPolicyScript`; rejects any other script. */
3319
+ function parseAssetAuthPolicyScript(script) {
3320
+ const end = script.length - 2;
3321
+ const nOp = script[end];
3322
+ if (script.length < 6 || script[end + 1] !== OP_CHECKASSETAUTH || nOp < OP_1 || nOp > OP_16) {
3323
+ throw new Error('parse: not an OP_CHECKASSETAUTH policy script');
3324
+ }
3325
+ const c = makeCursor(script);
3326
+ if (readPushUint8(c, 'version') !== ASSETAUTH_POLICY_VERSION) {
3327
+ throw new Error(`parse: policy version must be ${ASSETAUTH_POLICY_VERSION}`);
3328
+ }
3329
+ const M = readPushUint8(c, 'M');
3330
+ const G = readPushUint8(c, 'G');
3331
+ const names = [];
3332
+ while (c.pos < end)
3333
+ names.push(readPush(c, `role ${names.length + 1}`));
3334
+ if (c.pos !== end || names.length !== nOp - OP_1 + 1) {
3335
+ throw new Error('parse: role count does not match n');
3336
+ }
3337
+ const roles = names.map((name) => decoder.decode(name));
3338
+ const policy = { M, G, roles };
3339
+ // Strictly increasing as written: a re-sorted list would be another script.
3340
+ const rebuilt = buildAssetAuthPolicyScript(policy);
3341
+ if (compareBytes(rebuilt, script) !== 0) {
3342
+ throw new Error('parse: roles are not owner names in strictly increasing byte order');
3343
+ }
3344
+ return policy;
3345
+ }
3346
+ /**
3347
+ * Witness `args` [<c>, <a>, <b>, <T>] for the custody input: minimal script
3348
+ * numbers, 0 as the empty element. All default to 0, the synchronous spend.
3349
+ */
3350
+ function buildAssetAuthArgs({ c = 0, a = 0, b = 0, T = 0 } = {}) {
3351
+ for (const [name, value] of Object.entries({ c, a, b, T })) {
3352
+ if (!Number.isInteger(value) || value < 0 || value > MAX_ARGUMENT) {
3353
+ throw new Error(`${name} must be an integer from 0 to ${MAX_ARGUMENT}`);
3354
+ }
3355
+ }
3356
+ return [c, a, b, T].map((value) => encodeScriptNum(value));
3357
+ }
3358
+
3359
+ // Split a JS number into u32 halves without a BigInt allocation. Exact only for integers
3360
+ // `0 <= n < 2**53`; callers use it on byte / bit counters, which JS length math caps far below
3361
+ // that (an ArrayBuffer cannot exceed 2**53 - 1 bytes).
3362
+ const fromNumH = (n) => (n / 2 ** 32) | 0;
3363
+ const fromNumL = (n) => n >>> 0;
3364
+ // Drop-in replacement for `view.setBigUint64(byteOffset, BigInt(n), isLE)` without the per-call
3365
+ // BigInt allocation. Same `n < 2**53` precondition as `fromNumH`/`fromNumL`.
3366
+ function setU64FromNum(view, byteOffset, n, isLE) {
3367
+ const h = fromNumH(n);
3368
+ const l = fromNumL(n);
3369
+ view.setUint32(byteOffset, isLE ? l : h, isLE);
3370
+ view.setUint32(byteOffset + 4, isLE ? h : l, isLE);
3371
+ }
3372
+
3373
+ /**
3374
+ * Checks if something is Uint8Array. Be careful: nodejs Buffer will return true.
3375
+ * @param a - value to test
3376
+ * @returns `true` when the value is a Uint8Array-compatible view.
3377
+ * @example
3378
+ * Check whether a value is a Uint8Array-compatible view.
3379
+ * ```ts
3380
+ * isBytes(new Uint8Array([1, 2, 3]));
3381
+ * ```
3382
+ */
3383
+ function isBytes(a) {
3384
+ // Plain `instanceof Uint8Array` is too strict for some Buffer / proxy / cross-realm cases.
3385
+ // The fallback still requires a real ArrayBuffer view, so plain
3386
+ // JSON-deserialized `{ constructor: ... }` spoofing is rejected, and
3387
+ // `BYTES_PER_ELEMENT === 1` keeps the fallback on byte-oriented views.
3388
+ return (a instanceof Uint8Array ||
3389
+ (ArrayBuffer.isView(a) &&
3390
+ a.constructor.name === 'Uint8Array' &&
3391
+ 'BYTES_PER_ELEMENT' in a &&
3392
+ a.BYTES_PER_ELEMENT === 1));
3393
+ }
3394
+ // Shared error-message prefix builder. Only called on throw paths, so assert
3395
+ // success paths never pay for the string concatenation.
3396
+ const atitle = (title) => (title ? `"${title}" ` : '');
3397
+ /**
3398
+ * Asserts something is Uint8Array.
3399
+ * @param value - value to validate
3400
+ * @param length - optional exact length constraint
3401
+ * @param title - label included in thrown errors
3402
+ * @returns The validated byte array.
3403
+ * @throws On wrong argument types. {@link TypeError}
3404
+ * @throws On wrong argument ranges or values. {@link RangeError}
3405
+ * @example
3406
+ * Validate that a value is a byte array.
3407
+ * ```ts
3408
+ * abytes(new Uint8Array([1, 2, 3]));
3409
+ * ```
3410
+ */
3411
+ function abytes(value, length, title = '') {
3412
+ // Success path first: this runs at the start of every update() / digestInto(), and the
3413
+ // common `abytes(data)` form must not pay for length handling it does not use.
3414
+ if (isBytes(value) && (length === undefined))
3415
+ return value;
3416
+ const bytes = isBytes(value);
3417
+ const ofLen = '';
3418
+ const got = bytes ? `length=${value.length}` : `type=${typeof value}`;
3419
+ const message = atitle(title) + 'expected Uint8Array' + ofLen + ', got ' + got;
3420
+ if (!bytes)
3421
+ throw new TypeError(message);
3422
+ throw new RangeError(message);
3423
+ }
3424
+ const aobject = (value, label) => {
3425
+ if (value === null || typeof value !== 'object' || Array.isArray(value))
3426
+ throw new TypeError((label === 'object' ? '' : `"${label}" `) + 'expected object, got type=' + typeof value);
3427
+ };
3428
+ const aopts = (value, label) => {
3429
+ aobject(value, label);
3430
+ const proto = Object.getPrototypeOf(value);
3431
+ if (proto !== Object.prototype && proto !== null)
3432
+ throw new TypeError(`"${label}" expected plain object`);
3433
+ // Object.assign() treats an own "__proto__" source key as a write to the target's legacy
3434
+ // prototype setter. Reject it before merging so inherited option values cannot be injected.
3435
+ if (Object.hasOwn(value, '__proto__'))
3436
+ throw new TypeError(`"${label}.__proto__" is not allowed`);
3437
+ };
3438
+ /**
3439
+ * Asserts a hash instance has not been destroyed or finished.
3440
+ * @param instance - hash instance to validate
3441
+ * @param checkFinished - whether to reject finalized instances
3442
+ * @throws If the hash instance has already been destroyed or finalized. {@link Error}
3443
+ * @example
3444
+ * Validate that a hash instance is still usable.
3445
+ * ```ts
3446
+ * import { aexists } from '@noble/hashes/utils.js';
3447
+ * import { sha256 } from '@noble/hashes/sha2.js';
3448
+ * const hash = sha256.create();
3449
+ * aexists(hash);
3450
+ * ```
3451
+ */
3452
+ function aexists(instance, checkFinished = true) {
3453
+ // Runs on every update()/digestInto(); the flags are library-owned booleans, so only their
3454
+ // truthiness is checked - re-validating their type per call was pure hot-path overhead.
3455
+ if (instance.destroyed)
3456
+ throw new Error('hash was destroyed');
3457
+ if (checkFinished && instance.finished)
3458
+ throw new Error('digest() was already called');
3459
+ }
3460
+ /**
3461
+ * Asserts output is a sufficiently-sized byte array.
3462
+ * @param out - destination buffer
3463
+ * @param instance - hash instance providing output length
3464
+ * Oversized buffers are allowed; downstream code only promises to fill the first `outputLen` bytes.
3465
+ * @throws On wrong argument types. {@link TypeError}
3466
+ * @throws On wrong argument ranges or values. {@link RangeError}
3467
+ * @example
3468
+ * Validate a caller-provided digest buffer.
3469
+ * ```ts
3470
+ * import { aoutput } from '@noble/hashes/utils.js';
3471
+ * import { sha256 } from '@noble/hashes/sha2.js';
3472
+ * const hash = sha256.create();
3473
+ * aoutput(new Uint8Array(hash.outputLen), hash);
3474
+ * ```
3475
+ */
3476
+ function aoutput(out, instance) {
3477
+ abytes(out, undefined, 'output');
3478
+ // `outputLen` is a library-owned readonly number; the negated comparison keeps failing fast
3479
+ // when it is missing/NaN (comparisons with undefined/NaN are false) without an anumber() call.
3480
+ const min = instance.outputLen;
3481
+ if (!(out.length >= min)) {
3482
+ throw new RangeError('"output" expected length >= ' + min);
3483
+ }
3484
+ }
3485
+ /**
3486
+ * Zeroizes typed arrays in place. Warning: JS provides no guarantees.
3487
+ * @param arrays - arrays to overwrite with zeros
3488
+ * @example
3489
+ * Zeroize sensitive buffers in place.
3490
+ * ```ts
3491
+ * clean(new Uint8Array([1, 2, 3]));
3492
+ * ```
3493
+ */
3494
+ function clean(...arrays) {
3495
+ for (let i = 0; i < arrays.length; i++) {
3496
+ arrays[i].fill(0);
3497
+ }
3498
+ }
3499
+ /**
3500
+ * Creates a DataView for byte-level manipulation.
3501
+ * @param arr - source typed array
3502
+ * @returns DataView over the same buffer region.
3503
+ * @example
3504
+ * Create a DataView over an existing buffer.
3505
+ * ```ts
3506
+ * createView(new Uint8Array(4));
3507
+ * ```
3508
+ */
3509
+ function createView(arr) {
3510
+ return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
3511
+ }
3512
+ /**
3513
+ * Rotate-right operation for uint32 values.
3514
+ * @param word - source word
3515
+ * @param shift - shift amount in bits
3516
+ * @returns Rotated word.
3517
+ * @example
3518
+ * Rotate a 32-bit word to the right.
3519
+ * ```ts
3520
+ * rotr(0x12345678, 8);
3521
+ * ```
3522
+ */
3523
+ function rotr(word, shift) {
3524
+ return (word << (32 - shift)) | (word >>> shift);
3525
+ }
3526
+ /**
3527
+ * Merges default options and passed options.
3528
+ * @param defaults - base option object
3529
+ * @param opts - user overrides
3530
+ * @param title - label included in thrown override errors
3531
+ * @returns Fresh merged option object with a null prototype.
3532
+ * @throws On wrong argument types. {@link TypeError}
3533
+ * @example
3534
+ * Merge user overrides onto default options.
3535
+ * ```ts
3536
+ * checkOpts({ dkLen: 32 }, { asyncTick: 10 });
3537
+ * ```
3538
+ */
3539
+ function checkOpts(defaults, opts, title = 'opts') {
3540
+ aopts(defaults, 'defaults');
3541
+ if (opts !== undefined)
3542
+ aopts(opts, title);
3543
+ // Callers read optional fields directly, so omitted values must not fall through to ambient
3544
+ // Object.prototype pollution (for example a forged `dkLen` changing SHAKE's default output).
3545
+ const merged = Object.assign(Object.create(null), defaults, opts);
3546
+ return merged;
3547
+ }
3548
+ /**
3549
+ * Creates a callable hash function from a stateful class constructor.
3550
+ * @param hashCons - hash constructor or factory
3551
+ * @param info - optional metadata such as DER OID
3552
+ * @returns Frozen callable hash wrapper with `.create()`.
3553
+ * Wrapper construction eagerly calls `hashCons(undefined)` once to read
3554
+ * `outputLen` / `blockLen`, so constructor side effects happen at module
3555
+ * init time.
3556
+ * @throws On wrong argument types. {@link TypeError}
3557
+ * @example
3558
+ * Wrap a stateful hash constructor into a callable helper.
3559
+ * ```ts
3560
+ * import { createHasher } from '@noble/hashes/utils.js';
3561
+ * import { sha256 } from '@noble/hashes/sha2.js';
3562
+ * const wrapped = createHasher(sha256.create, { oid: sha256.oid });
3563
+ * wrapped(new Uint8Array([1]));
3564
+ * ```
3565
+ */
3566
+ function createHasher(hashCons, info = {}) {
3567
+ if (typeof hashCons !== 'function')
3568
+ throw new TypeError('"hashCons" expected function, got type=' + typeof hashCons);
3569
+ info = checkOpts({}, info, 'info');
3570
+ const hashC = (msg, opts) => hashCons(opts)
3571
+ .update(msg)
3572
+ .digest();
3573
+ const tmp = hashCons(undefined);
3574
+ hashC.outputLen = tmp.outputLen;
3575
+ hashC.blockLen = tmp.blockLen;
3576
+ hashC.canXOF = tmp.canXOF;
3577
+ hashC.create = (opts) => hashCons(opts);
3578
+ Object.assign(hashC, info);
3579
+ return Object.freeze(hashC);
3580
+ }
3581
+ /**
3582
+ * Creates OID metadata for NIST hashes with prefix `06 09 60 86 48 01 65 03 04 02`.
3583
+ * @param suffix - final OID byte for the selected hash.
3584
+ * The helper accepts any byte even though only the documented NIST hash
3585
+ * suffixes are meaningful downstream.
3586
+ * @returns Object containing the DER-encoded OID.
3587
+ * @example
3588
+ * Build OID metadata for a NIST hash.
3589
+ * ```ts
3590
+ * oidNist(0x01);
3591
+ * ```
3592
+ */
3593
+ const oidNist = (suffix) => ({
3594
+ // Current NIST hashAlgs suffixes used here fit in one DER subidentifier octet.
3595
+ // Larger suffix values would need base-128 OID encoding and a different length byte.
3596
+ oid: Uint8Array.from([0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, suffix]),
3597
+ });
3598
+
3599
+ /**
3600
+ * Internal Merkle-Damgard hash utils.
3601
+ * @module
3602
+ */
3603
+ /**
3604
+ * Shared 32-bit conditional boolean primitive reused by SHA-256, SHA-1, and MD5 `F`.
3605
+ * Returns bits from `b` when `a` is set, otherwise from `c`.
3606
+ * The XOR form is equivalent to MD5's `F(X,Y,Z) = XY v not(X)Z` because the masked terms never
3607
+ * set the same bit.
3608
+ * @param a - selector word
3609
+ * @param b - word chosen when selector bit is set
3610
+ * @param c - word chosen when selector bit is clear
3611
+ * @returns Mixed 32-bit word.
3612
+ * @example
3613
+ * Combine three words with the shared 32-bit choice primitive.
3614
+ * ```ts
3615
+ * Chi(0xffffffff, 0x12345678, 0x87654321);
3616
+ * ```
3617
+ */
3618
+ function Chi(a, b, c) {
3619
+ return (a & b) ^ (~a & c);
3620
+ }
3621
+ /**
3622
+ * Shared 32-bit majority primitive reused by SHA-256 and SHA-1.
3623
+ * Returns bits shared by at least two inputs.
3624
+ * @param a - first input word
3625
+ * @param b - second input word
3626
+ * @param c - third input word
3627
+ * @returns Mixed 32-bit word.
3628
+ * @example
3629
+ * Combine three words with the shared 32-bit majority primitive.
3630
+ * ```ts
3631
+ * Maj(0xffffffff, 0x12345678, 0x87654321);
3632
+ * ```
3633
+ */
3634
+ function Maj(a, b, c) {
3635
+ return (a & b) ^ (a & c) ^ (b & c);
3636
+ }
3637
+ /**
3638
+ * Merkle-Damgard hash construction base class.
3639
+ * Could be used to create MD5, RIPEMD, SHA1, SHA2.
3640
+ * Accepts only byte-aligned `Uint8Array` input, even when the underlying spec describes bit
3641
+ * strings with partial-byte tails.
3642
+ * @param blockLen - internal block size in bytes
3643
+ * @param outputLen - digest size in bytes
3644
+ * @param padOffset - trailing length field size in bytes
3645
+ * @param isLE - whether length and state words are encoded in little-endian
3646
+ * @example
3647
+ * Use a concrete subclass to get the shared Merkle-Damgard update/digest flow.
3648
+ * ```ts
3649
+ * import { _SHA1 } from '@noble/hashes/legacy.js';
3650
+ * const hash = new _SHA1();
3651
+ * hash.update(new Uint8Array([97, 98, 99]));
3652
+ * hash.digest();
3653
+ * ```
3654
+ */
3655
+ class HashMD {
3656
+ blockLen;
3657
+ outputLen;
3658
+ canXOF = false;
3659
+ padOffset;
3660
+ isLE;
3661
+ // For partial updates less than block size
3662
+ buffer;
3663
+ view;
3664
+ finished = false;
3665
+ length = 0;
3666
+ pos = 0;
3667
+ destroyed = false;
3668
+ constructor(blockLen, outputLen, padOffset, isLE) {
3669
+ this.blockLen = blockLen;
3670
+ this.outputLen = outputLen;
3671
+ this.padOffset = padOffset;
3672
+ this.isLE = isLE;
3673
+ this.buffer = new Uint8Array(blockLen);
3674
+ this.view = createView(this.buffer);
3675
+ }
3676
+ update(data) {
3677
+ aexists(this);
3678
+ abytes(data);
3679
+ const { view, buffer, blockLen } = this;
3680
+ const len = data.length;
3681
+ let processed = false;
3682
+ for (let pos = 0; pos < len;) {
3683
+ const take = Math.min(blockLen - this.pos, len - pos);
3684
+ // Fast path only when there is no buffered partial block: `take === blockLen` implies
3685
+ // `this.pos === 0`, so we can process full blocks directly from the input view.
3686
+ if (take === blockLen) {
3687
+ const dataView = createView(data);
3688
+ for (; blockLen <= len - pos; pos += blockLen)
3689
+ this.process(dataView, pos);
3690
+ processed = true;
3691
+ continue;
3692
+ }
3693
+ // When the whole input is buffered in one go (common for short messages), passing `data`
3694
+ // directly avoids allocating a subarray view.
3695
+ buffer.set(pos === 0 && take === len ? data : data.subarray(pos, pos + take), this.pos);
3696
+ this.pos += take;
3697
+ pos += take;
3698
+ if (this.pos === blockLen) {
3699
+ this.process(view, 0);
3700
+ this.pos = 0;
3701
+ processed = true;
3702
+ }
3703
+ }
3704
+ this.length += data.length;
3705
+ // Shared schedule buffers only pick up input-derived words inside process(); if everything
3706
+ // was buffered without processing, there is nothing to zero.
3707
+ if (processed)
3708
+ this.roundClean();
3709
+ return this;
3710
+ }
3711
+ digestInto(out) {
3712
+ aexists(this);
3713
+ aoutput(out, this);
3714
+ this.finished = true;
3715
+ // Padding
3716
+ // We can avoid allocation of buffer for padding completely if it
3717
+ // was previously not allocated here. But it won't change performance.
3718
+ const { buffer, view, blockLen, isLE } = this;
3719
+ let { pos } = this;
3720
+ // append the bit '1' to the message, then zero-pad the rest of the block
3721
+ buffer[pos++] = 0b10000000;
3722
+ buffer.fill(0, pos);
3723
+ // we have less than padOffset left in buffer, so we cannot put length in
3724
+ // current block, need process it and pad again
3725
+ if (this.padOffset > blockLen - pos) {
3726
+ this.process(view, 0);
3727
+ buffer.fill(0);
3728
+ }
3729
+ // `padOffset` reserves the whole length field. For SHA-384/512 the high 64 bits stay zero from
3730
+ // the padding fill above, and JS will overflow before user input can make that half non-zero.
3731
+ // So we only need to write the low 64 bits here (`length * 8` only scales the exponent of an
3732
+ // integer below 2**53, so the split inside the helper stays exact).
3733
+ setU64FromNum(view, blockLen - 8, this.length * 8, isLE);
3734
+ this.process(view, 0);
3735
+ // The final block above is processed outside update(), so the shared message-schedule
3736
+ // buffers (e.g. SHA256_W) would otherwise retain input-derived words after digest().
3737
+ this.roundClean();
3738
+ // digest() passes our own `buffer` as `out`; reuse its cached view instead of allocating one.
3739
+ const oview = out === buffer ? view : createView(out);
3740
+ const len = this.outputLen;
3741
+ // NOTE: we do division by 4 later, which must be fused in single op with modulo by JIT
3742
+ const outLen = len / 4;
3743
+ const state = this.get();
3744
+ // Subclass-misconfiguration invariant: outputLen must be 32-bit aligned and fit the state.
3745
+ if (len % 4 || outLen > state.length)
3746
+ throw new Error('invalid outputLen');
3747
+ for (let i = 0; i < outLen; i++)
3748
+ oview.setUint32(4 * i, state[i], isLE);
3749
+ }
3750
+ digest() {
3751
+ const { buffer, outputLen } = this;
3752
+ this.digestInto(buffer);
3753
+ // Copy before destroy(): subclasses wipe `buffer` during cleanup, but `digest()` must return
3754
+ // fresh bytes to the caller.
3755
+ const res = buffer.slice(0, outputLen);
3756
+ this.destroy();
3757
+ return res;
3758
+ }
3759
+ _cloneIntoMeta(to) {
3760
+ const { buffer, length, finished, destroyed, pos } = this;
3761
+ to.destroyed = destroyed;
3762
+ to.finished = finished;
3763
+ to.length = length;
3764
+ to.pos = pos;
3765
+ // Only partial-block bytes need copying: when `length % blockLen === 0`, `pos === 0` and
3766
+ // later `update()` / `digestInto()` overwrite `to.buffer` from the start before reading it.
3767
+ if (pos)
3768
+ to.buffer.set(buffer); // Avoid a hot modulo guard.
3769
+ return to;
3770
+ }
3771
+ clone() {
3772
+ return this._cloneInto();
3773
+ }
3774
+ }
3775
+ /**
3776
+ * Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
3777
+ * Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
3778
+ */
3779
+ /** Initial SHA256 state from RFC 6234 §6.1: the first 32 bits of the fractional parts of the
3780
+ * square roots of the first eight prime numbers. Exported as a shared table; callers must treat
3781
+ * it as read-only because constructors copy words from it by index. */
3782
+ const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
3783
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
3784
+ ]);
3785
+
3786
+ /**
3787
+ * SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
3788
+ * SHA256 is the fastest hash implementable in JS, even faster than Blake3.
3789
+ * Check out {@link https://www.rfc-editor.org/rfc/rfc4634 | RFC 4634} and
3790
+ * {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf | FIPS 180-4}.
3791
+ * @module
3792
+ */
3793
+ /**
3794
+ * SHA-224 / SHA-256 round constants from RFC 6234 §5.1: the first 32 bits
3795
+ * of the cube roots of the first 64 primes (2..311).
3796
+ */
3797
+ // prettier-ignore
3798
+ const SHA256_K = /* @__PURE__ */ Uint32Array.from([
3799
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
3800
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
3801
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
3802
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
3803
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
3804
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
3805
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
3806
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
3807
+ ]);
3808
+ /** Reusable SHA-224 / SHA-256 message schedule buffer `W_t` from RFC 6234 §6.2 step 1. */
3809
+ const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
3810
+ /** Internal SHA-224 / SHA-256 compression engine from RFC 6234 §6.2. */
3811
+ class SHA2_32B extends HashMD {
3812
+ // We cannot use array here since array allows indexing by variable
3813
+ // which means optimizer/compiler cannot use registers.
3814
+ // Numeric initializers matter: starting the fields as `undefined` changes
3815
+ // V8's field representation and makes sha256 3x slower (measured).
3816
+ A = 0;
3817
+ B = 0;
3818
+ C = 0;
3819
+ D = 0;
3820
+ E = 0;
3821
+ F = 0;
3822
+ G = 0;
3823
+ H = 0;
3824
+ constructor(outputLen, IV) {
3825
+ super(64, outputLen, 8, false);
3826
+ this.A = IV[0] | 0;
3827
+ this.B = IV[1] | 0;
3828
+ this.C = IV[2] | 0;
3829
+ this.D = IV[3] | 0;
3830
+ this.E = IV[4] | 0;
3831
+ this.F = IV[5] | 0;
3832
+ this.G = IV[6] | 0;
3833
+ this.H = IV[7] | 0;
3834
+ }
3835
+ get() {
3836
+ const { A, B, C, D, E, F, G, H } = this;
3837
+ return [A, B, C, D, E, F, G, H];
3838
+ }
3839
+ // prettier-ignore
3840
+ set(A, B, C, D, E, F, G, H) {
3841
+ this.A = A | 0;
3842
+ this.B = B | 0;
3843
+ this.C = C | 0;
3844
+ this.D = D | 0;
3845
+ this.E = E | 0;
3846
+ this.F = F | 0;
3847
+ this.G = G | 0;
3848
+ this.H = H | 0;
3849
+ }
3850
+ _cloneInto(to) {
3851
+ (to ||= new this.constructor()).set(...this.get());
3852
+ return this._cloneIntoMeta(to);
3853
+ }
3854
+ process(view, offset) {
3855
+ // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
3856
+ for (let i = 0; i < 16; i++, offset += 4)
3857
+ SHA256_W[i] = view.getUint32(offset, false);
3858
+ for (let i = 16; i < 64; i++) {
3859
+ const W15 = SHA256_W[i - 15];
3860
+ const W2 = SHA256_W[i - 2];
3861
+ const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
3862
+ const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
3863
+ SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
3864
+ }
3865
+ // Compression function main loop, 64 rounds
3866
+ let { A, B, C, D, E, F, G, H } = this;
3867
+ for (let i = 0; i < 64; i++) {
3868
+ const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
3869
+ const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
3870
+ const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
3871
+ const T2 = (sigma0 + Maj(A, B, C)) | 0;
3872
+ H = G;
3873
+ G = F;
3874
+ F = E;
3875
+ E = (D + T1) | 0;
3876
+ D = C;
3877
+ C = B;
3878
+ B = A;
3879
+ A = (T1 + T2) | 0;
3880
+ }
3881
+ // Add the compressed chunk to the current hash value
3882
+ A = (A + this.A) | 0;
3883
+ B = (B + this.B) | 0;
3884
+ C = (C + this.C) | 0;
3885
+ D = (D + this.D) | 0;
3886
+ E = (E + this.E) | 0;
3887
+ F = (F + this.F) | 0;
3888
+ G = (G + this.G) | 0;
3889
+ H = (H + this.H) | 0;
3890
+ this.set(A, B, C, D, E, F, G, H);
3891
+ }
3892
+ roundClean() {
3893
+ clean(SHA256_W);
3894
+ }
3895
+ destroy() {
3896
+ // HashMD callers route post-destroy usability through `destroyed`; zeroizing alone still leaves
3897
+ // update()/digest() callable on reused instances.
3898
+ this.destroyed = true;
3899
+ this.set(0, 0, 0, 0, 0, 0, 0, 0);
3900
+ clean(this.buffer);
3901
+ }
3902
+ }
3903
+ /** Internal SHA-256 hash class grounded in RFC 6234 §6.2. */
3904
+ class _SHA256 extends SHA2_32B {
3905
+ constructor() {
3906
+ super(32, SHA256_IV);
3907
+ }
3908
+ }
3909
+ /**
3910
+ * SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
3911
+ *
3912
+ * - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
3913
+ * - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
3914
+ * - Each sha256 hash is executing 2^18 bit operations.
3915
+ * - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
3916
+ * @param msg - message bytes to hash
3917
+ * @param opts - Reserved hash options.
3918
+ * @returns Digest bytes.
3919
+ * @example
3920
+ * Hash a message with SHA2-256.
3921
+ * ```ts
3922
+ * sha256(new Uint8Array([97, 98, 99]));
3923
+ * ```
3924
+ */
3925
+ const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(),
3926
+ /* @__PURE__ */ oidNist(0x01));
3927
+
3928
+ /**
3929
+ * NIP-054 proposal hash H, the message a vote carries.
3930
+ *
3931
+ * H = TaggedHash("NeuraiAssetAuthProposal", m)
3932
+ * m = chainId (u8) || nVersion (i32) || nLockTime (u32) || T (u32)
3933
+ * || compact(c) || compact(a) || compact(b)
3934
+ * || (outpoint, nSequence) of inputs 0..c-1
3935
+ * || outputs 0..a-1 || the last b outputs
3936
+ * || compact(#refs) || reference inputs (version 3 only)
3937
+ *
3938
+ * Inputs from index c on and the outputs between the prefix and the suffix
3939
+ * (approvals, returns, fees, change) are left to the executor, so a skeleton
3940
+ * transaction with only the proposal inputs and outputs gives the same H as
3941
+ * the execution. Votes carry H as is, as the 32-byte (64-hex) message of
3942
+ * their owner-token transfer: `bytesToHex(hash)`.
3943
+ */
3944
+ /** The chain identifier the node commits to (OP_CHAINCONTEXT selector 0x03). */
3945
+ const ASSETAUTH_CHAIN_IDS = Object.freeze({
3946
+ mainnet: 0,
3947
+ testnet: 1,
3948
+ regtest: 2
3949
+ });
3950
+ const PROPOSAL_TAG = new TextEncoder().encode('NeuraiAssetAuthProposal');
3951
+ function u32(value) {
3952
+ const out = new Uint8Array(4);
3953
+ new DataView(out.buffer).setUint32(0, value >>> 0, true);
3954
+ return out;
3955
+ }
3956
+ function compactSize(value) {
3957
+ if (value < 0xfd)
3958
+ return Uint8Array.of(value);
3959
+ if (value <= 0xffff)
3960
+ return Uint8Array.of(0xfd, value & 0xff, value >> 8);
3961
+ return concatBytes$1(Uint8Array.of(0xfe), u32(value));
3962
+ }
3963
+ /** A display-order txid and vout as the node serializes a COutPoint. */
3964
+ function outpoint(txid, vout) {
3965
+ return concatBytes$1(hexToBytes$1(txid).reverse(), u32(vout));
3966
+ }
3967
+ function buildAssetAuthProposalMessage(proposal) {
3968
+ const { c, a, b, T } = proposal;
3969
+ const chainId = ASSETAUTH_CHAIN_IDS[proposal.chain];
3970
+ if (chainId === undefined) {
3971
+ throw new Error(`unknown chain ${JSON.stringify(proposal.chain)}`);
3972
+ }
3973
+ for (const [name, value] of Object.entries({ c, a, b, T })) {
3974
+ if (!Number.isInteger(value) || value < 0 || value > 0x7fffffff) {
3975
+ throw new Error(`${name} must be an integer from 0 to ${0x7fffffff}`);
3976
+ }
3977
+ }
3978
+ const tx = parseTransaction(proposal.rawTx);
3979
+ if (c > tx.inputs.length) {
3980
+ throw new Error(`c (${c}) exceeds the ${tx.inputs.length} inputs of the transaction`);
3981
+ }
3982
+ if (a + b > tx.outputs.length) {
3983
+ throw new Error(`a + b (${a + b}) exceeds the ${tx.outputs.length} outputs of the transaction`);
3984
+ }
3985
+ const version = new Uint8Array(4);
3986
+ new DataView(version.buffer).setInt32(0, tx.version, true);
3987
+ const parts = [Uint8Array.of(chainId), version, u32(tx.locktime), u32(T), compactSize(c), compactSize(a), compactSize(b)];
3988
+ for (const input of tx.inputs.slice(0, c)) {
3989
+ parts.push(outpoint(input.txid, input.vout), u32(input.sequence));
3990
+ }
3991
+ for (const output of [...tx.outputs.slice(0, a), ...tx.outputs.slice(tx.outputs.length - b)]) {
3992
+ parts.push(serializeOutput(output));
3993
+ }
3994
+ const refs = tx.version === 3 ? tx.vrefin : [];
3995
+ parts.push(compactSize(refs.length));
3996
+ for (const ref of refs)
3997
+ parts.push(outpoint(ref.txid, ref.vout));
3998
+ return concatBytes$1(...parts);
3999
+ }
4000
+ /** H: 32 bytes, in the order a vote carries it. */
4001
+ function assetAuthProposalHash(proposal) {
4002
+ const tag = sha256(PROPOSAL_TAG);
4003
+ return sha256(concatBytes$1(tag, tag, buildAssetAuthProposalMessage(proposal)));
4004
+ }
4005
+
4006
+ /**
4007
+ * NIP-054 vote lock: a wallet template (not part of the opcode) that holds a
4008
+ * role's owner token while it votes for a proposal.
4009
+ *
4010
+ * The holder sends the owner token, with the proposal hash H as its transfer
4011
+ * message, to the generic AuthScript v1 (NoAuth) address of this script:
4012
+ *
4013
+ * OP_IF execute, up to height T
4014
+ * OP_1 OP_CHAINCONTEXT <T> OP_LESSTHANOREQUAL OP_VERIFY
4015
+ * OP_SWAP OP_4 OP_INPUTFIELD <0x01 || C> OP_EQUALVERIFY
4016
+ * OP_OUTPUTSCRIPT <return> OP_EQUAL
4017
+ * OP_ELSE give it back, after T
4018
+ * OP_1 OP_CHAINCONTEXT <T> OP_GREATERTHAN OP_VERIFY
4019
+ * OP_NIP OP_OUTPUTSCRIPT <return> OP_EQUAL
4020
+ * OP_ENDIF
4021
+ *
4022
+ * Both branches send the token back to its owner (`return`, the full output
4023
+ * script). The execute branch also needs the custody, commitment C, at the
4024
+ * input it names. It must use OP_INPUTFIELD selector 04, the full
4025
+ * version-plus-commitment: selector 02 only reads the first 34 bytes of the
4026
+ * spent script, which a forged anyone-can-spend custody can match.
4027
+ */
4028
+ /** OP_INPUTFIELD selector: the full version-plus-commitment of the spent script. */
4029
+ const INPUTFIELD_AUTHSCRIPT_DESTINATION = 0x04;
4030
+ const AUTHSCRIPT_V1 = 0x01;
4031
+ function asBytes(value) {
4032
+ return typeof value === 'string' ? hexToBytes$1(value) : value;
4033
+ }
4034
+ function assertIndex(name, value) {
4035
+ if (!Number.isInteger(value) || value < 0 || value > 0x7fffffff) {
4036
+ throw new Error(`${name} must be an integer from 0 to ${0x7fffffff}`);
4037
+ }
4038
+ }
4039
+ function buildAssetAuthVoteLockScript(params) {
4040
+ assertIndex('T', params.T);
4041
+ const commitment = asBytes(params.custodyCommitment);
4042
+ if (commitment.length !== 32) {
4043
+ throw new Error(`custodyCommitment must be 32 bytes (got ${commitment.length})`);
4044
+ }
4045
+ const returnScript = asBytes(params.returnScriptPubKey);
4046
+ if (returnScript.length === 0) {
4047
+ throw new Error('returnScriptPubKey must not be empty');
4048
+ }
4049
+ return new ScriptBuilder()
4050
+ .op(OP_IF)
4051
+ .pushInt(CHAINCONTEXT_HEIGHT).op(OP_CHAINCONTEXT).pushInt(params.T).op(OP_LESSTHANOREQUAL, OP_VERIFY)
4052
+ .op(OP_SWAP).pushInt(INPUTFIELD_AUTHSCRIPT_DESTINATION).op(OP_INPUTFIELD)
4053
+ .pushBytes(concatBytes$1(Uint8Array.of(AUTHSCRIPT_V1), commitment)).op(OP_EQUALVERIFY)
4054
+ .op(OP_OUTPUTSCRIPT).pushBytes(returnScript).op(OP_EQUAL)
4055
+ .op(OP_ELSE)
4056
+ .pushInt(CHAINCONTEXT_HEIGHT).op(OP_CHAINCONTEXT).pushInt(params.T).op(OP_GREATERTHAN, OP_VERIFY)
4057
+ .op(OP_NIP, OP_OUTPUTSCRIPT).pushBytes(returnScript).op(OP_EQUAL)
4058
+ .op(OP_ENDIF)
4059
+ .build();
4060
+ }
4061
+ /**
4062
+ * Witness `args` of the execute branch: the index of the custody input and
4063
+ * the index of the output that returns the token.
4064
+ */
4065
+ function buildAssetAuthVoteExecuteArgs(params) {
4066
+ assertIndex('custodyInput', params.custodyInput);
4067
+ assertIndex('returnOutput', params.returnOutput);
4068
+ return [encodeScriptNum(params.custodyInput), encodeScriptNum(params.returnOutput), encodeScriptNum(1)];
4069
+ }
4070
+ /** Witness `args` of the return branch, after T. */
4071
+ function buildAssetAuthVoteReturnArgs(params) {
4072
+ assertIndex('returnOutput', params.returnOutput);
4073
+ return [encodeScriptNum(0), encodeScriptNum(params.returnOutput), encodeScriptNum(0)];
4074
+ }
4075
+
4076
+ exports.ASSETAUTH_CHAIN_IDS = ASSETAUTH_CHAIN_IDS;
4077
+ exports.ASSETAUTH_MAX_ROLES = ASSETAUTH_MAX_ROLES;
4078
+ exports.ASSETAUTH_POLICY_VERSION = ASSETAUTH_POLICY_VERSION;
3138
4079
  exports.AUTHSCRIPT_LEGACY = AUTHSCRIPT_LEGACY;
3139
4080
  exports.AUTHSCRIPT_NOAUTH = AUTHSCRIPT_NOAUTH;
3140
4081
  exports.AUTHSCRIPT_PQ = AUTHSCRIPT_PQ;
@@ -3145,6 +4086,13 @@ exports.NULLDATA_STANDARD_MAX_SIZE = NULLDATA_STANDARD_MAX_SIZE;
3145
4086
  exports.PQ_PUBKEY_PREFIX = PQ_PUBKEY_PREFIX;
3146
4087
  exports.STRICT_PQ_PUBKEY_LENGTH = STRICT_PQ_PUBKEY_LENGTH;
3147
4088
  exports.ScriptBuilder = ScriptBuilder;
4089
+ exports.assetAuthProposalHash = assetAuthProposalHash;
4090
+ exports.buildAssetAuthArgs = buildAssetAuthArgs;
4091
+ exports.buildAssetAuthPolicyScript = buildAssetAuthPolicyScript;
4092
+ exports.buildAssetAuthProposalMessage = buildAssetAuthProposalMessage;
4093
+ exports.buildAssetAuthVoteExecuteArgs = buildAssetAuthVoteExecuteArgs;
4094
+ exports.buildAssetAuthVoteLockScript = buildAssetAuthVoteLockScript;
4095
+ exports.buildAssetAuthVoteReturnArgs = buildAssetAuthVoteReturnArgs;
3148
4096
  exports.buildAuthScriptWitnessLegacy = buildAuthScriptWitnessLegacy;
3149
4097
  exports.buildAuthScriptWitnessNoAuth = buildAuthScriptWitnessNoAuth;
3150
4098
  exports.buildAuthScriptWitnessPQ = buildAuthScriptWitnessPQ;
@@ -3165,8 +4113,8 @@ exports.buildPartialFillScriptPQHex = buildPartialFillScriptPQHex;
3165
4113
  exports.buildStrictWitnessECDSA = buildStrictWitnessECDSA;
3166
4114
  exports.buildStrictWitnessPQ = buildStrictWitnessPQ;
3167
4115
  exports.bytesEqual = bytesEqual;
3168
- exports.bytesToHex = bytesToHex;
3169
- exports.concatBytes = concatBytes;
4116
+ exports.bytesToHex = bytesToHex$1;
4117
+ exports.concatBytes = concatBytes$1;
3170
4118
  exports.encodeAuthScriptScriptPubKey = encodeAuthScriptScriptPubKey;
3171
4119
  exports.encodeMultisigRedeemScript = encodeMultisigRedeemScript;
3172
4120
  exports.encodeMultisigRedeemScriptHex = encodeMultisigRedeemScriptHex;
@@ -3177,10 +4125,11 @@ exports.encodeP2WPKHScriptPubKey = encodeP2WPKHScriptPubKey;
3177
4125
  exports.encodeP2WSHScriptPubKey = encodeP2WSHScriptPubKey;
3178
4126
  exports.encodeScriptNum = encodeScriptNum;
3179
4127
  exports.encodeSellerScriptPubKey = encodeSellerScriptPubKey;
3180
- exports.ensureHex = ensureHex;
3181
- exports.hexToBytes = hexToBytes;
4128
+ exports.ensureHex = ensureHex$1;
4129
+ exports.hexToBytes = hexToBytes$1;
3182
4130
  exports.isPartialFillScriptPQ = isPartialFillScriptPQ;
3183
4131
  exports.opcodes = opcodes;
4132
+ exports.parseAssetAuthPolicyScript = parseAssetAuthPolicyScript;
3184
4133
  exports.parsePartialFillScript = parsePartialFillScript;
3185
4134
  exports.parsePartialFillScriptPQ = parsePartialFillScriptPQ;
3186
4135
  exports.pushBytes = pushBytes;