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