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