@neuraiproject/neurai-scripts 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/NeuraiScripts.global.js +2333 -0
- package/dist/NeuraiScripts.global.js.map +1 -0
- package/dist/browser.js +2273 -0
- package/dist/browser.js.map +1 -0
- package/dist/index.cjs +2318 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.js +2273 -0
- package/dist/index.js.map +1 -0
- package/package.json +3 -1
package/dist/browser.js
ADDED
|
@@ -0,0 +1,2273 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal byte helpers. A subset of what `neurai-create-transaction` exposes,
|
|
3
|
+
* duplicated here to keep this package free of runtime coupling beyond its
|
|
4
|
+
* declared `dependencies` field. All sizes are little-endian, per Neurai.
|
|
5
|
+
*/
|
|
6
|
+
function ensureHex(hex, label = 'hex') {
|
|
7
|
+
const normalized = String(hex || '').trim().toLowerCase();
|
|
8
|
+
if (!/^[0-9a-f]*$/.test(normalized) || normalized.length % 2 !== 0) {
|
|
9
|
+
throw new Error(`Invalid ${label}: expected even-length hex string`);
|
|
10
|
+
}
|
|
11
|
+
return normalized;
|
|
12
|
+
}
|
|
13
|
+
function hexToBytes(hex) {
|
|
14
|
+
const normalized = ensureHex(hex);
|
|
15
|
+
const bytes = new Uint8Array(normalized.length / 2);
|
|
16
|
+
for (let i = 0; i < normalized.length; i += 2) {
|
|
17
|
+
bytes[i / 2] = Number.parseInt(normalized.slice(i, i + 2), 16);
|
|
18
|
+
}
|
|
19
|
+
return bytes;
|
|
20
|
+
}
|
|
21
|
+
function bytesToHex(bytes) {
|
|
22
|
+
return Array.from(bytes, (value) => value.toString(16).padStart(2, '0')).join('');
|
|
23
|
+
}
|
|
24
|
+
function concatBytes(...parts) {
|
|
25
|
+
const total = parts.reduce((sum, part) => sum + part.length, 0);
|
|
26
|
+
const out = new Uint8Array(total);
|
|
27
|
+
let offset = 0;
|
|
28
|
+
for (const part of parts) {
|
|
29
|
+
out.set(part, offset);
|
|
30
|
+
offset += part.length;
|
|
31
|
+
}
|
|
32
|
+
return out;
|
|
33
|
+
}
|
|
34
|
+
function bytesEqual(a, b) {
|
|
35
|
+
if (a.length !== b.length)
|
|
36
|
+
return false;
|
|
37
|
+
for (let i = 0; i < a.length; i += 1) {
|
|
38
|
+
if (a[i] !== b[i])
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
return true;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Opcode constants for Neurai Script.
|
|
46
|
+
*
|
|
47
|
+
* Covers:
|
|
48
|
+
* - Classic Script opcodes used by covenants.
|
|
49
|
+
* - New opcodes activated in the `DePIN-Test` branch (BIP 119, BIP 347 and
|
|
50
|
+
* Neurai-specific introspection / asset / arithmetic additions).
|
|
51
|
+
*
|
|
52
|
+
* Authority: `src/script/script.h` (enum `opcodetype`) in the Neurai repo.
|
|
53
|
+
* Reference: `doc/new-opcodes-depin-branch.md`.
|
|
54
|
+
*
|
|
55
|
+
* Disabled in consensus and intentionally omitted: OP_SUBSTR, OP_LEFT,
|
|
56
|
+
* OP_RIGHT, OP_INVERT, OP_AND, OP_OR, OP_XOR, OP_2MUL, OP_2DIV, OP_LSHIFT,
|
|
57
|
+
* OP_RSHIFT. Also omitted: OP_VER / OP_VERIF / OP_VERNOTIF (reserved), the
|
|
58
|
+
* template-matching pseudo-opcodes (OP_SMALLINTEGER, OP_PUBKEYS,
|
|
59
|
+
* OP_PUBKEYHASH, OP_PUBKEY) and OP_INVALIDOPCODE.
|
|
60
|
+
*/
|
|
61
|
+
// ---------- Push values ----------
|
|
62
|
+
const OP_0 = 0x00;
|
|
63
|
+
const OP_FALSE = OP_0;
|
|
64
|
+
const OP_PUSHDATA1 = 0x4c;
|
|
65
|
+
const OP_PUSHDATA2 = 0x4d;
|
|
66
|
+
const OP_PUSHDATA4 = 0x4e;
|
|
67
|
+
const OP_1NEGATE = 0x4f;
|
|
68
|
+
const OP_RESERVED = 0x50;
|
|
69
|
+
const OP_1 = 0x51;
|
|
70
|
+
const OP_TRUE = OP_1;
|
|
71
|
+
const OP_2 = 0x52;
|
|
72
|
+
const OP_3 = 0x53;
|
|
73
|
+
const OP_4 = 0x54;
|
|
74
|
+
const OP_5 = 0x55;
|
|
75
|
+
const OP_6 = 0x56;
|
|
76
|
+
const OP_7 = 0x57;
|
|
77
|
+
const OP_8 = 0x58;
|
|
78
|
+
const OP_9 = 0x59;
|
|
79
|
+
const OP_10 = 0x5a;
|
|
80
|
+
const OP_11 = 0x5b;
|
|
81
|
+
const OP_12 = 0x5c;
|
|
82
|
+
const OP_13 = 0x5d;
|
|
83
|
+
const OP_14 = 0x5e;
|
|
84
|
+
const OP_15 = 0x5f;
|
|
85
|
+
const OP_16 = 0x60;
|
|
86
|
+
// ---------- Control flow ----------
|
|
87
|
+
const OP_NOP = 0x61;
|
|
88
|
+
const OP_IF = 0x63;
|
|
89
|
+
const OP_NOTIF = 0x64;
|
|
90
|
+
const OP_ELSE = 0x67;
|
|
91
|
+
const OP_ENDIF = 0x68;
|
|
92
|
+
const OP_VERIFY = 0x69;
|
|
93
|
+
const OP_RETURN = 0x6a;
|
|
94
|
+
// ---------- Stack ----------
|
|
95
|
+
const OP_TOALTSTACK = 0x6b;
|
|
96
|
+
const OP_FROMALTSTACK = 0x6c;
|
|
97
|
+
const OP_2DROP = 0x6d;
|
|
98
|
+
const OP_2DUP = 0x6e;
|
|
99
|
+
const OP_3DUP = 0x6f;
|
|
100
|
+
const OP_2OVER = 0x70;
|
|
101
|
+
const OP_2ROT = 0x71;
|
|
102
|
+
const OP_2SWAP = 0x72;
|
|
103
|
+
const OP_IFDUP = 0x73;
|
|
104
|
+
const OP_DEPTH = 0x74;
|
|
105
|
+
const OP_DROP = 0x75;
|
|
106
|
+
const OP_DUP = 0x76;
|
|
107
|
+
const OP_NIP = 0x77;
|
|
108
|
+
const OP_OVER = 0x78;
|
|
109
|
+
const OP_PICK = 0x79;
|
|
110
|
+
const OP_ROLL = 0x7a;
|
|
111
|
+
const OP_ROT = 0x7b;
|
|
112
|
+
const OP_SWAP = 0x7c;
|
|
113
|
+
const OP_TUCK = 0x7d;
|
|
114
|
+
// ---------- Splice ----------
|
|
115
|
+
const OP_SIZE = 0x82;
|
|
116
|
+
// ---------- Bitwise / comparison ----------
|
|
117
|
+
const OP_EQUAL = 0x87;
|
|
118
|
+
const OP_EQUALVERIFY = 0x88;
|
|
119
|
+
// ---------- Unary numeric ----------
|
|
120
|
+
const OP_1ADD = 0x8b;
|
|
121
|
+
const OP_1SUB = 0x8c;
|
|
122
|
+
const OP_NEGATE = 0x8f;
|
|
123
|
+
const OP_ABS = 0x90;
|
|
124
|
+
const OP_NOT = 0x91;
|
|
125
|
+
const OP_0NOTEQUAL = 0x92;
|
|
126
|
+
// ---------- Arithmetic (64-bit after SCRIPT_VERIFY_64BIT_INTEGERS) ----------
|
|
127
|
+
const OP_ADD = 0x93;
|
|
128
|
+
const OP_SUB = 0x94;
|
|
129
|
+
const OP_MUL = 0x95;
|
|
130
|
+
const OP_DIV = 0x96;
|
|
131
|
+
const OP_MOD = 0x97;
|
|
132
|
+
// ---------- Boolean / numeric comparison ----------
|
|
133
|
+
const OP_BOOLAND = 0x9a;
|
|
134
|
+
const OP_BOOLOR = 0x9b;
|
|
135
|
+
const OP_NUMEQUAL = 0x9c;
|
|
136
|
+
const OP_NUMEQUALVERIFY = 0x9d;
|
|
137
|
+
const OP_NUMNOTEQUAL = 0x9e;
|
|
138
|
+
const OP_LESSTHAN = 0x9f;
|
|
139
|
+
const OP_GREATERTHAN = 0xa0;
|
|
140
|
+
const OP_LESSTHANOREQUAL = 0xa1;
|
|
141
|
+
const OP_GREATERTHANOREQUAL = 0xa2;
|
|
142
|
+
const OP_MIN = 0xa3;
|
|
143
|
+
const OP_MAX = 0xa4;
|
|
144
|
+
const OP_WITHIN = 0xa5;
|
|
145
|
+
// ---------- Crypto ----------
|
|
146
|
+
const OP_RIPEMD160 = 0xa6;
|
|
147
|
+
const OP_SHA1 = 0xa7;
|
|
148
|
+
const OP_SHA256 = 0xa8;
|
|
149
|
+
const OP_HASH160 = 0xa9;
|
|
150
|
+
const OP_HASH256 = 0xaa;
|
|
151
|
+
const OP_CODESEPARATOR = 0xab;
|
|
152
|
+
const OP_CHECKSIG = 0xac;
|
|
153
|
+
const OP_CHECKSIGVERIFY = 0xad;
|
|
154
|
+
const OP_CHECKMULTISIG = 0xae;
|
|
155
|
+
const OP_CHECKMULTISIGVERIFY = 0xaf;
|
|
156
|
+
// ---------- Expansion / NOPs ----------
|
|
157
|
+
// Only the NOPs not aliased by DePIN-Test opcodes are exported as NOPs.
|
|
158
|
+
// OP_NOP2 == OP_CHECKLOCKTIMEVERIFY (0xb1)
|
|
159
|
+
// OP_NOP3 == OP_CHECKSEQUENCEVERIFY (0xb2)
|
|
160
|
+
// OP_NOP4 == OP_CHECKTEMPLATEVERIFY (0xb3)
|
|
161
|
+
// OP_NOP5 == OP_CHECKSIGFROMSTACK (0xb4)
|
|
162
|
+
// OP_NOP6 == OP_TXHASH (0xb5)
|
|
163
|
+
// OP_NOP7 == OP_TXFIELD (0xb6)
|
|
164
|
+
// OP_NOP8 == OP_SPLIT (0xb7)
|
|
165
|
+
const OP_NOP1 = 0xb0;
|
|
166
|
+
const OP_NOP9 = 0xb8;
|
|
167
|
+
const OP_NOP10 = 0xb9;
|
|
168
|
+
// ---------- Locktime ----------
|
|
169
|
+
const OP_CHECKLOCKTIMEVERIFY = 0xb1;
|
|
170
|
+
const OP_CHECKSEQUENCEVERIFY = 0xb2;
|
|
171
|
+
// ---------- Covenants & templates (DePIN-Test) ----------
|
|
172
|
+
const OP_CHECKTEMPLATEVERIFY = 0xb3; // BIP 119
|
|
173
|
+
const OP_CHECKSIGFROMSTACK = 0xb4;
|
|
174
|
+
// ---------- Transaction introspection (DePIN-Test) ----------
|
|
175
|
+
const OP_TXHASH = 0xb5;
|
|
176
|
+
const OP_TXFIELD = 0xb6;
|
|
177
|
+
const OP_TXLOCKTIME = 0xc5;
|
|
178
|
+
const OP_OUTPUTVALUE = 0xcc;
|
|
179
|
+
const OP_OUTPUTSCRIPT = 0xcd;
|
|
180
|
+
const OP_INPUTCOUNT = 0xd0;
|
|
181
|
+
const OP_OUTPUTCOUNT = 0xd1;
|
|
182
|
+
// ---------- Asset introspection (DePIN-Test) ----------
|
|
183
|
+
const OP_OUTPUTASSETFIELD = 0xce;
|
|
184
|
+
const OP_INPUTASSETFIELD = 0xcf;
|
|
185
|
+
const OP_XNA_ASSET = 0xc0;
|
|
186
|
+
// ---------- Reference inputs (DePIN-Test, NIP-017) ----------
|
|
187
|
+
const OP_REFINPUTFIELD = 0xd2;
|
|
188
|
+
const OP_REFINPUTASSETFIELD = 0xd3;
|
|
189
|
+
const OP_REFINPUTCOUNT = 0xd4;
|
|
190
|
+
// ---------- Byte manipulation (DePIN-Test) ----------
|
|
191
|
+
const OP_CAT = 0x7e;
|
|
192
|
+
const OP_SPLIT = 0xb7;
|
|
193
|
+
const OP_REVERSEBYTES = 0xbc;
|
|
194
|
+
// ---------- Selectors for OP_TXFIELD / OP_REFINPUTFIELD ----------
|
|
195
|
+
// Both opcodes share the same selector table (OP_TXFIELD on the spent UTXO,
|
|
196
|
+
// OP_REFINPUTFIELD on an output referenced via vrefin). Valid: 0x01..0x03.
|
|
197
|
+
const TXFIELD_VALUE = 0x01;
|
|
198
|
+
const TXFIELD_AUTHSCRIPT_COMMITMENT = 0x02;
|
|
199
|
+
const TXFIELD_SCRIPTPUBKEY = 0x03;
|
|
200
|
+
// ---------- Bitmask selectors for OP_TXHASH ----------
|
|
201
|
+
// The selector is a single byte where each bit selects which transaction
|
|
202
|
+
// field to include in the double-SHA256. Selector 0x00 is invalid; any
|
|
203
|
+
// non-zero combination is valid. 0xff = all eight fields.
|
|
204
|
+
const TXHASH_VERSION = 0x01;
|
|
205
|
+
const TXHASH_LOCKTIME = 0x02;
|
|
206
|
+
const TXHASH_INPUT_PREVOUTS = 0x04;
|
|
207
|
+
const TXHASH_INPUT_SEQUENCES = 0x08;
|
|
208
|
+
const TXHASH_OUTPUTS = 0x10;
|
|
209
|
+
const TXHASH_CURRENT_PREVOUT = 0x20;
|
|
210
|
+
const TXHASH_CURRENT_SEQUENCE = 0x40;
|
|
211
|
+
const TXHASH_CURRENT_INDEX = 0x80;
|
|
212
|
+
const TXHASH_ALL = 0xff;
|
|
213
|
+
// ---------- Selectors for OP_OUTPUTASSETFIELD / OP_INPUTASSETFIELD / OP_REFINPUTASSETFIELD ----------
|
|
214
|
+
// All three opcodes share the same selector table. Valid range: 0x01..0x07.
|
|
215
|
+
// Selector 0x05 is the boolean "has IPFS" flag; 0x06 is the IPFS hash
|
|
216
|
+
// payload; 0x07 is the asset operation type. (This matches the asset-op
|
|
217
|
+
// encoding in `src/assets/assets.cpp` and the NIP spec §3.1.)
|
|
218
|
+
const ASSETFIELD_NAME = 0x01;
|
|
219
|
+
const ASSETFIELD_AMOUNT = 0x02;
|
|
220
|
+
const ASSETFIELD_UNITS = 0x03;
|
|
221
|
+
const ASSETFIELD_REISSUABLE = 0x04;
|
|
222
|
+
const ASSETFIELD_HAS_IPFS = 0x05;
|
|
223
|
+
const ASSETFIELD_IPFS_HASH = 0x06;
|
|
224
|
+
const ASSETFIELD_TYPE = 0x07;
|
|
225
|
+
|
|
226
|
+
var opcodes = /*#__PURE__*/Object.freeze({
|
|
227
|
+
__proto__: null,
|
|
228
|
+
ASSETFIELD_AMOUNT: ASSETFIELD_AMOUNT,
|
|
229
|
+
ASSETFIELD_HAS_IPFS: ASSETFIELD_HAS_IPFS,
|
|
230
|
+
ASSETFIELD_IPFS_HASH: ASSETFIELD_IPFS_HASH,
|
|
231
|
+
ASSETFIELD_NAME: ASSETFIELD_NAME,
|
|
232
|
+
ASSETFIELD_REISSUABLE: ASSETFIELD_REISSUABLE,
|
|
233
|
+
ASSETFIELD_TYPE: ASSETFIELD_TYPE,
|
|
234
|
+
ASSETFIELD_UNITS: ASSETFIELD_UNITS,
|
|
235
|
+
OP_0: OP_0,
|
|
236
|
+
OP_0NOTEQUAL: OP_0NOTEQUAL,
|
|
237
|
+
OP_1: OP_1,
|
|
238
|
+
OP_10: OP_10,
|
|
239
|
+
OP_11: OP_11,
|
|
240
|
+
OP_12: OP_12,
|
|
241
|
+
OP_13: OP_13,
|
|
242
|
+
OP_14: OP_14,
|
|
243
|
+
OP_15: OP_15,
|
|
244
|
+
OP_16: OP_16,
|
|
245
|
+
OP_1ADD: OP_1ADD,
|
|
246
|
+
OP_1NEGATE: OP_1NEGATE,
|
|
247
|
+
OP_1SUB: OP_1SUB,
|
|
248
|
+
OP_2: OP_2,
|
|
249
|
+
OP_2DROP: OP_2DROP,
|
|
250
|
+
OP_2DUP: OP_2DUP,
|
|
251
|
+
OP_2OVER: OP_2OVER,
|
|
252
|
+
OP_2ROT: OP_2ROT,
|
|
253
|
+
OP_2SWAP: OP_2SWAP,
|
|
254
|
+
OP_3: OP_3,
|
|
255
|
+
OP_3DUP: OP_3DUP,
|
|
256
|
+
OP_4: OP_4,
|
|
257
|
+
OP_5: OP_5,
|
|
258
|
+
OP_6: OP_6,
|
|
259
|
+
OP_7: OP_7,
|
|
260
|
+
OP_8: OP_8,
|
|
261
|
+
OP_9: OP_9,
|
|
262
|
+
OP_ABS: OP_ABS,
|
|
263
|
+
OP_ADD: OP_ADD,
|
|
264
|
+
OP_BOOLAND: OP_BOOLAND,
|
|
265
|
+
OP_BOOLOR: OP_BOOLOR,
|
|
266
|
+
OP_CAT: OP_CAT,
|
|
267
|
+
OP_CHECKLOCKTIMEVERIFY: OP_CHECKLOCKTIMEVERIFY,
|
|
268
|
+
OP_CHECKMULTISIG: OP_CHECKMULTISIG,
|
|
269
|
+
OP_CHECKMULTISIGVERIFY: OP_CHECKMULTISIGVERIFY,
|
|
270
|
+
OP_CHECKSEQUENCEVERIFY: OP_CHECKSEQUENCEVERIFY,
|
|
271
|
+
OP_CHECKSIG: OP_CHECKSIG,
|
|
272
|
+
OP_CHECKSIGFROMSTACK: OP_CHECKSIGFROMSTACK,
|
|
273
|
+
OP_CHECKSIGVERIFY: OP_CHECKSIGVERIFY,
|
|
274
|
+
OP_CHECKTEMPLATEVERIFY: OP_CHECKTEMPLATEVERIFY,
|
|
275
|
+
OP_CODESEPARATOR: OP_CODESEPARATOR,
|
|
276
|
+
OP_DEPTH: OP_DEPTH,
|
|
277
|
+
OP_DIV: OP_DIV,
|
|
278
|
+
OP_DROP: OP_DROP,
|
|
279
|
+
OP_DUP: OP_DUP,
|
|
280
|
+
OP_ELSE: OP_ELSE,
|
|
281
|
+
OP_ENDIF: OP_ENDIF,
|
|
282
|
+
OP_EQUAL: OP_EQUAL,
|
|
283
|
+
OP_EQUALVERIFY: OP_EQUALVERIFY,
|
|
284
|
+
OP_FALSE: OP_FALSE,
|
|
285
|
+
OP_FROMALTSTACK: OP_FROMALTSTACK,
|
|
286
|
+
OP_GREATERTHAN: OP_GREATERTHAN,
|
|
287
|
+
OP_GREATERTHANOREQUAL: OP_GREATERTHANOREQUAL,
|
|
288
|
+
OP_HASH160: OP_HASH160,
|
|
289
|
+
OP_HASH256: OP_HASH256,
|
|
290
|
+
OP_IF: OP_IF,
|
|
291
|
+
OP_IFDUP: OP_IFDUP,
|
|
292
|
+
OP_INPUTASSETFIELD: OP_INPUTASSETFIELD,
|
|
293
|
+
OP_INPUTCOUNT: OP_INPUTCOUNT,
|
|
294
|
+
OP_LESSTHAN: OP_LESSTHAN,
|
|
295
|
+
OP_LESSTHANOREQUAL: OP_LESSTHANOREQUAL,
|
|
296
|
+
OP_MAX: OP_MAX,
|
|
297
|
+
OP_MIN: OP_MIN,
|
|
298
|
+
OP_MOD: OP_MOD,
|
|
299
|
+
OP_MUL: OP_MUL,
|
|
300
|
+
OP_NEGATE: OP_NEGATE,
|
|
301
|
+
OP_NIP: OP_NIP,
|
|
302
|
+
OP_NOP: OP_NOP,
|
|
303
|
+
OP_NOP1: OP_NOP1,
|
|
304
|
+
OP_NOP10: OP_NOP10,
|
|
305
|
+
OP_NOP9: OP_NOP9,
|
|
306
|
+
OP_NOT: OP_NOT,
|
|
307
|
+
OP_NOTIF: OP_NOTIF,
|
|
308
|
+
OP_NUMEQUAL: OP_NUMEQUAL,
|
|
309
|
+
OP_NUMEQUALVERIFY: OP_NUMEQUALVERIFY,
|
|
310
|
+
OP_NUMNOTEQUAL: OP_NUMNOTEQUAL,
|
|
311
|
+
OP_OUTPUTASSETFIELD: OP_OUTPUTASSETFIELD,
|
|
312
|
+
OP_OUTPUTCOUNT: OP_OUTPUTCOUNT,
|
|
313
|
+
OP_OUTPUTSCRIPT: OP_OUTPUTSCRIPT,
|
|
314
|
+
OP_OUTPUTVALUE: OP_OUTPUTVALUE,
|
|
315
|
+
OP_OVER: OP_OVER,
|
|
316
|
+
OP_PICK: OP_PICK,
|
|
317
|
+
OP_PUSHDATA1: OP_PUSHDATA1,
|
|
318
|
+
OP_PUSHDATA2: OP_PUSHDATA2,
|
|
319
|
+
OP_PUSHDATA4: OP_PUSHDATA4,
|
|
320
|
+
OP_REFINPUTASSETFIELD: OP_REFINPUTASSETFIELD,
|
|
321
|
+
OP_REFINPUTCOUNT: OP_REFINPUTCOUNT,
|
|
322
|
+
OP_REFINPUTFIELD: OP_REFINPUTFIELD,
|
|
323
|
+
OP_RESERVED: OP_RESERVED,
|
|
324
|
+
OP_RETURN: OP_RETURN,
|
|
325
|
+
OP_REVERSEBYTES: OP_REVERSEBYTES,
|
|
326
|
+
OP_RIPEMD160: OP_RIPEMD160,
|
|
327
|
+
OP_ROLL: OP_ROLL,
|
|
328
|
+
OP_ROT: OP_ROT,
|
|
329
|
+
OP_SHA1: OP_SHA1,
|
|
330
|
+
OP_SHA256: OP_SHA256,
|
|
331
|
+
OP_SIZE: OP_SIZE,
|
|
332
|
+
OP_SPLIT: OP_SPLIT,
|
|
333
|
+
OP_SUB: OP_SUB,
|
|
334
|
+
OP_SWAP: OP_SWAP,
|
|
335
|
+
OP_TOALTSTACK: OP_TOALTSTACK,
|
|
336
|
+
OP_TRUE: OP_TRUE,
|
|
337
|
+
OP_TUCK: OP_TUCK,
|
|
338
|
+
OP_TXFIELD: OP_TXFIELD,
|
|
339
|
+
OP_TXHASH: OP_TXHASH,
|
|
340
|
+
OP_TXLOCKTIME: OP_TXLOCKTIME,
|
|
341
|
+
OP_VERIFY: OP_VERIFY,
|
|
342
|
+
OP_WITHIN: OP_WITHIN,
|
|
343
|
+
OP_XNA_ASSET: OP_XNA_ASSET,
|
|
344
|
+
TXFIELD_AUTHSCRIPT_COMMITMENT: TXFIELD_AUTHSCRIPT_COMMITMENT,
|
|
345
|
+
TXFIELD_SCRIPTPUBKEY: TXFIELD_SCRIPTPUBKEY,
|
|
346
|
+
TXFIELD_VALUE: TXFIELD_VALUE,
|
|
347
|
+
TXHASH_ALL: TXHASH_ALL,
|
|
348
|
+
TXHASH_CURRENT_INDEX: TXHASH_CURRENT_INDEX,
|
|
349
|
+
TXHASH_CURRENT_PREVOUT: TXHASH_CURRENT_PREVOUT,
|
|
350
|
+
TXHASH_CURRENT_SEQUENCE: TXHASH_CURRENT_SEQUENCE,
|
|
351
|
+
TXHASH_INPUT_PREVOUTS: TXHASH_INPUT_PREVOUTS,
|
|
352
|
+
TXHASH_INPUT_SEQUENCES: TXHASH_INPUT_SEQUENCES,
|
|
353
|
+
TXHASH_LOCKTIME: TXHASH_LOCKTIME,
|
|
354
|
+
TXHASH_OUTPUTS: TXHASH_OUTPUTS,
|
|
355
|
+
TXHASH_VERSION: TXHASH_VERSION
|
|
356
|
+
});
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* Low-level Script assembler. Emits the exact byte layout expected by the
|
|
360
|
+
* Neurai interpreter: pushdata prefixes follow the same rules as Bitcoin
|
|
361
|
+
* (direct push for 1..75 bytes, OP_PUSHDATA1/2/4 otherwise), and integers
|
|
362
|
+
* are minimally-encoded as CScriptNum.
|
|
363
|
+
*/
|
|
364
|
+
/**
|
|
365
|
+
* Minimal CScriptNum encoding (Bitcoin consensus rules).
|
|
366
|
+
*
|
|
367
|
+
* - 0 → empty vector
|
|
368
|
+
* - 1..16 → single opcode OP_1..OP_16 (handled in `pushInt`, not here)
|
|
369
|
+
* - -1 → OP_1NEGATE (handled in `pushInt`)
|
|
370
|
+
* - otherwise: sign-magnitude little-endian, with a sign bit on the last byte
|
|
371
|
+
*/
|
|
372
|
+
function encodeScriptNum(value) {
|
|
373
|
+
let n = typeof value === 'bigint' ? value : BigInt(value);
|
|
374
|
+
if (n === 0n)
|
|
375
|
+
return new Uint8Array();
|
|
376
|
+
const negative = n < 0n;
|
|
377
|
+
if (negative)
|
|
378
|
+
n = -n;
|
|
379
|
+
const result = [];
|
|
380
|
+
while (n > 0n) {
|
|
381
|
+
result.push(Number(n & 0xffn));
|
|
382
|
+
n >>= 8n;
|
|
383
|
+
}
|
|
384
|
+
// If the most-significant bit is set, add a padding byte so the sign bit
|
|
385
|
+
// is unambiguous. If negative, flip that sign bit instead.
|
|
386
|
+
if (result[result.length - 1] & 0x80) {
|
|
387
|
+
result.push(negative ? 0x80 : 0x00);
|
|
388
|
+
}
|
|
389
|
+
else if (negative) {
|
|
390
|
+
result[result.length - 1] |= 0x80;
|
|
391
|
+
}
|
|
392
|
+
return Uint8Array.from(result);
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Emit a pushdata opcode followed by the payload. Chooses the shortest
|
|
396
|
+
* valid encoding.
|
|
397
|
+
*
|
|
398
|
+
* Neurai Script caps stack elements at `MAX_SCRIPT_ELEMENT_SIZE = 520`
|
|
399
|
+
* bytes by default, but NIP-18 raises the cap to
|
|
400
|
+
* `MAX_PQ_SCRIPT_ELEMENT_SIZE = 3072` whenever
|
|
401
|
+
* `SCRIPT_VERIFY_CHECKSIGFROMSTACK` is active (testnet today, mainnet once
|
|
402
|
+
* the CSFS fork lands). The builder here emits pushes up to 3072 bytes so
|
|
403
|
+
* it can target either regime; legacy scripts should stay under 520 bytes
|
|
404
|
+
* per push, and the node will reject anything larger if the CSFS flag is
|
|
405
|
+
* not set during evaluation.
|
|
406
|
+
*/
|
|
407
|
+
function pushBytes(data) {
|
|
408
|
+
if (data.length === 0) {
|
|
409
|
+
return Uint8Array.of(OP_0);
|
|
410
|
+
}
|
|
411
|
+
if (data.length <= 75) {
|
|
412
|
+
return concatBytes(Uint8Array.of(data.length), data);
|
|
413
|
+
}
|
|
414
|
+
if (data.length <= 0xff) {
|
|
415
|
+
return concatBytes(Uint8Array.of(0x4c, data.length), data);
|
|
416
|
+
}
|
|
417
|
+
if (data.length <= 3072) {
|
|
418
|
+
return concatBytes(Uint8Array.of(0x4d, data.length & 0xff, (data.length >> 8) & 0xff), data);
|
|
419
|
+
}
|
|
420
|
+
throw new Error(`pushBytes: element of ${data.length} bytes exceeds MAX_PQ_SCRIPT_ELEMENT_SIZE (3072)`);
|
|
421
|
+
}
|
|
422
|
+
/**
|
|
423
|
+
* Emit a minimally-encoded integer push. Uses OP_1NEGATE, OP_0 and OP_1..OP_16
|
|
424
|
+
* when available to match how the node's own templates look on the wire.
|
|
425
|
+
*/
|
|
426
|
+
function pushInt(value) {
|
|
427
|
+
const n = typeof value === 'bigint' ? value : BigInt(value);
|
|
428
|
+
if (n === -1n)
|
|
429
|
+
return Uint8Array.of(OP_1NEGATE);
|
|
430
|
+
if (n === 0n)
|
|
431
|
+
return Uint8Array.of(OP_0);
|
|
432
|
+
if (n >= 1n && n <= 16n) {
|
|
433
|
+
return Uint8Array.of(OP_1 + Number(n) - 1);
|
|
434
|
+
}
|
|
435
|
+
return pushBytes(encodeScriptNum(n));
|
|
436
|
+
}
|
|
437
|
+
function pushHex(hex) {
|
|
438
|
+
return pushBytes(hexToBytes(hex));
|
|
439
|
+
}
|
|
440
|
+
/** Fluent assembler for readable script definitions. */
|
|
441
|
+
class ScriptBuilder {
|
|
442
|
+
parts = [];
|
|
443
|
+
op(...opcodes) {
|
|
444
|
+
for (const op of opcodes) {
|
|
445
|
+
if (!Number.isInteger(op) || op < 0 || op > 0xff) {
|
|
446
|
+
throw new Error(`Invalid opcode byte: ${op}`);
|
|
447
|
+
}
|
|
448
|
+
this.parts.push(Uint8Array.of(op));
|
|
449
|
+
}
|
|
450
|
+
return this;
|
|
451
|
+
}
|
|
452
|
+
pushInt(value) {
|
|
453
|
+
this.parts.push(pushInt(value));
|
|
454
|
+
return this;
|
|
455
|
+
}
|
|
456
|
+
pushBytes(data) {
|
|
457
|
+
this.parts.push(pushBytes(data));
|
|
458
|
+
return this;
|
|
459
|
+
}
|
|
460
|
+
pushHex(hex) {
|
|
461
|
+
this.parts.push(pushHex(hex));
|
|
462
|
+
return this;
|
|
463
|
+
}
|
|
464
|
+
raw(bytes) {
|
|
465
|
+
this.parts.push(bytes);
|
|
466
|
+
return this;
|
|
467
|
+
}
|
|
468
|
+
build() {
|
|
469
|
+
return concatBytes(...this.parts);
|
|
470
|
+
}
|
|
471
|
+
buildHex() {
|
|
472
|
+
return bytesToHex(this.build());
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* Pay-to-Public-Key-Hash (P2PKH) scriptPubKey.
|
|
478
|
+
* Layout: OP_DUP OP_HASH160 0x14 <20-byte PKH> OP_EQUALVERIFY OP_CHECKSIG
|
|
479
|
+
*/
|
|
480
|
+
function encodeP2PKHScriptPubKey(pubKeyHash) {
|
|
481
|
+
if (!(pubKeyHash instanceof Uint8Array) || pubKeyHash.length !== 20) {
|
|
482
|
+
throw new Error('P2PKH pubKeyHash must be a 20-byte Uint8Array');
|
|
483
|
+
}
|
|
484
|
+
return concatBytes(Uint8Array.of(OP_DUP, OP_HASH160, 0x14), pubKeyHash, Uint8Array.of(OP_EQUALVERIFY, OP_CHECKSIG));
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* Native segwit v0 Pay-to-Witness-Public-Key-Hash (P2WPKH) scriptPubKey.
|
|
489
|
+
* Layout: OP_0 0x14 <20-byte HASH160(pubKey)>
|
|
490
|
+
*
|
|
491
|
+
* Callers compute HASH160 externally (e.g. via neurai-key / their crypto
|
|
492
|
+
* stack). This helper only encodes the scriptPubKey once the hash is known.
|
|
493
|
+
*/
|
|
494
|
+
function encodeP2WPKHScriptPubKey(pubKeyHash) {
|
|
495
|
+
if (!(pubKeyHash instanceof Uint8Array) || pubKeyHash.length !== 20) {
|
|
496
|
+
throw new Error('P2WPKH pubKeyHash must be a 20-byte Uint8Array');
|
|
497
|
+
}
|
|
498
|
+
return concatBytes(Uint8Array.of(OP_0, 0x14), pubKeyHash);
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/**
|
|
502
|
+
* Native segwit v0 Pay-to-Witness-Script-Hash (P2WSH) scriptPubKey.
|
|
503
|
+
* Layout: OP_0 0x20 <32-byte SHA256(witnessScript)>
|
|
504
|
+
*
|
|
505
|
+
* This helper takes the SHA256 digest of the witness script directly. The
|
|
506
|
+
* SHA256 is computed externally by the caller's crypto stack (kept out of
|
|
507
|
+
* this library to avoid a hash dependency).
|
|
508
|
+
*/
|
|
509
|
+
function encodeP2WSHScriptPubKey(witnessScriptSha256) {
|
|
510
|
+
if (!(witnessScriptSha256 instanceof Uint8Array) || witnessScriptSha256.length !== 32) {
|
|
511
|
+
throw new Error('P2WSH witnessScriptSha256 must be a 32-byte Uint8Array');
|
|
512
|
+
}
|
|
513
|
+
return concatBytes(Uint8Array.of(OP_0, 0x20), witnessScriptSha256);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* AuthScript (witness v1) scriptPubKey + witness-stack builders.
|
|
518
|
+
*
|
|
519
|
+
* AuthScript outputs encode a 32-byte commitment in a witness v1 program:
|
|
520
|
+
* scriptPubKey = OP_1 0x20 <32-byte program>
|
|
521
|
+
*
|
|
522
|
+
* The program is `HASH160`/`SHA256` over a descriptor that depends on the
|
|
523
|
+
* `auth_type` byte carried as the first witness-stack element at spend time.
|
|
524
|
+
* This library only assembles the stack; computing the descriptor/commitment
|
|
525
|
+
* and producing the signature live in neurai-key / neurai-sign-transaction.
|
|
526
|
+
*
|
|
527
|
+
* Auth type values (authoritative: Neurai `src/script/interpreter.cpp`,
|
|
528
|
+
* cross-checked against `lib/neurai-key/src/shared/address.ts`):
|
|
529
|
+
*
|
|
530
|
+
* 0x00 NoAuth — no signature; spend gated only by witnessScript
|
|
531
|
+
* 0x01 PQ — ML-DSA-44 signature (post-quantum)
|
|
532
|
+
* 0x02 Legacy — secp256k1 ECDSA signature (classic)
|
|
533
|
+
* 0x03 RefScript — NIP-015 reference-script spend (future)
|
|
534
|
+
*
|
|
535
|
+
* Witness stack (exact order consumed by the interpreter):
|
|
536
|
+
* [ auth_type, sig, pubkey, arg0, ..., argN, witnessScript ]
|
|
537
|
+
*
|
|
538
|
+
* NoAuth and RefScript spends omit the `sig`/`pubkey` items.
|
|
539
|
+
*/
|
|
540
|
+
const AUTHSCRIPT_NOAUTH = 0x00;
|
|
541
|
+
const AUTHSCRIPT_PQ = 0x01;
|
|
542
|
+
const AUTHSCRIPT_LEGACY = 0x02;
|
|
543
|
+
/** NIP-015: reference-script spend mode. Not yet activated in consensus. */
|
|
544
|
+
const AUTHSCRIPT_REF = 0x03;
|
|
545
|
+
/** Cap for PQ signature / pubkey pushes under NIP-018 (3072 B). */
|
|
546
|
+
const MAX_PQ_PUSH = 3072;
|
|
547
|
+
function encodeAuthScriptScriptPubKey(program) {
|
|
548
|
+
if (!(program instanceof Uint8Array) || program.length !== 32) {
|
|
549
|
+
throw new Error('AuthScript program must be a 32-byte Uint8Array');
|
|
550
|
+
}
|
|
551
|
+
return concatBytes(Uint8Array.of(OP_1, 0x20), program);
|
|
552
|
+
}
|
|
553
|
+
function assertWitnessScript(ws) {
|
|
554
|
+
if (!(ws instanceof Uint8Array) || ws.length === 0) {
|
|
555
|
+
throw new Error('witnessScript must be a non-empty Uint8Array');
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
function assertArgs(args) {
|
|
559
|
+
if (args == null)
|
|
560
|
+
return;
|
|
561
|
+
if (!Array.isArray(args)) {
|
|
562
|
+
throw new Error('args must be an array of Uint8Array');
|
|
563
|
+
}
|
|
564
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
565
|
+
if (!(args[i] instanceof Uint8Array)) {
|
|
566
|
+
throw new Error(`args[${i}] must be a Uint8Array`);
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
/**
|
|
571
|
+
* Build the witness stack for a legacy ECDSA AuthScript spend.
|
|
572
|
+
*
|
|
573
|
+
* Returns an array of raw stack elements. Serialization of the witness
|
|
574
|
+
* (compact-size item count + per-item length-prefixes) is the caller's
|
|
575
|
+
* responsibility — neurai-create-transaction handles it at tx-assembly time.
|
|
576
|
+
*/
|
|
577
|
+
function buildAuthScriptWitnessLegacy(input) {
|
|
578
|
+
if (!(input.signature instanceof Uint8Array) || input.signature.length === 0) {
|
|
579
|
+
throw new Error('signature must be a non-empty Uint8Array');
|
|
580
|
+
}
|
|
581
|
+
if (!(input.pubKey instanceof Uint8Array) ||
|
|
582
|
+
(input.pubKey.length !== 33 && input.pubKey.length !== 65)) {
|
|
583
|
+
throw new Error('pubKey must be a compressed (33B) or uncompressed (65B) secp256k1 key');
|
|
584
|
+
}
|
|
585
|
+
assertArgs(input.args);
|
|
586
|
+
assertWitnessScript(input.witnessScript);
|
|
587
|
+
return [
|
|
588
|
+
Uint8Array.of(AUTHSCRIPT_LEGACY),
|
|
589
|
+
input.signature,
|
|
590
|
+
input.pubKey,
|
|
591
|
+
...(input.args ?? []),
|
|
592
|
+
input.witnessScript
|
|
593
|
+
];
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Build the witness stack for a PQ (ML-DSA-44) AuthScript spend.
|
|
597
|
+
* NIP-018 must be active: both signature and pubKey are pushed as single
|
|
598
|
+
* stack elements and may each be up to 3072 B.
|
|
599
|
+
*/
|
|
600
|
+
function buildAuthScriptWitnessPQ(input) {
|
|
601
|
+
if (!(input.signature instanceof Uint8Array) || input.signature.length === 0) {
|
|
602
|
+
throw new Error('signature must be a non-empty Uint8Array');
|
|
603
|
+
}
|
|
604
|
+
if (input.signature.length > MAX_PQ_PUSH) {
|
|
605
|
+
throw new Error(`signature of ${input.signature.length} bytes exceeds MAX_PQ_SCRIPT_ELEMENT_SIZE (${MAX_PQ_PUSH})`);
|
|
606
|
+
}
|
|
607
|
+
if (!(input.pubKey instanceof Uint8Array) || input.pubKey.length === 0) {
|
|
608
|
+
throw new Error('pubKey must be a non-empty Uint8Array');
|
|
609
|
+
}
|
|
610
|
+
if (input.pubKey.length > MAX_PQ_PUSH) {
|
|
611
|
+
throw new Error(`pubKey of ${input.pubKey.length} bytes exceeds MAX_PQ_SCRIPT_ELEMENT_SIZE (${MAX_PQ_PUSH})`);
|
|
612
|
+
}
|
|
613
|
+
assertArgs(input.args);
|
|
614
|
+
assertWitnessScript(input.witnessScript);
|
|
615
|
+
return [
|
|
616
|
+
Uint8Array.of(AUTHSCRIPT_PQ),
|
|
617
|
+
input.signature,
|
|
618
|
+
input.pubKey,
|
|
619
|
+
...(input.args ?? []),
|
|
620
|
+
input.witnessScript
|
|
621
|
+
];
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* Build the witness stack for a NoAuth AuthScript spend. The spend is gated
|
|
625
|
+
* by the witnessScript alone (covenants, hash-locks, time-locks, ...); no
|
|
626
|
+
* signature or public key is carried.
|
|
627
|
+
*/
|
|
628
|
+
function buildAuthScriptWitnessNoAuth(input) {
|
|
629
|
+
assertArgs(input.args);
|
|
630
|
+
assertWitnessScript(input.witnessScript);
|
|
631
|
+
return [
|
|
632
|
+
Uint8Array.of(AUTHSCRIPT_NOAUTH),
|
|
633
|
+
...(input.args ?? []),
|
|
634
|
+
input.witnessScript
|
|
635
|
+
];
|
|
636
|
+
}
|
|
637
|
+
/**
|
|
638
|
+
* Build the witness stack for a NIP-015 reference-script spend. The last
|
|
639
|
+
* item is the 4-byte little-endian index into `tx.vrefin` that locates the
|
|
640
|
+
* reference-script carrier output; the interpreter resolves the `refScript`
|
|
641
|
+
* from that carrier at validation time.
|
|
642
|
+
*
|
|
643
|
+
* NOTE: NIP-015 is not yet activated in consensus. This builder emits the
|
|
644
|
+
* spec-conformant witness for forward compatibility and testnet experiments.
|
|
645
|
+
*/
|
|
646
|
+
function buildAuthScriptWitnessRef(input) {
|
|
647
|
+
if (!Number.isInteger(input.refIndex) || input.refIndex < 0 || input.refIndex > 0xffffffff) {
|
|
648
|
+
throw new Error('refIndex must be a uint32 (0 .. 2^32 - 1)');
|
|
649
|
+
}
|
|
650
|
+
assertArgs(input.args);
|
|
651
|
+
const refLocator = new Uint8Array(4);
|
|
652
|
+
const dv = new DataView(refLocator.buffer);
|
|
653
|
+
dv.setUint32(0, input.refIndex, /* little-endian */ true);
|
|
654
|
+
return [
|
|
655
|
+
Uint8Array.of(AUTHSCRIPT_REF),
|
|
656
|
+
...(input.args ?? []),
|
|
657
|
+
refLocator
|
|
658
|
+
];
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
/**
|
|
662
|
+
* Provably-unspendable OP_RETURN (null-data) output scripts.
|
|
663
|
+
* Layout: OP_RETURN <push> [<push> ...]
|
|
664
|
+
*
|
|
665
|
+
* Neurai inherits the Bitcoin Core standard policy cap of 80 bytes of
|
|
666
|
+
* payload for a relayed null-data output. Outputs over that cap are still
|
|
667
|
+
* consensus-valid but will not be relayed by default mempool policy; use
|
|
668
|
+
* the `allowNonStandard` option to opt in explicitly.
|
|
669
|
+
*/
|
|
670
|
+
const NULLDATA_STANDARD_MAX_SIZE = 80;
|
|
671
|
+
function encodeNullDataScript(payload, options = {}) {
|
|
672
|
+
const payloads = payload instanceof Uint8Array ? [payload] : payload;
|
|
673
|
+
if (!Array.isArray(payloads) || payloads.length === 0) {
|
|
674
|
+
throw new Error('payload must be a Uint8Array or a non-empty array of Uint8Array');
|
|
675
|
+
}
|
|
676
|
+
let totalPayload = 0;
|
|
677
|
+
for (let i = 0; i < payloads.length; i += 1) {
|
|
678
|
+
const p = payloads[i];
|
|
679
|
+
if (!(p instanceof Uint8Array)) {
|
|
680
|
+
throw new Error(`payload[${i}] must be a Uint8Array`);
|
|
681
|
+
}
|
|
682
|
+
totalPayload += p.length;
|
|
683
|
+
}
|
|
684
|
+
if (!options.allowNonStandard && totalPayload > NULLDATA_STANDARD_MAX_SIZE) {
|
|
685
|
+
throw new Error(`nulldata payload of ${totalPayload} bytes exceeds standard cap ${NULLDATA_STANDARD_MAX_SIZE}; set allowNonStandard=true to override`);
|
|
686
|
+
}
|
|
687
|
+
const parts = [Uint8Array.of(OP_RETURN)];
|
|
688
|
+
for (const p of payloads)
|
|
689
|
+
parts.push(pushBytes(p));
|
|
690
|
+
return concatBytes(...parts);
|
|
691
|
+
}
|
|
692
|
+
|
|
693
|
+
/**
|
|
694
|
+
* Classic bare m-of-n multisig via OP_CHECKMULTISIG, plus the P2SH wrapper
|
|
695
|
+
* that is normally used in practice.
|
|
696
|
+
*
|
|
697
|
+
* redeemScript = <m> <pubkey_1> ... <pubkey_n> <n> OP_CHECKMULTISIG
|
|
698
|
+
* P2SH spk = OP_HASH160 0x14 <HASH160(redeemScript)> OP_EQUAL
|
|
699
|
+
*
|
|
700
|
+
* OP_CHECKMULTISIG caps n at 20 pubkeys (see `MAX_PUBKEYS_PER_MULTISIG` in
|
|
701
|
+
* the Neurai interpreter). Bare multisig outputs are still consensus-valid
|
|
702
|
+
* but non-standard for relay; the P2SH wrapping is what mempool accepts.
|
|
703
|
+
*/
|
|
704
|
+
const MULTISIG_MAX_PUBKEYS = 20;
|
|
705
|
+
function assertPubKey(pk, idx) {
|
|
706
|
+
if (!(pk instanceof Uint8Array) || (pk.length !== 33 && pk.length !== 65)) {
|
|
707
|
+
throw new Error(`pubKey[${idx}] must be 33 or 65 bytes (got ${pk?.length})`);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
function encodeMultisigRedeemScript({ m, pubKeys }) {
|
|
711
|
+
if (!Array.isArray(pubKeys) || pubKeys.length === 0) {
|
|
712
|
+
throw new Error('pubKeys must be a non-empty array');
|
|
713
|
+
}
|
|
714
|
+
if (pubKeys.length > MULTISIG_MAX_PUBKEYS) {
|
|
715
|
+
throw new Error(`pubKeys length ${pubKeys.length} exceeds OP_CHECKMULTISIG cap (${MULTISIG_MAX_PUBKEYS})`);
|
|
716
|
+
}
|
|
717
|
+
if (!Number.isInteger(m) || m < 1 || m > pubKeys.length) {
|
|
718
|
+
throw new Error(`m must be an integer in [1, ${pubKeys.length}] (got ${m})`);
|
|
719
|
+
}
|
|
720
|
+
for (let i = 0; i < pubKeys.length; i += 1)
|
|
721
|
+
assertPubKey(pubKeys[i], i);
|
|
722
|
+
const parts = [pushInt(m)];
|
|
723
|
+
for (const pk of pubKeys)
|
|
724
|
+
parts.push(pushBytes(pk));
|
|
725
|
+
parts.push(pushInt(pubKeys.length));
|
|
726
|
+
parts.push(Uint8Array.of(OP_CHECKMULTISIG));
|
|
727
|
+
return concatBytes(...parts);
|
|
728
|
+
}
|
|
729
|
+
function encodeMultisigRedeemScriptHex(params) {
|
|
730
|
+
return bytesToHex(encodeMultisigRedeemScript(params));
|
|
731
|
+
}
|
|
732
|
+
/**
|
|
733
|
+
* P2SH scriptPubKey wrapping any redeem script. Pass the 20-byte HASH160 of
|
|
734
|
+
* the redeem script (RIPEMD160(SHA256(redeemScript))) — compute it
|
|
735
|
+
* externally via the caller's crypto stack.
|
|
736
|
+
*/
|
|
737
|
+
function encodeP2SHScriptPubKey(redeemScriptHash160) {
|
|
738
|
+
if (!(redeemScriptHash160 instanceof Uint8Array) || redeemScriptHash160.length !== 20) {
|
|
739
|
+
throw new Error('redeemScriptHash160 must be a 20-byte Uint8Array');
|
|
740
|
+
}
|
|
741
|
+
return concatBytes(Uint8Array.of(OP_HASH160, 0x14), redeemScriptHash160, Uint8Array.of(OP_EQUAL));
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
// base-x encoding / decoding
|
|
745
|
+
// Copyright (c) 2018 base-x contributors
|
|
746
|
+
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
|
|
747
|
+
// Distributed under the MIT software license, see the accompanying
|
|
748
|
+
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
|
|
749
|
+
function base (ALPHABET) {
|
|
750
|
+
if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }
|
|
751
|
+
const BASE_MAP = new Uint8Array(256);
|
|
752
|
+
for (let j = 0; j < BASE_MAP.length; j++) {
|
|
753
|
+
BASE_MAP[j] = 255;
|
|
754
|
+
}
|
|
755
|
+
for (let i = 0; i < ALPHABET.length; i++) {
|
|
756
|
+
const x = ALPHABET.charAt(i);
|
|
757
|
+
const xc = x.charCodeAt(0);
|
|
758
|
+
if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }
|
|
759
|
+
BASE_MAP[xc] = i;
|
|
760
|
+
}
|
|
761
|
+
const BASE = ALPHABET.length;
|
|
762
|
+
const LEADER = ALPHABET.charAt(0);
|
|
763
|
+
const FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up
|
|
764
|
+
const iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up
|
|
765
|
+
function encode (source) {
|
|
766
|
+
// eslint-disable-next-line no-empty
|
|
767
|
+
if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {
|
|
768
|
+
source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);
|
|
769
|
+
} else if (Array.isArray(source)) {
|
|
770
|
+
source = Uint8Array.from(source);
|
|
771
|
+
}
|
|
772
|
+
if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }
|
|
773
|
+
if (source.length === 0) { return '' }
|
|
774
|
+
// Skip & count leading zeroes.
|
|
775
|
+
let zeroes = 0;
|
|
776
|
+
let length = 0;
|
|
777
|
+
let pbegin = 0;
|
|
778
|
+
const pend = source.length;
|
|
779
|
+
while (pbegin !== pend && source[pbegin] === 0) {
|
|
780
|
+
pbegin++;
|
|
781
|
+
zeroes++;
|
|
782
|
+
}
|
|
783
|
+
// Allocate enough space in big-endian base58 representation.
|
|
784
|
+
const size = ((pend - pbegin) * iFACTOR + 1) >>> 0;
|
|
785
|
+
const b58 = new Uint8Array(size);
|
|
786
|
+
// Process the bytes.
|
|
787
|
+
while (pbegin !== pend) {
|
|
788
|
+
let carry = source[pbegin];
|
|
789
|
+
// Apply "b58 = b58 * 256 + ch".
|
|
790
|
+
let i = 0;
|
|
791
|
+
for (let it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
|
|
792
|
+
carry += (256 * b58[it1]) >>> 0;
|
|
793
|
+
b58[it1] = (carry % BASE) >>> 0;
|
|
794
|
+
carry = (carry / BASE) >>> 0;
|
|
795
|
+
}
|
|
796
|
+
if (carry !== 0) { throw new Error('Non-zero carry') }
|
|
797
|
+
length = i;
|
|
798
|
+
pbegin++;
|
|
799
|
+
}
|
|
800
|
+
// Skip leading zeroes in base58 result.
|
|
801
|
+
let it2 = size - length;
|
|
802
|
+
while (it2 !== size && b58[it2] === 0) {
|
|
803
|
+
it2++;
|
|
804
|
+
}
|
|
805
|
+
// Translate the result into a string.
|
|
806
|
+
let str = LEADER.repeat(zeroes);
|
|
807
|
+
for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }
|
|
808
|
+
return str
|
|
809
|
+
}
|
|
810
|
+
function decodeUnsafe (source) {
|
|
811
|
+
if (typeof source !== 'string') { throw new TypeError('Expected String') }
|
|
812
|
+
if (source.length === 0) { return new Uint8Array() }
|
|
813
|
+
let psz = 0;
|
|
814
|
+
// Skip and count leading '1's.
|
|
815
|
+
let zeroes = 0;
|
|
816
|
+
let length = 0;
|
|
817
|
+
while (source[psz] === LEADER) {
|
|
818
|
+
zeroes++;
|
|
819
|
+
psz++;
|
|
820
|
+
}
|
|
821
|
+
// Allocate enough space in big-endian base256 representation.
|
|
822
|
+
const size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.
|
|
823
|
+
const b256 = new Uint8Array(size);
|
|
824
|
+
// Process the characters.
|
|
825
|
+
while (psz < source.length) {
|
|
826
|
+
// Find code of next character
|
|
827
|
+
const charCode = source.charCodeAt(psz);
|
|
828
|
+
// Base map can not be indexed using char code
|
|
829
|
+
if (charCode > 255) { return }
|
|
830
|
+
// Decode character
|
|
831
|
+
let carry = BASE_MAP[charCode];
|
|
832
|
+
// Invalid character
|
|
833
|
+
if (carry === 255) { return }
|
|
834
|
+
let i = 0;
|
|
835
|
+
for (let it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
|
|
836
|
+
carry += (BASE * b256[it3]) >>> 0;
|
|
837
|
+
b256[it3] = (carry % 256) >>> 0;
|
|
838
|
+
carry = (carry / 256) >>> 0;
|
|
839
|
+
}
|
|
840
|
+
if (carry !== 0) { throw new Error('Non-zero carry') }
|
|
841
|
+
length = i;
|
|
842
|
+
psz++;
|
|
843
|
+
}
|
|
844
|
+
// Skip leading zeroes in b256.
|
|
845
|
+
let it4 = size - length;
|
|
846
|
+
while (it4 !== size && b256[it4] === 0) {
|
|
847
|
+
it4++;
|
|
848
|
+
}
|
|
849
|
+
const vch = new Uint8Array(zeroes + (size - it4));
|
|
850
|
+
let j = zeroes;
|
|
851
|
+
while (it4 !== size) {
|
|
852
|
+
vch[j++] = b256[it4++];
|
|
853
|
+
}
|
|
854
|
+
return vch
|
|
855
|
+
}
|
|
856
|
+
function decode (string) {
|
|
857
|
+
const buffer = decodeUnsafe(string);
|
|
858
|
+
if (buffer) { return buffer }
|
|
859
|
+
throw new Error('Non-base' + BASE + ' character')
|
|
860
|
+
}
|
|
861
|
+
return {
|
|
862
|
+
encode,
|
|
863
|
+
decodeUnsafe,
|
|
864
|
+
decode
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
|
|
869
|
+
var base58 = base(ALPHABET);
|
|
870
|
+
|
|
871
|
+
var dist = {};
|
|
872
|
+
|
|
873
|
+
var hasRequiredDist;
|
|
874
|
+
|
|
875
|
+
function requireDist () {
|
|
876
|
+
if (hasRequiredDist) return dist;
|
|
877
|
+
hasRequiredDist = 1;
|
|
878
|
+
Object.defineProperty(dist, "__esModule", { value: true });
|
|
879
|
+
dist.bech32m = dist.bech32 = void 0;
|
|
880
|
+
const ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';
|
|
881
|
+
const ALPHABET_MAP = {};
|
|
882
|
+
for (let z = 0; z < ALPHABET.length; z++) {
|
|
883
|
+
const x = ALPHABET.charAt(z);
|
|
884
|
+
ALPHABET_MAP[x] = z;
|
|
885
|
+
}
|
|
886
|
+
function polymodStep(pre) {
|
|
887
|
+
const b = pre >> 25;
|
|
888
|
+
return (((pre & 0x1ffffff) << 5) ^
|
|
889
|
+
(-((b >> 0) & 1) & 0x3b6a57b2) ^
|
|
890
|
+
(-((b >> 1) & 1) & 0x26508e6d) ^
|
|
891
|
+
(-((b >> 2) & 1) & 0x1ea119fa) ^
|
|
892
|
+
(-((b >> 3) & 1) & 0x3d4233dd) ^
|
|
893
|
+
(-((b >> 4) & 1) & 0x2a1462b3));
|
|
894
|
+
}
|
|
895
|
+
function prefixChk(prefix) {
|
|
896
|
+
let chk = 1;
|
|
897
|
+
for (let i = 0; i < prefix.length; ++i) {
|
|
898
|
+
const c = prefix.charCodeAt(i);
|
|
899
|
+
if (c < 33 || c > 126)
|
|
900
|
+
return 'Invalid prefix (' + prefix + ')';
|
|
901
|
+
chk = polymodStep(chk) ^ (c >> 5);
|
|
902
|
+
}
|
|
903
|
+
chk = polymodStep(chk);
|
|
904
|
+
for (let i = 0; i < prefix.length; ++i) {
|
|
905
|
+
const v = prefix.charCodeAt(i);
|
|
906
|
+
chk = polymodStep(chk) ^ (v & 0x1f);
|
|
907
|
+
}
|
|
908
|
+
return chk;
|
|
909
|
+
}
|
|
910
|
+
function convert(data, inBits, outBits, pad) {
|
|
911
|
+
let value = 0;
|
|
912
|
+
let bits = 0;
|
|
913
|
+
const maxV = (1 << outBits) - 1;
|
|
914
|
+
const result = [];
|
|
915
|
+
for (let i = 0; i < data.length; ++i) {
|
|
916
|
+
value = (value << inBits) | data[i];
|
|
917
|
+
bits += inBits;
|
|
918
|
+
while (bits >= outBits) {
|
|
919
|
+
bits -= outBits;
|
|
920
|
+
result.push((value >> bits) & maxV);
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
if (pad) {
|
|
924
|
+
if (bits > 0) {
|
|
925
|
+
result.push((value << (outBits - bits)) & maxV);
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
else {
|
|
929
|
+
if (bits >= inBits)
|
|
930
|
+
return 'Excess padding';
|
|
931
|
+
if ((value << (outBits - bits)) & maxV)
|
|
932
|
+
return 'Non-zero padding';
|
|
933
|
+
}
|
|
934
|
+
return result;
|
|
935
|
+
}
|
|
936
|
+
function toWords(bytes) {
|
|
937
|
+
return convert(bytes, 8, 5, true);
|
|
938
|
+
}
|
|
939
|
+
function fromWordsUnsafe(words) {
|
|
940
|
+
const res = convert(words, 5, 8, false);
|
|
941
|
+
if (Array.isArray(res))
|
|
942
|
+
return res;
|
|
943
|
+
}
|
|
944
|
+
function fromWords(words) {
|
|
945
|
+
const res = convert(words, 5, 8, false);
|
|
946
|
+
if (Array.isArray(res))
|
|
947
|
+
return res;
|
|
948
|
+
throw new Error(res);
|
|
949
|
+
}
|
|
950
|
+
function getLibraryFromEncoding(encoding) {
|
|
951
|
+
let ENCODING_CONST;
|
|
952
|
+
if (encoding === 'bech32') {
|
|
953
|
+
ENCODING_CONST = 1;
|
|
954
|
+
}
|
|
955
|
+
else {
|
|
956
|
+
ENCODING_CONST = 0x2bc830a3;
|
|
957
|
+
}
|
|
958
|
+
function encode(prefix, words, LIMIT) {
|
|
959
|
+
LIMIT = LIMIT || 90;
|
|
960
|
+
if (prefix.length + 7 + words.length > LIMIT)
|
|
961
|
+
throw new TypeError('Exceeds length limit');
|
|
962
|
+
prefix = prefix.toLowerCase();
|
|
963
|
+
// determine chk mod
|
|
964
|
+
let chk = prefixChk(prefix);
|
|
965
|
+
if (typeof chk === 'string')
|
|
966
|
+
throw new Error(chk);
|
|
967
|
+
let result = prefix + '1';
|
|
968
|
+
for (let i = 0; i < words.length; ++i) {
|
|
969
|
+
const x = words[i];
|
|
970
|
+
if (x >> 5 !== 0)
|
|
971
|
+
throw new Error('Non 5-bit word');
|
|
972
|
+
chk = polymodStep(chk) ^ x;
|
|
973
|
+
result += ALPHABET.charAt(x);
|
|
974
|
+
}
|
|
975
|
+
for (let i = 0; i < 6; ++i) {
|
|
976
|
+
chk = polymodStep(chk);
|
|
977
|
+
}
|
|
978
|
+
chk ^= ENCODING_CONST;
|
|
979
|
+
for (let i = 0; i < 6; ++i) {
|
|
980
|
+
const v = (chk >> ((5 - i) * 5)) & 0x1f;
|
|
981
|
+
result += ALPHABET.charAt(v);
|
|
982
|
+
}
|
|
983
|
+
return result;
|
|
984
|
+
}
|
|
985
|
+
function __decode(str, LIMIT) {
|
|
986
|
+
LIMIT = LIMIT || 90;
|
|
987
|
+
if (str.length < 8)
|
|
988
|
+
return str + ' too short';
|
|
989
|
+
if (str.length > LIMIT)
|
|
990
|
+
return 'Exceeds length limit';
|
|
991
|
+
// don't allow mixed case
|
|
992
|
+
const lowered = str.toLowerCase();
|
|
993
|
+
const uppered = str.toUpperCase();
|
|
994
|
+
if (str !== lowered && str !== uppered)
|
|
995
|
+
return 'Mixed-case string ' + str;
|
|
996
|
+
str = lowered;
|
|
997
|
+
const split = str.lastIndexOf('1');
|
|
998
|
+
if (split === -1)
|
|
999
|
+
return 'No separator character for ' + str;
|
|
1000
|
+
if (split === 0)
|
|
1001
|
+
return 'Missing prefix for ' + str;
|
|
1002
|
+
const prefix = str.slice(0, split);
|
|
1003
|
+
const wordChars = str.slice(split + 1);
|
|
1004
|
+
if (wordChars.length < 6)
|
|
1005
|
+
return 'Data too short';
|
|
1006
|
+
let chk = prefixChk(prefix);
|
|
1007
|
+
if (typeof chk === 'string')
|
|
1008
|
+
return chk;
|
|
1009
|
+
const words = [];
|
|
1010
|
+
for (let i = 0; i < wordChars.length; ++i) {
|
|
1011
|
+
const c = wordChars.charAt(i);
|
|
1012
|
+
const v = ALPHABET_MAP[c];
|
|
1013
|
+
if (v === undefined)
|
|
1014
|
+
return 'Unknown character ' + c;
|
|
1015
|
+
chk = polymodStep(chk) ^ v;
|
|
1016
|
+
// not in the checksum?
|
|
1017
|
+
if (i + 6 >= wordChars.length)
|
|
1018
|
+
continue;
|
|
1019
|
+
words.push(v);
|
|
1020
|
+
}
|
|
1021
|
+
if (chk !== ENCODING_CONST)
|
|
1022
|
+
return 'Invalid checksum for ' + str;
|
|
1023
|
+
return { prefix, words };
|
|
1024
|
+
}
|
|
1025
|
+
function decodeUnsafe(str, LIMIT) {
|
|
1026
|
+
const res = __decode(str, LIMIT);
|
|
1027
|
+
if (typeof res === 'object')
|
|
1028
|
+
return res;
|
|
1029
|
+
}
|
|
1030
|
+
function decode(str, LIMIT) {
|
|
1031
|
+
const res = __decode(str, LIMIT);
|
|
1032
|
+
if (typeof res === 'object')
|
|
1033
|
+
return res;
|
|
1034
|
+
throw new Error(res);
|
|
1035
|
+
}
|
|
1036
|
+
return {
|
|
1037
|
+
decodeUnsafe,
|
|
1038
|
+
decode,
|
|
1039
|
+
encode,
|
|
1040
|
+
toWords,
|
|
1041
|
+
fromWordsUnsafe,
|
|
1042
|
+
fromWords,
|
|
1043
|
+
};
|
|
1044
|
+
}
|
|
1045
|
+
dist.bech32 = getLibraryFromEncoding('bech32');
|
|
1046
|
+
dist.bech32m = getLibraryFromEncoding('bech32m');
|
|
1047
|
+
return dist;
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
var distExports = requireDist();
|
|
1051
|
+
|
|
1052
|
+
/**
|
|
1053
|
+
* Utilities for hex, bytes, CSPRNG.
|
|
1054
|
+
* @module
|
|
1055
|
+
*/
|
|
1056
|
+
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
1057
|
+
// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.
|
|
1058
|
+
// node.js versions earlier than v19 don't declare it in global scope.
|
|
1059
|
+
// For node.js, package.json#exports field mapping rewrites import
|
|
1060
|
+
// from `crypto` to `cryptoNode`, which imports native module.
|
|
1061
|
+
// Makes the utils un-importable in browsers without a bundler.
|
|
1062
|
+
// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.
|
|
1063
|
+
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
|
|
1064
|
+
function isBytes(a) {
|
|
1065
|
+
return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');
|
|
1066
|
+
}
|
|
1067
|
+
/** Asserts something is Uint8Array. */
|
|
1068
|
+
function abytes(b, ...lengths) {
|
|
1069
|
+
if (!isBytes(b))
|
|
1070
|
+
throw new Error('Uint8Array expected');
|
|
1071
|
+
if (lengths.length > 0 && !lengths.includes(b.length))
|
|
1072
|
+
throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);
|
|
1073
|
+
}
|
|
1074
|
+
/** Asserts a hash instance has not been destroyed / finished */
|
|
1075
|
+
function aexists(instance, checkFinished = true) {
|
|
1076
|
+
if (instance.destroyed)
|
|
1077
|
+
throw new Error('Hash instance has been destroyed');
|
|
1078
|
+
if (checkFinished && instance.finished)
|
|
1079
|
+
throw new Error('Hash#digest() has already been called');
|
|
1080
|
+
}
|
|
1081
|
+
/** Asserts output is properly-sized byte array */
|
|
1082
|
+
function aoutput(out, instance) {
|
|
1083
|
+
abytes(out);
|
|
1084
|
+
const min = instance.outputLen;
|
|
1085
|
+
if (out.length < min) {
|
|
1086
|
+
throw new Error('digestInto() expects output buffer of length at least ' + min);
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
/** Zeroize a byte array. Warning: JS provides no guarantees. */
|
|
1090
|
+
function clean(...arrays) {
|
|
1091
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
1092
|
+
arrays[i].fill(0);
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
/** Create DataView of an array for easy byte-level manipulation. */
|
|
1096
|
+
function createView(arr) {
|
|
1097
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
1098
|
+
}
|
|
1099
|
+
/** The rotate right (circular right shift) operation for uint32 */
|
|
1100
|
+
function rotr(word, shift) {
|
|
1101
|
+
return (word << (32 - shift)) | (word >>> shift);
|
|
1102
|
+
}
|
|
1103
|
+
/**
|
|
1104
|
+
* Converts string to bytes using UTF8 encoding.
|
|
1105
|
+
* @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
|
|
1106
|
+
*/
|
|
1107
|
+
function utf8ToBytes(str) {
|
|
1108
|
+
if (typeof str !== 'string')
|
|
1109
|
+
throw new Error('string expected');
|
|
1110
|
+
return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809
|
|
1111
|
+
}
|
|
1112
|
+
/**
|
|
1113
|
+
* Normalizes (non-hex) string or Uint8Array to Uint8Array.
|
|
1114
|
+
* Warning: when Uint8Array is passed, it would NOT get copied.
|
|
1115
|
+
* Keep in mind for future mutable operations.
|
|
1116
|
+
*/
|
|
1117
|
+
function toBytes(data) {
|
|
1118
|
+
if (typeof data === 'string')
|
|
1119
|
+
data = utf8ToBytes(data);
|
|
1120
|
+
abytes(data);
|
|
1121
|
+
return data;
|
|
1122
|
+
}
|
|
1123
|
+
/** For runtime check if class implements interface */
|
|
1124
|
+
class Hash {
|
|
1125
|
+
}
|
|
1126
|
+
/** Wraps hash function, creating an interface on top of it */
|
|
1127
|
+
function createHasher(hashCons) {
|
|
1128
|
+
const hashC = (msg) => hashCons().update(toBytes(msg)).digest();
|
|
1129
|
+
const tmp = hashCons();
|
|
1130
|
+
hashC.outputLen = tmp.outputLen;
|
|
1131
|
+
hashC.blockLen = tmp.blockLen;
|
|
1132
|
+
hashC.create = () => hashCons();
|
|
1133
|
+
return hashC;
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
/**
|
|
1137
|
+
* Internal Merkle-Damgard hash utils.
|
|
1138
|
+
* @module
|
|
1139
|
+
*/
|
|
1140
|
+
/** Polyfill for Safari 14. https://caniuse.com/mdn-javascript_builtins_dataview_setbiguint64 */
|
|
1141
|
+
function setBigUint64(view, byteOffset, value, isLE) {
|
|
1142
|
+
if (typeof view.setBigUint64 === 'function')
|
|
1143
|
+
return view.setBigUint64(byteOffset, value, isLE);
|
|
1144
|
+
const _32n = BigInt(32);
|
|
1145
|
+
const _u32_max = BigInt(0xffffffff);
|
|
1146
|
+
const wh = Number((value >> _32n) & _u32_max);
|
|
1147
|
+
const wl = Number(value & _u32_max);
|
|
1148
|
+
const h = isLE ? 4 : 0;
|
|
1149
|
+
const l = isLE ? 0 : 4;
|
|
1150
|
+
view.setUint32(byteOffset + h, wh, isLE);
|
|
1151
|
+
view.setUint32(byteOffset + l, wl, isLE);
|
|
1152
|
+
}
|
|
1153
|
+
/** Choice: a ? b : c */
|
|
1154
|
+
function Chi(a, b, c) {
|
|
1155
|
+
return (a & b) ^ (~a & c);
|
|
1156
|
+
}
|
|
1157
|
+
/** Majority function, true if any two inputs is true. */
|
|
1158
|
+
function Maj(a, b, c) {
|
|
1159
|
+
return (a & b) ^ (a & c) ^ (b & c);
|
|
1160
|
+
}
|
|
1161
|
+
/**
|
|
1162
|
+
* Merkle-Damgard hash construction base class.
|
|
1163
|
+
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
|
|
1164
|
+
*/
|
|
1165
|
+
class HashMD extends Hash {
|
|
1166
|
+
constructor(blockLen, outputLen, padOffset, isLE) {
|
|
1167
|
+
super();
|
|
1168
|
+
this.finished = false;
|
|
1169
|
+
this.length = 0;
|
|
1170
|
+
this.pos = 0;
|
|
1171
|
+
this.destroyed = false;
|
|
1172
|
+
this.blockLen = blockLen;
|
|
1173
|
+
this.outputLen = outputLen;
|
|
1174
|
+
this.padOffset = padOffset;
|
|
1175
|
+
this.isLE = isLE;
|
|
1176
|
+
this.buffer = new Uint8Array(blockLen);
|
|
1177
|
+
this.view = createView(this.buffer);
|
|
1178
|
+
}
|
|
1179
|
+
update(data) {
|
|
1180
|
+
aexists(this);
|
|
1181
|
+
data = toBytes(data);
|
|
1182
|
+
abytes(data);
|
|
1183
|
+
const { view, buffer, blockLen } = this;
|
|
1184
|
+
const len = data.length;
|
|
1185
|
+
for (let pos = 0; pos < len;) {
|
|
1186
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
1187
|
+
// Fast path: we have at least one block in input, cast it to view and process
|
|
1188
|
+
if (take === blockLen) {
|
|
1189
|
+
const dataView = createView(data);
|
|
1190
|
+
for (; blockLen <= len - pos; pos += blockLen)
|
|
1191
|
+
this.process(dataView, pos);
|
|
1192
|
+
continue;
|
|
1193
|
+
}
|
|
1194
|
+
buffer.set(data.subarray(pos, pos + take), this.pos);
|
|
1195
|
+
this.pos += take;
|
|
1196
|
+
pos += take;
|
|
1197
|
+
if (this.pos === blockLen) {
|
|
1198
|
+
this.process(view, 0);
|
|
1199
|
+
this.pos = 0;
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
this.length += data.length;
|
|
1203
|
+
this.roundClean();
|
|
1204
|
+
return this;
|
|
1205
|
+
}
|
|
1206
|
+
digestInto(out) {
|
|
1207
|
+
aexists(this);
|
|
1208
|
+
aoutput(out, this);
|
|
1209
|
+
this.finished = true;
|
|
1210
|
+
// Padding
|
|
1211
|
+
// We can avoid allocation of buffer for padding completely if it
|
|
1212
|
+
// was previously not allocated here. But it won't change performance.
|
|
1213
|
+
const { buffer, view, blockLen, isLE } = this;
|
|
1214
|
+
let { pos } = this;
|
|
1215
|
+
// append the bit '1' to the message
|
|
1216
|
+
buffer[pos++] = 0b10000000;
|
|
1217
|
+
clean(this.buffer.subarray(pos));
|
|
1218
|
+
// we have less than padOffset left in buffer, so we cannot put length in
|
|
1219
|
+
// current block, need process it and pad again
|
|
1220
|
+
if (this.padOffset > blockLen - pos) {
|
|
1221
|
+
this.process(view, 0);
|
|
1222
|
+
pos = 0;
|
|
1223
|
+
}
|
|
1224
|
+
// Pad until full block byte with zeros
|
|
1225
|
+
for (let i = pos; i < blockLen; i++)
|
|
1226
|
+
buffer[i] = 0;
|
|
1227
|
+
// Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that
|
|
1228
|
+
// You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.
|
|
1229
|
+
// So we just write lowest 64 bits of that value.
|
|
1230
|
+
setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);
|
|
1231
|
+
this.process(view, 0);
|
|
1232
|
+
const oview = createView(out);
|
|
1233
|
+
const len = this.outputLen;
|
|
1234
|
+
// NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT
|
|
1235
|
+
if (len % 4)
|
|
1236
|
+
throw new Error('_sha2: outputLen should be aligned to 32bit');
|
|
1237
|
+
const outLen = len / 4;
|
|
1238
|
+
const state = this.get();
|
|
1239
|
+
if (outLen > state.length)
|
|
1240
|
+
throw new Error('_sha2: outputLen bigger than state');
|
|
1241
|
+
for (let i = 0; i < outLen; i++)
|
|
1242
|
+
oview.setUint32(4 * i, state[i], isLE);
|
|
1243
|
+
}
|
|
1244
|
+
digest() {
|
|
1245
|
+
const { buffer, outputLen } = this;
|
|
1246
|
+
this.digestInto(buffer);
|
|
1247
|
+
const res = buffer.slice(0, outputLen);
|
|
1248
|
+
this.destroy();
|
|
1249
|
+
return res;
|
|
1250
|
+
}
|
|
1251
|
+
_cloneInto(to) {
|
|
1252
|
+
to || (to = new this.constructor());
|
|
1253
|
+
to.set(...this.get());
|
|
1254
|
+
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
|
1255
|
+
to.destroyed = destroyed;
|
|
1256
|
+
to.finished = finished;
|
|
1257
|
+
to.length = length;
|
|
1258
|
+
to.pos = pos;
|
|
1259
|
+
if (length % blockLen)
|
|
1260
|
+
to.buffer.set(buffer);
|
|
1261
|
+
return to;
|
|
1262
|
+
}
|
|
1263
|
+
clone() {
|
|
1264
|
+
return this._cloneInto();
|
|
1265
|
+
}
|
|
1266
|
+
}
|
|
1267
|
+
/**
|
|
1268
|
+
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
|
|
1269
|
+
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
|
|
1270
|
+
*/
|
|
1271
|
+
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
|
|
1272
|
+
const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
1273
|
+
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
|
|
1274
|
+
]);
|
|
1275
|
+
|
|
1276
|
+
/**
|
|
1277
|
+
* SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
|
|
1278
|
+
* SHA256 is the fastest hash implementable in JS, even faster than Blake3.
|
|
1279
|
+
* Check out [RFC 4634](https://datatracker.ietf.org/doc/html/rfc4634) and
|
|
1280
|
+
* [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
|
|
1281
|
+
* @module
|
|
1282
|
+
*/
|
|
1283
|
+
/**
|
|
1284
|
+
* Round constants:
|
|
1285
|
+
* First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
|
|
1286
|
+
*/
|
|
1287
|
+
// prettier-ignore
|
|
1288
|
+
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
1289
|
+
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
|
|
1290
|
+
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
|
|
1291
|
+
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
|
|
1292
|
+
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
|
|
1293
|
+
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
|
|
1294
|
+
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
|
|
1295
|
+
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
|
|
1296
|
+
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
|
|
1297
|
+
]);
|
|
1298
|
+
/** Reusable temporary buffer. "W" comes straight from spec. */
|
|
1299
|
+
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
1300
|
+
class SHA256 extends HashMD {
|
|
1301
|
+
constructor(outputLen = 32) {
|
|
1302
|
+
super(64, outputLen, 8, false);
|
|
1303
|
+
// We cannot use array here since array allows indexing by variable
|
|
1304
|
+
// which means optimizer/compiler cannot use registers.
|
|
1305
|
+
this.A = SHA256_IV[0] | 0;
|
|
1306
|
+
this.B = SHA256_IV[1] | 0;
|
|
1307
|
+
this.C = SHA256_IV[2] | 0;
|
|
1308
|
+
this.D = SHA256_IV[3] | 0;
|
|
1309
|
+
this.E = SHA256_IV[4] | 0;
|
|
1310
|
+
this.F = SHA256_IV[5] | 0;
|
|
1311
|
+
this.G = SHA256_IV[6] | 0;
|
|
1312
|
+
this.H = SHA256_IV[7] | 0;
|
|
1313
|
+
}
|
|
1314
|
+
get() {
|
|
1315
|
+
const { A, B, C, D, E, F, G, H } = this;
|
|
1316
|
+
return [A, B, C, D, E, F, G, H];
|
|
1317
|
+
}
|
|
1318
|
+
// prettier-ignore
|
|
1319
|
+
set(A, B, C, D, E, F, G, H) {
|
|
1320
|
+
this.A = A | 0;
|
|
1321
|
+
this.B = B | 0;
|
|
1322
|
+
this.C = C | 0;
|
|
1323
|
+
this.D = D | 0;
|
|
1324
|
+
this.E = E | 0;
|
|
1325
|
+
this.F = F | 0;
|
|
1326
|
+
this.G = G | 0;
|
|
1327
|
+
this.H = H | 0;
|
|
1328
|
+
}
|
|
1329
|
+
process(view, offset) {
|
|
1330
|
+
// Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array
|
|
1331
|
+
for (let i = 0; i < 16; i++, offset += 4)
|
|
1332
|
+
SHA256_W[i] = view.getUint32(offset, false);
|
|
1333
|
+
for (let i = 16; i < 64; i++) {
|
|
1334
|
+
const W15 = SHA256_W[i - 15];
|
|
1335
|
+
const W2 = SHA256_W[i - 2];
|
|
1336
|
+
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);
|
|
1337
|
+
const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);
|
|
1338
|
+
SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;
|
|
1339
|
+
}
|
|
1340
|
+
// Compression function main loop, 64 rounds
|
|
1341
|
+
let { A, B, C, D, E, F, G, H } = this;
|
|
1342
|
+
for (let i = 0; i < 64; i++) {
|
|
1343
|
+
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
1344
|
+
const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;
|
|
1345
|
+
const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);
|
|
1346
|
+
const T2 = (sigma0 + Maj(A, B, C)) | 0;
|
|
1347
|
+
H = G;
|
|
1348
|
+
G = F;
|
|
1349
|
+
F = E;
|
|
1350
|
+
E = (D + T1) | 0;
|
|
1351
|
+
D = C;
|
|
1352
|
+
C = B;
|
|
1353
|
+
B = A;
|
|
1354
|
+
A = (T1 + T2) | 0;
|
|
1355
|
+
}
|
|
1356
|
+
// Add the compressed chunk to the current hash value
|
|
1357
|
+
A = (A + this.A) | 0;
|
|
1358
|
+
B = (B + this.B) | 0;
|
|
1359
|
+
C = (C + this.C) | 0;
|
|
1360
|
+
D = (D + this.D) | 0;
|
|
1361
|
+
E = (E + this.E) | 0;
|
|
1362
|
+
F = (F + this.F) | 0;
|
|
1363
|
+
G = (G + this.G) | 0;
|
|
1364
|
+
H = (H + this.H) | 0;
|
|
1365
|
+
this.set(A, B, C, D, E, F, G, H);
|
|
1366
|
+
}
|
|
1367
|
+
roundClean() {
|
|
1368
|
+
clean(SHA256_W);
|
|
1369
|
+
}
|
|
1370
|
+
destroy() {
|
|
1371
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
1372
|
+
clean(this.buffer);
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
/**
|
|
1376
|
+
* SHA2-256 hash function from RFC 4634.
|
|
1377
|
+
*
|
|
1378
|
+
* It is the fastest JS hash, even faster than Blake3.
|
|
1379
|
+
* To break sha256 using birthday attack, attackers need to try 2^128 hashes.
|
|
1380
|
+
* BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
|
|
1381
|
+
*/
|
|
1382
|
+
const sha256$1 = /* @__PURE__ */ createHasher(() => new SHA256());
|
|
1383
|
+
|
|
1384
|
+
/**
|
|
1385
|
+
* SHA2-256 a.k.a. sha256. In JS, it is the fastest hash, even faster than Blake3.
|
|
1386
|
+
*
|
|
1387
|
+
* To break sha256 using birthday attack, attackers need to try 2^128 hashes.
|
|
1388
|
+
* BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
|
|
1389
|
+
*
|
|
1390
|
+
* Check out [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
|
|
1391
|
+
* @module
|
|
1392
|
+
* @deprecated
|
|
1393
|
+
*/
|
|
1394
|
+
/** @deprecated Use import from `noble/hashes/sha2` module */
|
|
1395
|
+
const sha256 = sha256$1;
|
|
1396
|
+
|
|
1397
|
+
function bs58checkBase (checksumFn) {
|
|
1398
|
+
// Encode a buffer as a base58-check encoded string
|
|
1399
|
+
function encode(payload) {
|
|
1400
|
+
var payloadU8 = Uint8Array.from(payload);
|
|
1401
|
+
var checksum = checksumFn(payloadU8);
|
|
1402
|
+
var length = payloadU8.length + 4;
|
|
1403
|
+
var both = new Uint8Array(length);
|
|
1404
|
+
both.set(payloadU8, 0);
|
|
1405
|
+
both.set(checksum.subarray(0, 4), payloadU8.length);
|
|
1406
|
+
return base58.encode(both);
|
|
1407
|
+
}
|
|
1408
|
+
function decodeRaw(buffer) {
|
|
1409
|
+
var payload = buffer.slice(0, -4);
|
|
1410
|
+
var checksum = buffer.slice(-4);
|
|
1411
|
+
var newChecksum = checksumFn(payload);
|
|
1412
|
+
// eslint-disable-next-line
|
|
1413
|
+
if (checksum[0] ^ newChecksum[0] |
|
|
1414
|
+
checksum[1] ^ newChecksum[1] |
|
|
1415
|
+
checksum[2] ^ newChecksum[2] |
|
|
1416
|
+
checksum[3] ^ newChecksum[3])
|
|
1417
|
+
return;
|
|
1418
|
+
return payload;
|
|
1419
|
+
}
|
|
1420
|
+
// Decode a base58-check encoded string to a buffer, no result if checksum is wrong
|
|
1421
|
+
function decodeUnsafe(str) {
|
|
1422
|
+
var buffer = base58.decodeUnsafe(str);
|
|
1423
|
+
if (buffer == null)
|
|
1424
|
+
return;
|
|
1425
|
+
return decodeRaw(buffer);
|
|
1426
|
+
}
|
|
1427
|
+
function decode(str) {
|
|
1428
|
+
var buffer = base58.decode(str);
|
|
1429
|
+
var payload = decodeRaw(buffer);
|
|
1430
|
+
if (payload == null)
|
|
1431
|
+
throw new Error('Invalid checksum');
|
|
1432
|
+
return payload;
|
|
1433
|
+
}
|
|
1434
|
+
return {
|
|
1435
|
+
encode: encode,
|
|
1436
|
+
decode: decode,
|
|
1437
|
+
decodeUnsafe: decodeUnsafe
|
|
1438
|
+
};
|
|
1439
|
+
}
|
|
1440
|
+
|
|
1441
|
+
// SHA256(SHA256(buffer))
|
|
1442
|
+
function sha256x2(buffer) {
|
|
1443
|
+
return sha256(sha256(buffer));
|
|
1444
|
+
}
|
|
1445
|
+
var bs58check = bs58checkBase(sha256x2);
|
|
1446
|
+
|
|
1447
|
+
function resolveAddressInput(address) {
|
|
1448
|
+
if (typeof address === 'string') {
|
|
1449
|
+
return String(address).trim();
|
|
1450
|
+
}
|
|
1451
|
+
if (address && typeof address.address === 'string') {
|
|
1452
|
+
return String(address.address).trim();
|
|
1453
|
+
}
|
|
1454
|
+
throw new Error('Address must be a string or an object with an address field');
|
|
1455
|
+
}
|
|
1456
|
+
|
|
1457
|
+
const LEGACY_MAINNET_PREFIX = 53;
|
|
1458
|
+
const LEGACY_TESTNET_PREFIX = 127;
|
|
1459
|
+
const PQ_MAINNET_HRP = 'nq';
|
|
1460
|
+
const PQ_TESTNET_HRP = 'tnq';
|
|
1461
|
+
function inferNetworkFromAddress(address) {
|
|
1462
|
+
const normalized = resolveAddressInput(address).toLowerCase();
|
|
1463
|
+
if (normalized.startsWith(PQ_MAINNET_HRP + '1'))
|
|
1464
|
+
return 'xna-pq';
|
|
1465
|
+
if (normalized.startsWith(PQ_TESTNET_HRP + '1'))
|
|
1466
|
+
return 'xna-pq-test';
|
|
1467
|
+
if (normalized.startsWith('n'))
|
|
1468
|
+
return 'xna';
|
|
1469
|
+
if (normalized.startsWith('t'))
|
|
1470
|
+
return 'xna-test';
|
|
1471
|
+
throw new Error(`Unsupported Neurai address: ${address}`);
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
function decodeAddress(address) {
|
|
1475
|
+
const normalized = resolveAddressInput(address);
|
|
1476
|
+
const lowered = normalized.toLowerCase();
|
|
1477
|
+
if (!normalized)
|
|
1478
|
+
throw new Error('Address is required');
|
|
1479
|
+
if (lowered.startsWith(PQ_MAINNET_HRP + '1') || lowered.startsWith(PQ_TESTNET_HRP + '1')) {
|
|
1480
|
+
const decoded = distExports.bech32m.decode(normalized);
|
|
1481
|
+
const version = decoded.words[0];
|
|
1482
|
+
const program = Uint8Array.from(distExports.bech32m.fromWords(decoded.words.slice(1)));
|
|
1483
|
+
if (version !== 1 || program.length !== 32) {
|
|
1484
|
+
throw new Error(`Unsupported AuthScript address program for ${address}`);
|
|
1485
|
+
}
|
|
1486
|
+
const network = lowered.startsWith(PQ_TESTNET_HRP + '1') ? 'xna-pq-test' : 'xna-pq';
|
|
1487
|
+
return { address: normalized, type: 'authscript', network, program, commitment: program };
|
|
1488
|
+
}
|
|
1489
|
+
const payload = Uint8Array.from(bs58check.decode(normalized));
|
|
1490
|
+
if (payload.length !== 21) {
|
|
1491
|
+
throw new Error(`Unsupported legacy address payload length for ${address}`);
|
|
1492
|
+
}
|
|
1493
|
+
const prefix = payload[0];
|
|
1494
|
+
if (prefix !== LEGACY_MAINNET_PREFIX && prefix !== LEGACY_TESTNET_PREFIX) {
|
|
1495
|
+
throw new Error(`Unsupported legacy address prefix ${prefix} for ${address}`);
|
|
1496
|
+
}
|
|
1497
|
+
return {
|
|
1498
|
+
address: normalized,
|
|
1499
|
+
type: 'p2pkh',
|
|
1500
|
+
network: inferNetworkFromAddress(normalized),
|
|
1501
|
+
program: payload.slice(1),
|
|
1502
|
+
hash: payload.slice(1)
|
|
1503
|
+
};
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1506
|
+
/**
|
|
1507
|
+
* Address helpers. Wraps `decodeAddress` from
|
|
1508
|
+
* `@neuraiproject/neurai-create-transaction` to produce the exact
|
|
1509
|
+
* scriptPubKey bytes a covenant needs to hardcode. The actual
|
|
1510
|
+
* scriptPubKey encoders live in `./standard/*`; this module delegates.
|
|
1511
|
+
*
|
|
1512
|
+
* Two destination types are supported for the payment output (output[0]):
|
|
1513
|
+
* - Legacy P2PKH (base58check)
|
|
1514
|
+
* - AuthScript witness v1 (bech32m)
|
|
1515
|
+
*/
|
|
1516
|
+
/**
|
|
1517
|
+
* Resolve any accepted seller address string into its scriptPubKey.
|
|
1518
|
+
* The returned bytes are what the covenant will hardcode and later verify
|
|
1519
|
+
* via `OP_OUTPUTSCRIPT == <bytes>`.
|
|
1520
|
+
*/
|
|
1521
|
+
function encodeSellerScriptPubKey(address) {
|
|
1522
|
+
const decoded = decodeAddress(address);
|
|
1523
|
+
if (decoded.type === 'p2pkh') {
|
|
1524
|
+
const hash = Uint8Array.from(decoded.hash);
|
|
1525
|
+
return {
|
|
1526
|
+
kind: 'p2pkh',
|
|
1527
|
+
bytes: encodeP2PKHScriptPubKey(hash),
|
|
1528
|
+
hash
|
|
1529
|
+
};
|
|
1530
|
+
}
|
|
1531
|
+
if (decoded.type === 'authscript') {
|
|
1532
|
+
const program = Uint8Array.from(decoded.program);
|
|
1533
|
+
return {
|
|
1534
|
+
kind: 'authscript',
|
|
1535
|
+
bytes: encodeAuthScriptScriptPubKey(program),
|
|
1536
|
+
hash: program
|
|
1537
|
+
};
|
|
1538
|
+
}
|
|
1539
|
+
throw new Error(`Unsupported seller address type for "${address}"`);
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
/**
|
|
1543
|
+
* Partial-Fill Sell Order covenant script.
|
|
1544
|
+
*
|
|
1545
|
+
* The covenant has two branches selected by the top of the unlock stack:
|
|
1546
|
+
*
|
|
1547
|
+
* OP_IF (unlock pushed 1) → Cancel: seller signs, recovers remainder.
|
|
1548
|
+
* OP_ELSE (unlock pushed 0) → Public partial fill: buyer provides the
|
|
1549
|
+
* fill amount `N` and the tx layout is
|
|
1550
|
+
* validated byte by byte.
|
|
1551
|
+
*
|
|
1552
|
+
* The partial-fill branch enforces a fixed output layout so that the script
|
|
1553
|
+
* stays compact and parseable:
|
|
1554
|
+
*
|
|
1555
|
+
* output[0] = XNA payment to seller (value >= N * unitPriceSats)
|
|
1556
|
+
* output[1] = asset to buyer (tokenId, amount == N)
|
|
1557
|
+
* output[2] = covenant remainder (same scriptPubKey, amount == in - N)
|
|
1558
|
+
* output[3+] = optional buyer change (not constrained by the covenant)
|
|
1559
|
+
*
|
|
1560
|
+
* The remainder UTXO reuses the spent scriptPubKey via
|
|
1561
|
+
* `OP_OUTPUTSCRIPT == OP_TXFIELD 0x03`, so the covenant is self-replicating
|
|
1562
|
+
* without hardcoding its own hash.
|
|
1563
|
+
*
|
|
1564
|
+
* The cancel branch uses classical ECDSA (`OP_HASH160 + OP_CHECKSIG`) and
|
|
1565
|
+
* commits to a 20-byte PKH. As a consequence this variant only accepts
|
|
1566
|
+
* legacy P2PKH addresses as the seller destination. For AuthScript bech32m
|
|
1567
|
+
* destinations and post-quantum signing, use `buildPartialFillScriptPQ`.
|
|
1568
|
+
*/
|
|
1569
|
+
const ASSET_NAME_MAX$1 = 32;
|
|
1570
|
+
function decodeSellerAddress(sellerAddress) {
|
|
1571
|
+
if (typeof sellerAddress !== 'string' || sellerAddress.length === 0) {
|
|
1572
|
+
throw new Error('sellerAddress is required');
|
|
1573
|
+
}
|
|
1574
|
+
const decoded = decodeAddress(sellerAddress);
|
|
1575
|
+
if (decoded.type !== 'p2pkh') {
|
|
1576
|
+
throw new Error(`sellerAddress must be a legacy P2PKH address (the legacy partial-fill covenant uses OP_HASH160 + OP_CHECKSIG); ` +
|
|
1577
|
+
`got ${decoded.type}. Use buildPartialFillScriptPQ for AuthScript destinations.`);
|
|
1578
|
+
}
|
|
1579
|
+
const pkh = Uint8Array.from(decoded.hash);
|
|
1580
|
+
if (pkh.length !== 20) {
|
|
1581
|
+
throw new Error(`decoded sellerAddress produced a ${pkh.length}-byte hash, expected 20`);
|
|
1582
|
+
}
|
|
1583
|
+
return pkh;
|
|
1584
|
+
}
|
|
1585
|
+
function assertTokenId$1(tokenId) {
|
|
1586
|
+
if (typeof tokenId !== 'string' || tokenId.length === 0) {
|
|
1587
|
+
throw new Error('tokenId is required');
|
|
1588
|
+
}
|
|
1589
|
+
if (!/^[A-Z0-9._]+$/.test(tokenId)) {
|
|
1590
|
+
throw new Error(`tokenId "${tokenId}" is not a valid Neurai asset name`);
|
|
1591
|
+
}
|
|
1592
|
+
if (tokenId.length > ASSET_NAME_MAX$1) {
|
|
1593
|
+
throw new Error(`tokenId exceeds ${ASSET_NAME_MAX$1} bytes`);
|
|
1594
|
+
}
|
|
1595
|
+
}
|
|
1596
|
+
function assertPrice$1(priceSats) {
|
|
1597
|
+
if (typeof priceSats !== 'bigint') {
|
|
1598
|
+
throw new Error('unitPriceSats must be a bigint (satoshis per indivisible unit)');
|
|
1599
|
+
}
|
|
1600
|
+
if (priceSats <= 0n) {
|
|
1601
|
+
throw new Error('unitPriceSats must be > 0');
|
|
1602
|
+
}
|
|
1603
|
+
// 8-byte signed int ceiling: values beyond this cannot be produced by OP_MUL
|
|
1604
|
+
// inside the covenant without overflow (CScriptNum is int64).
|
|
1605
|
+
if (priceSats > 0x7fffffffffffffffn) {
|
|
1606
|
+
throw new Error('unitPriceSats exceeds int64 range');
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
/**
|
|
1610
|
+
* Build the `scriptPubKey` of a Partial-Fill Sell Order covenant UTXO.
|
|
1611
|
+
* Returns raw bytes; wrap with `bytesToHex` for wire format.
|
|
1612
|
+
*/
|
|
1613
|
+
function buildPartialFillScript(params) {
|
|
1614
|
+
const { sellerAddress, tokenId, unitPriceSats } = params;
|
|
1615
|
+
const sellerPubKeyHash = decodeSellerAddress(sellerAddress);
|
|
1616
|
+
assertTokenId$1(tokenId);
|
|
1617
|
+
assertPrice$1(unitPriceSats);
|
|
1618
|
+
const sellerScriptPubKey = encodeP2PKHScriptPubKey(sellerPubKeyHash);
|
|
1619
|
+
const tokenIdBytes = new TextEncoder().encode(tokenId);
|
|
1620
|
+
const b = new ScriptBuilder();
|
|
1621
|
+
// ───────── Cancel branch (IF) ─────────
|
|
1622
|
+
// scriptSig expected: <sig> <pubkey> OP_1
|
|
1623
|
+
b.op(OP_IF)
|
|
1624
|
+
.op(OP_DUP, OP_HASH160)
|
|
1625
|
+
.pushBytes(sellerPubKeyHash)
|
|
1626
|
+
.op(OP_EQUALVERIFY, OP_CHECKSIG)
|
|
1627
|
+
.op(OP_ELSE);
|
|
1628
|
+
// ───────── Partial-fill branch (ELSE) ─────────
|
|
1629
|
+
// scriptSig expected: <N> OP_0
|
|
1630
|
+
//
|
|
1631
|
+
// Stack invariant entering the ELSE branch: [ N ]
|
|
1632
|
+
// 1. Payment value to seller (output 0)
|
|
1633
|
+
// require outputValue(0) >= N * unitPriceSats
|
|
1634
|
+
b.op(OP_DUP) // [ N, N ]
|
|
1635
|
+
.pushInt(unitPriceSats) // [ N, N, price ]
|
|
1636
|
+
.op(OP_MUL) // [ N, N*price ]
|
|
1637
|
+
.pushInt(0) // [ N, N*price, 0 ]
|
|
1638
|
+
.op(OP_OUTPUTVALUE) // [ N, N*price, value ]
|
|
1639
|
+
.op(OP_SWAP) // [ N, value, N*price ]
|
|
1640
|
+
.op(OP_GREATERTHANOREQUAL)
|
|
1641
|
+
.op(OP_VERIFY); // [ N ]
|
|
1642
|
+
// 2. Payment scriptPubKey must equal Alice's (output 0)
|
|
1643
|
+
b.pushInt(0)
|
|
1644
|
+
.op(OP_OUTPUTSCRIPT) // [ N, scriptPubKey_out0 ]
|
|
1645
|
+
.pushBytes(sellerScriptPubKey)
|
|
1646
|
+
.op(OP_EQUALVERIFY); // [ N ]
|
|
1647
|
+
// 3. Asset delivered to buyer (output 1): amount == N
|
|
1648
|
+
b.op(OP_DUP) // [ N, N ]
|
|
1649
|
+
.pushInt(1) // [ N, N, 1 ]
|
|
1650
|
+
.pushInt(ASSETFIELD_AMOUNT)
|
|
1651
|
+
.op(OP_OUTPUTASSETFIELD) // [ N, N, amount_out1 ]
|
|
1652
|
+
.op(OP_EQUALVERIFY); // [ N ]
|
|
1653
|
+
// 4. Asset delivered to buyer (output 1): name == tokenId
|
|
1654
|
+
b.pushInt(1)
|
|
1655
|
+
.pushInt(ASSETFIELD_NAME)
|
|
1656
|
+
.op(OP_OUTPUTASSETFIELD) // [ N, name_out1 ]
|
|
1657
|
+
.pushBytes(tokenIdBytes)
|
|
1658
|
+
.op(OP_EQUALVERIFY); // [ N ]
|
|
1659
|
+
// 5. Remainder covenant continuity (output 2): same scriptPubKey as spent
|
|
1660
|
+
b.pushInt(2)
|
|
1661
|
+
.op(OP_OUTPUTSCRIPT) // [ N, spk_out2 ]
|
|
1662
|
+
.pushInt(TXFIELD_SCRIPTPUBKEY)
|
|
1663
|
+
.op(OP_TXFIELD) // [ N, spk_out2, spent_spk ]
|
|
1664
|
+
.op(OP_EQUALVERIFY); // [ N ]
|
|
1665
|
+
// 6. Remainder output: same tokenId
|
|
1666
|
+
b.pushInt(2)
|
|
1667
|
+
.pushInt(ASSETFIELD_NAME)
|
|
1668
|
+
.op(OP_OUTPUTASSETFIELD) // [ N, name_out2 ]
|
|
1669
|
+
.pushBytes(tokenIdBytes)
|
|
1670
|
+
.op(OP_EQUALVERIFY); // [ N ]
|
|
1671
|
+
// 7. Remainder output: amount == inputAssetAmount - N
|
|
1672
|
+
b.pushInt(2)
|
|
1673
|
+
.pushInt(ASSETFIELD_AMOUNT)
|
|
1674
|
+
.op(OP_OUTPUTASSETFIELD) // [ N, rem_amount ]
|
|
1675
|
+
.op(OP_OVER) // [ N, rem_amount, N ] -- copy N under top
|
|
1676
|
+
.pushInt(0) // [ N, rem_amount, N, 0 ]
|
|
1677
|
+
.pushInt(ASSETFIELD_AMOUNT)
|
|
1678
|
+
.op(OP_INPUTASSETFIELD) // [ N, rem_amount, N, in_amount ]
|
|
1679
|
+
.op(OP_SWAP) // [ N, rem_amount, in_amount, N ]
|
|
1680
|
+
.op(OP_SUB) // [ N, rem_amount, in_amount - N ]
|
|
1681
|
+
.op(OP_EQUALVERIFY); // [ N ]
|
|
1682
|
+
// Drop N, leave TRUE on the stack so the ELSE branch evaluates as success.
|
|
1683
|
+
b.op(OP_DROP).pushInt(1);
|
|
1684
|
+
b.op(OP_ENDIF);
|
|
1685
|
+
return b.build();
|
|
1686
|
+
}
|
|
1687
|
+
/** Hex convenience wrapper for `buildPartialFillScript`. */
|
|
1688
|
+
function buildPartialFillScriptHex(params) {
|
|
1689
|
+
return bytesToHex(buildPartialFillScript(params));
|
|
1690
|
+
}
|
|
1691
|
+
|
|
1692
|
+
/**
|
|
1693
|
+
* PQ (post-quantum) variant of the Partial-Fill Sell Order covenant.
|
|
1694
|
+
*
|
|
1695
|
+
* Identical partial-fill branch to the legacy covenant, but the **cancel**
|
|
1696
|
+
* branch accepts an ML-DSA-44 signature instead of an ECDSA one. This
|
|
1697
|
+
* requires:
|
|
1698
|
+
* - `SCRIPT_VERIFY_CHECKSIGFROMSTACK` (for OP_CSFS) active
|
|
1699
|
+
* - `SCRIPT_VERIFY_TXHASH` (for OP_TXHASH) active
|
|
1700
|
+
* - NIP-18 (`MAX_PQ_SCRIPT_ELEMENT_SIZE = 3072`) active, so the ~2.4 KB
|
|
1701
|
+
* signature and ~1.3 KB pubkey can be pushed to the script stack
|
|
1702
|
+
*
|
|
1703
|
+
* All three are active on DePIN-Test testnet.
|
|
1704
|
+
*
|
|
1705
|
+
* Cancel-branch flow (scriptSig pushes `<sig> <pubkey> OP_1`):
|
|
1706
|
+
*
|
|
1707
|
+
* 1. OP_DUP OP_SHA256 <commitment> OP_EQUALVERIFY → pubkey matches
|
|
1708
|
+
* 2. <selector> OP_TXHASH → message = H(tx)
|
|
1709
|
+
* 3. OP_SWAP OP_CHECKSIGFROMSTACK → CSFS verifies sig
|
|
1710
|
+
*
|
|
1711
|
+
* The message that gets signed is **SHA256(OP_TXHASH(selector))** — CSFS
|
|
1712
|
+
* single-SHA256s its message argument before verification, and OP_TXHASH
|
|
1713
|
+
* produces its own 32-byte hash, so the seller computes:
|
|
1714
|
+
* `sign(pqSeckey, SHA256(doubleSHA256(selected_tx_fields)))`
|
|
1715
|
+
*/
|
|
1716
|
+
const ASSET_NAME_MAX = 32;
|
|
1717
|
+
const DEFAULT_PQ_TXHASH_SELECTOR = 0xff;
|
|
1718
|
+
function assertCommitment(commitment) {
|
|
1719
|
+
if (!(commitment instanceof Uint8Array) || commitment.length !== 32) {
|
|
1720
|
+
throw new Error('pubKeyCommitment must be a 32-byte Uint8Array (SHA256 of pubKey)');
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
function assertTokenId(tokenId) {
|
|
1724
|
+
if (typeof tokenId !== 'string' || tokenId.length === 0) {
|
|
1725
|
+
throw new Error('tokenId is required');
|
|
1726
|
+
}
|
|
1727
|
+
if (!/^[A-Z0-9._]+$/.test(tokenId)) {
|
|
1728
|
+
throw new Error(`tokenId "${tokenId}" is not a valid Neurai asset name`);
|
|
1729
|
+
}
|
|
1730
|
+
if (tokenId.length > ASSET_NAME_MAX) {
|
|
1731
|
+
throw new Error(`tokenId exceeds ${ASSET_NAME_MAX} bytes`);
|
|
1732
|
+
}
|
|
1733
|
+
}
|
|
1734
|
+
function assertPrice(priceSats) {
|
|
1735
|
+
if (typeof priceSats !== 'bigint') {
|
|
1736
|
+
throw new Error('unitPriceSats must be a bigint');
|
|
1737
|
+
}
|
|
1738
|
+
if (priceSats <= 0n) {
|
|
1739
|
+
throw new Error('unitPriceSats must be > 0');
|
|
1740
|
+
}
|
|
1741
|
+
if (priceSats > 0x7fffffffffffffffn) {
|
|
1742
|
+
throw new Error('unitPriceSats exceeds int64 range');
|
|
1743
|
+
}
|
|
1744
|
+
}
|
|
1745
|
+
function assertSelector(selector) {
|
|
1746
|
+
if (!Number.isInteger(selector) || selector < 0 || selector > 0xff) {
|
|
1747
|
+
throw new Error('txHashSelector must be a single byte (0x00..0xff)');
|
|
1748
|
+
}
|
|
1749
|
+
if (selector === 0) {
|
|
1750
|
+
throw new Error('txHashSelector 0x00 is rejected by OP_TXHASH');
|
|
1751
|
+
}
|
|
1752
|
+
}
|
|
1753
|
+
/**
|
|
1754
|
+
* Build the scriptPubKey of a PQ Partial-Fill Sell Order covenant UTXO.
|
|
1755
|
+
*/
|
|
1756
|
+
function buildPartialFillScriptPQ(params) {
|
|
1757
|
+
const { paymentAddress, pubKeyCommitment, tokenId, unitPriceSats, txHashSelector = DEFAULT_PQ_TXHASH_SELECTOR } = params;
|
|
1758
|
+
assertCommitment(pubKeyCommitment);
|
|
1759
|
+
assertTokenId(tokenId);
|
|
1760
|
+
assertPrice(unitPriceSats);
|
|
1761
|
+
assertSelector(txHashSelector);
|
|
1762
|
+
const payment = encodeSellerScriptPubKey(paymentAddress);
|
|
1763
|
+
const tokenIdBytes = new TextEncoder().encode(tokenId);
|
|
1764
|
+
const b = new ScriptBuilder();
|
|
1765
|
+
// ───────── Cancel branch (PQ via OP_CHECKSIGFROMSTACK) ─────────
|
|
1766
|
+
// scriptSig expected: <sigPQ> <pubKeyPQ> OP_1
|
|
1767
|
+
// After OP_IF consumes the flag: [ sig, pubKey ]
|
|
1768
|
+
b.op(OP_IF)
|
|
1769
|
+
.op(OP_DUP) // [ sig, pubKey, pubKey ]
|
|
1770
|
+
.op(OP_SHA256) // [ sig, pubKey, H(pubKey) ]
|
|
1771
|
+
.pushBytes(pubKeyCommitment) // [ sig, pubKey, H(pubKey), commitment ]
|
|
1772
|
+
.op(OP_EQUALVERIFY) // [ sig, pubKey ]
|
|
1773
|
+
.pushInt(txHashSelector) // [ sig, pubKey, selector ]
|
|
1774
|
+
.op(OP_TXHASH) // [ sig, pubKey, txHash ]
|
|
1775
|
+
.op(OP_SWAP) // [ sig, txHash, pubKey ]
|
|
1776
|
+
.op(OP_CHECKSIGFROMSTACK) // [ 1 | 0 ]
|
|
1777
|
+
.op(OP_ELSE);
|
|
1778
|
+
// ───────── Partial-fill branch (identical layout to legacy) ─────────
|
|
1779
|
+
// scriptSig expected: <N> OP_0
|
|
1780
|
+
// Stack entering ELSE: [ N ]
|
|
1781
|
+
// 1. Payment value (output 0) >= N * unitPriceSats
|
|
1782
|
+
b.op(OP_DUP)
|
|
1783
|
+
.pushInt(unitPriceSats)
|
|
1784
|
+
.op(OP_MUL)
|
|
1785
|
+
.pushInt(0)
|
|
1786
|
+
.op(OP_OUTPUTVALUE)
|
|
1787
|
+
.op(OP_SWAP)
|
|
1788
|
+
.op(OP_GREATERTHANOREQUAL)
|
|
1789
|
+
.op(OP_VERIFY);
|
|
1790
|
+
// 2. Payment scriptPubKey (output 0) == payment.bytes
|
|
1791
|
+
b.pushInt(0)
|
|
1792
|
+
.op(OP_OUTPUTSCRIPT)
|
|
1793
|
+
.pushBytes(payment.bytes)
|
|
1794
|
+
.op(OP_EQUALVERIFY);
|
|
1795
|
+
// 3. Asset to buyer (output 1) amount == N
|
|
1796
|
+
b.op(OP_DUP)
|
|
1797
|
+
.pushInt(1)
|
|
1798
|
+
.pushInt(ASSETFIELD_AMOUNT)
|
|
1799
|
+
.op(OP_OUTPUTASSETFIELD)
|
|
1800
|
+
.op(OP_EQUALVERIFY);
|
|
1801
|
+
// 4. Asset to buyer (output 1) name == tokenId
|
|
1802
|
+
b.pushInt(1)
|
|
1803
|
+
.pushInt(ASSETFIELD_NAME)
|
|
1804
|
+
.op(OP_OUTPUTASSETFIELD)
|
|
1805
|
+
.pushBytes(tokenIdBytes)
|
|
1806
|
+
.op(OP_EQUALVERIFY);
|
|
1807
|
+
// 5. Remainder continuity (output 2) — same scriptPubKey as spent
|
|
1808
|
+
b.pushInt(2)
|
|
1809
|
+
.op(OP_OUTPUTSCRIPT)
|
|
1810
|
+
.pushInt(TXFIELD_SCRIPTPUBKEY)
|
|
1811
|
+
.op(OP_TXFIELD)
|
|
1812
|
+
.op(OP_EQUALVERIFY);
|
|
1813
|
+
// 6. Remainder tokenId
|
|
1814
|
+
b.pushInt(2)
|
|
1815
|
+
.pushInt(ASSETFIELD_NAME)
|
|
1816
|
+
.op(OP_OUTPUTASSETFIELD)
|
|
1817
|
+
.pushBytes(tokenIdBytes)
|
|
1818
|
+
.op(OP_EQUALVERIFY);
|
|
1819
|
+
// 7. Remainder amount == inputAssetAmount - N
|
|
1820
|
+
b.pushInt(2)
|
|
1821
|
+
.pushInt(ASSETFIELD_AMOUNT)
|
|
1822
|
+
.op(OP_OUTPUTASSETFIELD)
|
|
1823
|
+
.op(OP_OVER)
|
|
1824
|
+
.pushInt(0)
|
|
1825
|
+
.pushInt(ASSETFIELD_AMOUNT)
|
|
1826
|
+
.op(OP_INPUTASSETFIELD)
|
|
1827
|
+
.op(OP_SWAP)
|
|
1828
|
+
.op(OP_SUB)
|
|
1829
|
+
.op(OP_EQUALVERIFY);
|
|
1830
|
+
b.op(OP_DROP).pushInt(1);
|
|
1831
|
+
b.op(OP_ENDIF);
|
|
1832
|
+
return b.build();
|
|
1833
|
+
}
|
|
1834
|
+
function buildPartialFillScriptPQHex(params) {
|
|
1835
|
+
return bytesToHex(buildPartialFillScriptPQ(params));
|
|
1836
|
+
}
|
|
1837
|
+
|
|
1838
|
+
/**
|
|
1839
|
+
* scriptSig builders for the Partial-Fill Sell Order covenant.
|
|
1840
|
+
*
|
|
1841
|
+
* These return the raw scriptSig bytes that unlock the covenant UTXO. The
|
|
1842
|
+
* surrounding transaction (inputs, outputs, fees, signatures on the buyer's
|
|
1843
|
+
* own inputs, etc.) is the caller's responsibility — stitch them together
|
|
1844
|
+
* with `@neuraiproject/neurai-create-transaction`.
|
|
1845
|
+
*/
|
|
1846
|
+
/**
|
|
1847
|
+
* Unlock the covenant via the public partial-fill branch.
|
|
1848
|
+
*
|
|
1849
|
+
* Layout on the stack before OP_IF executes (top → bottom):
|
|
1850
|
+
* 0 ← selects the OP_ELSE (fill) branch
|
|
1851
|
+
* N ← amount of asset the buyer is taking from this order
|
|
1852
|
+
*
|
|
1853
|
+
* so the scriptSig pushes `<N>` then `<0>`.
|
|
1854
|
+
*
|
|
1855
|
+
* @param amount units of the asset the buyer is taking. Must be > 0 and
|
|
1856
|
+
* strictly less than the amount locked in the order UTXO
|
|
1857
|
+
* (equal would leave a zero-asset remainder, which isn't a
|
|
1858
|
+
* valid Neurai transfer output).
|
|
1859
|
+
*/
|
|
1860
|
+
function buildFillScriptSig(amount) {
|
|
1861
|
+
if (typeof amount !== 'bigint') {
|
|
1862
|
+
throw new Error('amount must be a bigint');
|
|
1863
|
+
}
|
|
1864
|
+
if (amount <= 0n) {
|
|
1865
|
+
throw new Error('fill amount must be > 0');
|
|
1866
|
+
}
|
|
1867
|
+
return new ScriptBuilder()
|
|
1868
|
+
.pushInt(amount)
|
|
1869
|
+
.pushInt(0)
|
|
1870
|
+
.build();
|
|
1871
|
+
}
|
|
1872
|
+
function buildFillScriptSigHex(amount) {
|
|
1873
|
+
return bytesToHex(buildFillScriptSig(amount));
|
|
1874
|
+
}
|
|
1875
|
+
/**
|
|
1876
|
+
* Unlock the covenant via the seller's cancel branch.
|
|
1877
|
+
*
|
|
1878
|
+
* Stack before OP_IF (top → bottom):
|
|
1879
|
+
* 1 ← selects the OP_IF branch
|
|
1880
|
+
* pubkey ← consumed by OP_DUP OP_HASH160 … OP_EQUALVERIFY
|
|
1881
|
+
* sig ← consumed by OP_CHECKSIG
|
|
1882
|
+
*
|
|
1883
|
+
* so the scriptSig pushes `<sig> <pubkey> <1>`.
|
|
1884
|
+
*
|
|
1885
|
+
* The signature is on whatever sighash the caller picked; this builder does
|
|
1886
|
+
* not hash or sign, it only assembles the unlock script once a signature is
|
|
1887
|
+
* available.
|
|
1888
|
+
*/
|
|
1889
|
+
function buildCancelScriptSig(signatureDer, pubKey) {
|
|
1890
|
+
if (!(signatureDer instanceof Uint8Array) || signatureDer.length === 0) {
|
|
1891
|
+
throw new Error('signatureDer must be a non-empty Uint8Array');
|
|
1892
|
+
}
|
|
1893
|
+
if (!(pubKey instanceof Uint8Array) || (pubKey.length !== 33 && pubKey.length !== 65)) {
|
|
1894
|
+
throw new Error('pubKey must be a compressed (33B) or uncompressed (65B) secp256k1 key');
|
|
1895
|
+
}
|
|
1896
|
+
return new ScriptBuilder()
|
|
1897
|
+
.pushBytes(signatureDer)
|
|
1898
|
+
.pushBytes(pubKey)
|
|
1899
|
+
.pushInt(1)
|
|
1900
|
+
.build();
|
|
1901
|
+
}
|
|
1902
|
+
function buildCancelScriptSigHex(signatureDer, pubKey) {
|
|
1903
|
+
return bytesToHex(buildCancelScriptSig(signatureDer, pubKey));
|
|
1904
|
+
}
|
|
1905
|
+
|
|
1906
|
+
/**
|
|
1907
|
+
* scriptSig builders for the PQ Partial-Fill Sell Order covenant.
|
|
1908
|
+
*
|
|
1909
|
+
* The fill branch is identical to the legacy variant (just pushes `<N> <0>`),
|
|
1910
|
+
* so callers reuse `buildFillScriptSig` from `./spend.ts`. Only the cancel
|
|
1911
|
+
* branch is different: it carries a full PQ pubkey (~1313 B) and signature
|
|
1912
|
+
* (~2421 B), which requires NIP-18's expanded element-size cap.
|
|
1913
|
+
*/
|
|
1914
|
+
/**
|
|
1915
|
+
* Build the scriptSig that unlocks the PQ cancel branch.
|
|
1916
|
+
*
|
|
1917
|
+
* Stack ordering pushed (bottom → top): `sig, pubkey, 1`.
|
|
1918
|
+
*
|
|
1919
|
+
* @param sigPQ ML-DSA-44 signature over `SHA256(OP_TXHASH(selector))`,
|
|
1920
|
+
* **with trailing sighash byte appended** (same convention as
|
|
1921
|
+
* OP_CHECKSIG — CSFS strips it before verification). Expected
|
|
1922
|
+
* length 2421 bytes for ML-DSA-44.
|
|
1923
|
+
* @param pubKey Versioned PQ public key bytes, 1313 bytes (1-byte prefix
|
|
1924
|
+
* + 1312-byte ML-DSA-44 key). Must hash (via SHA256) to the
|
|
1925
|
+
* `pubKeyCommitment` embedded in the covenant scriptPubKey.
|
|
1926
|
+
*/
|
|
1927
|
+
function buildCancelScriptSigPQ(sigPQ, pubKey) {
|
|
1928
|
+
if (!(sigPQ instanceof Uint8Array) || sigPQ.length === 0) {
|
|
1929
|
+
throw new Error('sigPQ must be a non-empty Uint8Array');
|
|
1930
|
+
}
|
|
1931
|
+
if (sigPQ.length > 3072) {
|
|
1932
|
+
throw new Error(`sigPQ of ${sigPQ.length} bytes exceeds MAX_PQ_SCRIPT_ELEMENT_SIZE (3072)`);
|
|
1933
|
+
}
|
|
1934
|
+
if (!(pubKey instanceof Uint8Array) || pubKey.length === 0) {
|
|
1935
|
+
throw new Error('pubKey must be a non-empty Uint8Array');
|
|
1936
|
+
}
|
|
1937
|
+
if (pubKey.length > 3072) {
|
|
1938
|
+
throw new Error(`pubKey of ${pubKey.length} bytes exceeds MAX_PQ_SCRIPT_ELEMENT_SIZE (3072)`);
|
|
1939
|
+
}
|
|
1940
|
+
return new ScriptBuilder()
|
|
1941
|
+
.pushBytes(sigPQ)
|
|
1942
|
+
.pushBytes(pubKey)
|
|
1943
|
+
.pushInt(1)
|
|
1944
|
+
.build();
|
|
1945
|
+
}
|
|
1946
|
+
function buildCancelScriptSigPQHex(sigPQ, pubKey) {
|
|
1947
|
+
return bytesToHex(buildCancelScriptSigPQ(sigPQ, pubKey));
|
|
1948
|
+
}
|
|
1949
|
+
|
|
1950
|
+
/**
|
|
1951
|
+
* Shared parsing primitives for strict covenant parsers. Each covenant
|
|
1952
|
+
* parser walks the exact byte layout emitted by its builder and fails on
|
|
1953
|
+
* any deviation; the primitives here centralize the cursor arithmetic,
|
|
1954
|
+
* pushdata decoding, and CScriptNum decoding so the legacy and PQ parsers
|
|
1955
|
+
* (and future covenant parsers) cannot drift in rigor.
|
|
1956
|
+
*/
|
|
1957
|
+
function makeCursor(bytes) {
|
|
1958
|
+
return { bytes, pos: 0 };
|
|
1959
|
+
}
|
|
1960
|
+
/** Consume one byte and verify it equals `expected`. */
|
|
1961
|
+
function expectByte(c, expected, label) {
|
|
1962
|
+
if (c.pos >= c.bytes.length) {
|
|
1963
|
+
throw new Error(`parse: unexpected end of script while reading ${label}`);
|
|
1964
|
+
}
|
|
1965
|
+
const got = c.bytes[c.pos];
|
|
1966
|
+
if (got !== expected) {
|
|
1967
|
+
throw new Error(`parse: expected ${label} = 0x${expected.toString(16)} at offset ${c.pos}, got 0x${got.toString(16)}`);
|
|
1968
|
+
}
|
|
1969
|
+
c.pos += 1;
|
|
1970
|
+
}
|
|
1971
|
+
/** Fail if the cursor has not consumed every byte of the script. */
|
|
1972
|
+
function assertTrailing(c) {
|
|
1973
|
+
if (c.pos !== c.bytes.length) {
|
|
1974
|
+
throw new Error(`parse: ${c.bytes.length - c.pos} trailing bytes after end of script`);
|
|
1975
|
+
}
|
|
1976
|
+
}
|
|
1977
|
+
/**
|
|
1978
|
+
* Read one pushdata element from the cursor. Supports direct pushes
|
|
1979
|
+
* (1..75 bytes), `OP_PUSHDATA1` and `OP_PUSHDATA2`. `OP_PUSHDATA4` is not
|
|
1980
|
+
* supported by any current covenant script and would overflow the
|
|
1981
|
+
* per-element cap anyway. Truncation is checked for all length fields
|
|
1982
|
+
* and payload ranges.
|
|
1983
|
+
*/
|
|
1984
|
+
function readPush(c, label) {
|
|
1985
|
+
if (c.pos >= c.bytes.length) {
|
|
1986
|
+
throw new Error(`parse: unexpected end of script while reading push for ${label}`);
|
|
1987
|
+
}
|
|
1988
|
+
const opcode = c.bytes[c.pos];
|
|
1989
|
+
c.pos += 1;
|
|
1990
|
+
// Short direct push: 1..75 bytes
|
|
1991
|
+
if (opcode >= 0x01 && opcode <= 0x4b) {
|
|
1992
|
+
const len = opcode;
|
|
1993
|
+
if (c.pos + len > c.bytes.length) {
|
|
1994
|
+
throw new Error(`parse: short push of ${len} bytes exceeds script length at ${label}`);
|
|
1995
|
+
}
|
|
1996
|
+
const data = c.bytes.slice(c.pos, c.pos + len);
|
|
1997
|
+
c.pos += len;
|
|
1998
|
+
return data;
|
|
1999
|
+
}
|
|
2000
|
+
// OP_PUSHDATA1
|
|
2001
|
+
if (opcode === 0x4c) {
|
|
2002
|
+
if (c.pos >= c.bytes.length) {
|
|
2003
|
+
throw new Error(`parse: truncated PUSHDATA1 length at ${label}`);
|
|
2004
|
+
}
|
|
2005
|
+
const len = c.bytes[c.pos];
|
|
2006
|
+
c.pos += 1;
|
|
2007
|
+
if (c.pos + len > c.bytes.length) {
|
|
2008
|
+
throw new Error(`parse: PUSHDATA1 of ${len} bytes exceeds script length at ${label}`);
|
|
2009
|
+
}
|
|
2010
|
+
const data = c.bytes.slice(c.pos, c.pos + len);
|
|
2011
|
+
c.pos += len;
|
|
2012
|
+
return data;
|
|
2013
|
+
}
|
|
2014
|
+
// OP_PUSHDATA2
|
|
2015
|
+
if (opcode === 0x4d) {
|
|
2016
|
+
if (c.pos + 2 > c.bytes.length) {
|
|
2017
|
+
throw new Error(`parse: truncated PUSHDATA2 length at ${label}`);
|
|
2018
|
+
}
|
|
2019
|
+
const len = c.bytes[c.pos] | (c.bytes[c.pos + 1] << 8);
|
|
2020
|
+
c.pos += 2;
|
|
2021
|
+
if (c.pos + len > c.bytes.length) {
|
|
2022
|
+
throw new Error(`parse: PUSHDATA2 of ${len} bytes exceeds script length at ${label}`);
|
|
2023
|
+
}
|
|
2024
|
+
const data = c.bytes.slice(c.pos, c.pos + len);
|
|
2025
|
+
c.pos += len;
|
|
2026
|
+
return data;
|
|
2027
|
+
}
|
|
2028
|
+
throw new Error(`parse: expected a pushdata opcode at ${label}, got 0x${opcode.toString(16)} at offset ${c.pos - 1}`);
|
|
2029
|
+
}
|
|
2030
|
+
/**
|
|
2031
|
+
* Decode a `CScriptNum` byte vector (little-endian sign-magnitude, up to
|
|
2032
|
+
* 8 bytes) into a BigInt. Empty vector encodes 0.
|
|
2033
|
+
*/
|
|
2034
|
+
function decodeScriptNum(data, label) {
|
|
2035
|
+
if (data.length === 0)
|
|
2036
|
+
return 0n;
|
|
2037
|
+
if (data.length > 8) {
|
|
2038
|
+
throw new Error(`parse: CScriptNum at ${label} exceeds 8 bytes`);
|
|
2039
|
+
}
|
|
2040
|
+
let n = 0n;
|
|
2041
|
+
for (let i = 0; i < data.length - 1; i += 1) {
|
|
2042
|
+
n |= BigInt(data[i]) << BigInt(8 * i);
|
|
2043
|
+
}
|
|
2044
|
+
const last = data[data.length - 1];
|
|
2045
|
+
n |= BigInt(last & 0x7f) << BigInt(8 * (data.length - 1));
|
|
2046
|
+
if (last & 0x80) {
|
|
2047
|
+
n = -n;
|
|
2048
|
+
}
|
|
2049
|
+
return n;
|
|
2050
|
+
}
|
|
2051
|
+
/**
|
|
2052
|
+
* Read a push as a non-negative CScriptNum. Recognises OP_1..OP_16
|
|
2053
|
+
* shorthand. `OP_0` is not accepted because the covenant callers use this
|
|
2054
|
+
* only for values that are strictly positive (prices, selectors, indices).
|
|
2055
|
+
*/
|
|
2056
|
+
function readPushPositiveInt(c, label) {
|
|
2057
|
+
if (c.pos >= c.bytes.length) {
|
|
2058
|
+
throw new Error(`parse: end of script at ${label}`);
|
|
2059
|
+
}
|
|
2060
|
+
const opcode = c.bytes[c.pos];
|
|
2061
|
+
if (opcode >= OP_1 && opcode <= 0x60) {
|
|
2062
|
+
c.pos += 1;
|
|
2063
|
+
return BigInt(opcode - OP_1 + 1);
|
|
2064
|
+
}
|
|
2065
|
+
const data = readPush(c, label);
|
|
2066
|
+
return decodeScriptNum(data, label);
|
|
2067
|
+
}
|
|
2068
|
+
|
|
2069
|
+
/**
|
|
2070
|
+
* Parser for the Partial-Fill Sell Order covenant.
|
|
2071
|
+
*
|
|
2072
|
+
* Extracts `(sellerPubKeyHash, unitPriceSats, tokenId)` from a scriptPubKey
|
|
2073
|
+
* that was produced by `buildPartialFillScript`. The parser walks the exact
|
|
2074
|
+
* byte layout emitted by the builder and fails on any deviation — this is
|
|
2075
|
+
* deliberate, so a downstream indexer can unambiguously classify a UTXO as
|
|
2076
|
+
* "partial-fill order" or "unknown script" with no false positives.
|
|
2077
|
+
*/
|
|
2078
|
+
/**
|
|
2079
|
+
* Parse a covenant scriptPubKey and extract its parameters. Throws with a
|
|
2080
|
+
* descriptive message if the bytes don't match the partial-fill template.
|
|
2081
|
+
*/
|
|
2082
|
+
function parsePartialFillScript(script, network = 'xna-test') {
|
|
2083
|
+
const bytes = typeof script === 'string' ? hexToBytes(script) : script;
|
|
2084
|
+
const c = makeCursor(bytes);
|
|
2085
|
+
// ───── Cancel branch prefix ─────
|
|
2086
|
+
expectByte(c, OP_IF, 'OP_IF');
|
|
2087
|
+
expectByte(c, OP_DUP, 'OP_DUP (cancel)');
|
|
2088
|
+
expectByte(c, OP_HASH160, 'OP_HASH160');
|
|
2089
|
+
const sellerPubKeyHash = readPush(c, 'sellerPubKeyHash');
|
|
2090
|
+
if (sellerPubKeyHash.length !== 20) {
|
|
2091
|
+
throw new Error(`parse: sellerPubKeyHash is ${sellerPubKeyHash.length} bytes, expected 20`);
|
|
2092
|
+
}
|
|
2093
|
+
expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (cancel)');
|
|
2094
|
+
expectByte(c, OP_CHECKSIG, 'OP_CHECKSIG (cancel)');
|
|
2095
|
+
expectByte(c, OP_ELSE, 'OP_ELSE');
|
|
2096
|
+
// ───── Payment value check ─────
|
|
2097
|
+
expectByte(c, OP_DUP, 'OP_DUP (price)');
|
|
2098
|
+
const unitPriceSats = readPushPositiveInt(c, 'unitPriceSats');
|
|
2099
|
+
expectByte(c, OP_MUL, 'OP_MUL');
|
|
2100
|
+
expectByte(c, OP_0, 'OP_0 (payment idx)');
|
|
2101
|
+
expectByte(c, OP_OUTPUTVALUE, 'OP_OUTPUTVALUE');
|
|
2102
|
+
expectByte(c, OP_SWAP, 'OP_SWAP');
|
|
2103
|
+
expectByte(c, OP_GREATERTHANOREQUAL, 'OP_GREATERTHANOREQUAL');
|
|
2104
|
+
expectByte(c, OP_VERIFY, 'OP_VERIFY (payment)');
|
|
2105
|
+
// ───── Payment scriptPubKey check ─────
|
|
2106
|
+
expectByte(c, OP_0, 'OP_0 (spk idx)');
|
|
2107
|
+
expectByte(c, OP_OUTPUTSCRIPT, 'OP_OUTPUTSCRIPT (payment)');
|
|
2108
|
+
const sellerSpk = readPush(c, 'sellerScriptPubKey');
|
|
2109
|
+
// Must be P2PKH with our PKH.
|
|
2110
|
+
const expectedSpk = new Uint8Array([
|
|
2111
|
+
OP_DUP, OP_HASH160, 0x14, ...sellerPubKeyHash, OP_EQUALVERIFY, OP_CHECKSIG
|
|
2112
|
+
]);
|
|
2113
|
+
if (!bytesEqual(sellerSpk, expectedSpk)) {
|
|
2114
|
+
throw new Error('parse: embedded seller scriptPubKey does not match the cancel PKH');
|
|
2115
|
+
}
|
|
2116
|
+
expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (payment spk)');
|
|
2117
|
+
// ───── Buyer asset amount check (output 1) ─────
|
|
2118
|
+
expectByte(c, OP_DUP, 'OP_DUP (buyer amount)');
|
|
2119
|
+
expectByte(c, OP_1, 'OP_1 (buyer idx)');
|
|
2120
|
+
expectByte(c, OP_2, 'OP_2 (AMOUNT selector)');
|
|
2121
|
+
expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer amount)');
|
|
2122
|
+
expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer amount)');
|
|
2123
|
+
// ───── Buyer asset name check (output 1) ─────
|
|
2124
|
+
expectByte(c, OP_1, 'OP_1 (buyer idx)');
|
|
2125
|
+
expectByte(c, OP_1, 'OP_1 (NAME selector)');
|
|
2126
|
+
expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer name)');
|
|
2127
|
+
const tokenIdBytes1 = readPush(c, 'tokenId #1');
|
|
2128
|
+
expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer name)');
|
|
2129
|
+
// ───── Remainder continuity: same scriptPubKey ─────
|
|
2130
|
+
expectByte(c, OP_2, 'OP_2 (remainder idx)');
|
|
2131
|
+
expectByte(c, OP_OUTPUTSCRIPT, 'OP_OUTPUTSCRIPT (remainder)');
|
|
2132
|
+
expectByte(c, OP_3, 'OP_3 (TXFIELD selector)');
|
|
2133
|
+
expectByte(c, OP_TXFIELD, 'OP_TXFIELD');
|
|
2134
|
+
expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder spk)');
|
|
2135
|
+
// ───── Remainder tokenId check ─────
|
|
2136
|
+
expectByte(c, OP_2, 'OP_2 (remainder idx)');
|
|
2137
|
+
expectByte(c, OP_1, 'OP_1 (NAME selector)');
|
|
2138
|
+
expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder name)');
|
|
2139
|
+
const tokenIdBytes2 = readPush(c, 'tokenId #2');
|
|
2140
|
+
expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder name)');
|
|
2141
|
+
// ───── Remainder amount == input amount - N ─────
|
|
2142
|
+
expectByte(c, OP_2, 'OP_2 (remainder idx)');
|
|
2143
|
+
expectByte(c, OP_2, 'OP_2 (AMOUNT selector)');
|
|
2144
|
+
expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder amount)');
|
|
2145
|
+
expectByte(c, OP_OVER, 'OP_OVER');
|
|
2146
|
+
expectByte(c, OP_0, 'OP_0 (input idx)');
|
|
2147
|
+
expectByte(c, OP_2, 'OP_2 (AMOUNT selector)');
|
|
2148
|
+
expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD');
|
|
2149
|
+
expectByte(c, OP_SWAP, 'OP_SWAP');
|
|
2150
|
+
expectByte(c, OP_SUB, 'OP_SUB');
|
|
2151
|
+
expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder amount)');
|
|
2152
|
+
// ───── Tail ─────
|
|
2153
|
+
expectByte(c, OP_DROP, 'OP_DROP');
|
|
2154
|
+
expectByte(c, OP_1, 'OP_1 (true)');
|
|
2155
|
+
expectByte(c, OP_ENDIF, 'OP_ENDIF');
|
|
2156
|
+
assertTrailing(c);
|
|
2157
|
+
if (!bytesEqual(tokenIdBytes1, tokenIdBytes2)) {
|
|
2158
|
+
throw new Error('parse: tokenId bytes differ between buyer and remainder checks');
|
|
2159
|
+
}
|
|
2160
|
+
const tokenId = new TextDecoder('utf-8', { fatal: true }).decode(tokenIdBytes1);
|
|
2161
|
+
return {
|
|
2162
|
+
network,
|
|
2163
|
+
sellerPubKeyHash,
|
|
2164
|
+
unitPriceSats,
|
|
2165
|
+
tokenId,
|
|
2166
|
+
scriptHex: bytesToHex(bytes)
|
|
2167
|
+
};
|
|
2168
|
+
}
|
|
2169
|
+
|
|
2170
|
+
/**
|
|
2171
|
+
* Parser for the PQ Partial-Fill Sell Order covenant. Returns the same
|
|
2172
|
+
* economic parameters as the legacy parser, plus the payment scriptPubKey
|
|
2173
|
+
* bytes (which may be P2PKH or AuthScript) and the configured TXHASH
|
|
2174
|
+
* selector.
|
|
2175
|
+
*/
|
|
2176
|
+
/** Quick discriminator without throwing — useful for indexers. */
|
|
2177
|
+
function isPartialFillScriptPQ(script) {
|
|
2178
|
+
const bytes = typeof script === 'string' ? hexToBytes(script) : script;
|
|
2179
|
+
// PQ cancel starts with: OP_IF OP_DUP OP_SHA256
|
|
2180
|
+
return (bytes.length > 3 &&
|
|
2181
|
+
bytes[0] === OP_IF &&
|
|
2182
|
+
bytes[1] === OP_DUP &&
|
|
2183
|
+
bytes[2] === OP_SHA256);
|
|
2184
|
+
}
|
|
2185
|
+
/**
|
|
2186
|
+
* Parse a PQ partial-fill covenant. Throws if the bytes do not match the
|
|
2187
|
+
* exact layout produced by `buildPartialFillScriptPQ`.
|
|
2188
|
+
*/
|
|
2189
|
+
function parsePartialFillScriptPQ(script, network = 'xna-test') {
|
|
2190
|
+
const bytes = typeof script === 'string' ? hexToBytes(script) : script;
|
|
2191
|
+
const c = makeCursor(bytes);
|
|
2192
|
+
// ───── Cancel branch (PQ) ─────
|
|
2193
|
+
expectByte(c, OP_IF, 'OP_IF');
|
|
2194
|
+
expectByte(c, OP_DUP, 'OP_DUP (cancel)');
|
|
2195
|
+
expectByte(c, OP_SHA256, 'OP_SHA256');
|
|
2196
|
+
const pubKeyCommitment = readPush(c, 'pubKeyCommitment');
|
|
2197
|
+
if (pubKeyCommitment.length !== 32) {
|
|
2198
|
+
throw new Error(`parse-pq: pubKeyCommitment must be 32 bytes, got ${pubKeyCommitment.length}`);
|
|
2199
|
+
}
|
|
2200
|
+
expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (cancel)');
|
|
2201
|
+
const txHashSelectorBig = readPushPositiveInt(c, 'txHashSelector');
|
|
2202
|
+
if (txHashSelectorBig < 1n || txHashSelectorBig > 0xffn) {
|
|
2203
|
+
throw new Error(`parse-pq: txHashSelector out of range (${txHashSelectorBig})`);
|
|
2204
|
+
}
|
|
2205
|
+
const txHashSelector = Number(txHashSelectorBig);
|
|
2206
|
+
expectByte(c, OP_TXHASH, 'OP_TXHASH');
|
|
2207
|
+
expectByte(c, OP_SWAP, 'OP_SWAP');
|
|
2208
|
+
expectByte(c, OP_CHECKSIGFROMSTACK, 'OP_CHECKSIGFROMSTACK');
|
|
2209
|
+
expectByte(c, OP_ELSE, 'OP_ELSE');
|
|
2210
|
+
// ───── Fill branch ─────
|
|
2211
|
+
expectByte(c, OP_DUP, 'OP_DUP (price)');
|
|
2212
|
+
const unitPriceSats = readPushPositiveInt(c, 'unitPriceSats');
|
|
2213
|
+
expectByte(c, OP_MUL, 'OP_MUL');
|
|
2214
|
+
expectByte(c, OP_0, 'OP_0 (payment idx)');
|
|
2215
|
+
expectByte(c, OP_OUTPUTVALUE, 'OP_OUTPUTVALUE');
|
|
2216
|
+
expectByte(c, OP_SWAP, 'OP_SWAP');
|
|
2217
|
+
expectByte(c, OP_GREATERTHANOREQUAL, 'OP_GE');
|
|
2218
|
+
expectByte(c, OP_VERIFY, 'OP_VERIFY');
|
|
2219
|
+
expectByte(c, OP_0, 'OP_0 (payment spk idx)');
|
|
2220
|
+
expectByte(c, OP_OUTPUTSCRIPT, 'OP_OUTPUTSCRIPT (payment)');
|
|
2221
|
+
const paymentScriptPubKey = readPush(c, 'paymentScriptPubKey');
|
|
2222
|
+
expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (payment)');
|
|
2223
|
+
expectByte(c, OP_DUP, 'OP_DUP (buyer amount)');
|
|
2224
|
+
expectByte(c, OP_1, 'OP_1 (buyer idx)');
|
|
2225
|
+
expectByte(c, OP_2, 'OP_2 (AMOUNT selector)');
|
|
2226
|
+
expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer amount)');
|
|
2227
|
+
expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer amount)');
|
|
2228
|
+
expectByte(c, OP_1, 'OP_1 (buyer idx)');
|
|
2229
|
+
expectByte(c, OP_1, 'OP_1 (NAME selector)');
|
|
2230
|
+
expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (buyer name)');
|
|
2231
|
+
const tokenIdBytes1 = readPush(c, 'tokenId #1');
|
|
2232
|
+
expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (buyer name)');
|
|
2233
|
+
expectByte(c, OP_2, 'OP_2 (remainder idx)');
|
|
2234
|
+
expectByte(c, OP_OUTPUTSCRIPT, 'OP_OUTPUTSCRIPT (remainder)');
|
|
2235
|
+
expectByte(c, OP_3, 'OP_3 (TXFIELD selector)');
|
|
2236
|
+
expectByte(c, OP_TXFIELD, 'OP_TXFIELD');
|
|
2237
|
+
expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder spk)');
|
|
2238
|
+
expectByte(c, OP_2, 'OP_2 (remainder idx)');
|
|
2239
|
+
expectByte(c, OP_1, 'OP_1 (NAME selector)');
|
|
2240
|
+
expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder name)');
|
|
2241
|
+
const tokenIdBytes2 = readPush(c, 'tokenId #2');
|
|
2242
|
+
expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder name)');
|
|
2243
|
+
expectByte(c, OP_2, 'OP_2 (remainder idx)');
|
|
2244
|
+
expectByte(c, OP_2, 'OP_2 (AMOUNT selector)');
|
|
2245
|
+
expectByte(c, OP_OUTPUTASSETFIELD, 'OP_OUTPUTASSETFIELD (remainder amount)');
|
|
2246
|
+
expectByte(c, OP_OVER, 'OP_OVER');
|
|
2247
|
+
expectByte(c, OP_0, 'OP_0 (input idx)');
|
|
2248
|
+
expectByte(c, OP_2, 'OP_2 (AMOUNT selector)');
|
|
2249
|
+
expectByte(c, OP_INPUTASSETFIELD, 'OP_INPUTASSETFIELD');
|
|
2250
|
+
expectByte(c, OP_SWAP, 'OP_SWAP');
|
|
2251
|
+
expectByte(c, OP_SUB, 'OP_SUB');
|
|
2252
|
+
expectByte(c, OP_EQUALVERIFY, 'OP_EQUALVERIFY (remainder amount)');
|
|
2253
|
+
expectByte(c, OP_DROP, 'OP_DROP');
|
|
2254
|
+
expectByte(c, OP_1, 'OP_1 (true)');
|
|
2255
|
+
expectByte(c, OP_ENDIF, 'OP_ENDIF');
|
|
2256
|
+
assertTrailing(c);
|
|
2257
|
+
if (!bytesEqual(tokenIdBytes1, tokenIdBytes2)) {
|
|
2258
|
+
throw new Error('parse-pq: tokenId differs between buyer and remainder checks');
|
|
2259
|
+
}
|
|
2260
|
+
const tokenId = new TextDecoder('utf-8', { fatal: true }).decode(tokenIdBytes1);
|
|
2261
|
+
return {
|
|
2262
|
+
network,
|
|
2263
|
+
pubKeyCommitment,
|
|
2264
|
+
tokenId,
|
|
2265
|
+
unitPriceSats,
|
|
2266
|
+
txHashSelector,
|
|
2267
|
+
paymentScriptPubKey,
|
|
2268
|
+
scriptHex: bytesToHex(bytes)
|
|
2269
|
+
};
|
|
2270
|
+
}
|
|
2271
|
+
|
|
2272
|
+
export { AUTHSCRIPT_LEGACY, AUTHSCRIPT_NOAUTH, AUTHSCRIPT_PQ, AUTHSCRIPT_REF, DEFAULT_PQ_TXHASH_SELECTOR, MULTISIG_MAX_PUBKEYS, NULLDATA_STANDARD_MAX_SIZE, ScriptBuilder, buildAuthScriptWitnessLegacy, buildAuthScriptWitnessNoAuth, buildAuthScriptWitnessPQ, buildAuthScriptWitnessRef, buildCancelScriptSig, buildCancelScriptSigHex, buildCancelScriptSigPQ, buildCancelScriptSigPQHex, buildFillScriptSig, buildFillScriptSigHex, buildPartialFillScript, buildPartialFillScriptHex, buildPartialFillScriptPQ, buildPartialFillScriptPQHex, bytesEqual, bytesToHex, concatBytes, encodeAuthScriptScriptPubKey, encodeMultisigRedeemScript, encodeMultisigRedeemScriptHex, encodeNullDataScript, encodeP2PKHScriptPubKey, encodeP2SHScriptPubKey, encodeP2WPKHScriptPubKey, encodeP2WSHScriptPubKey, encodeScriptNum, encodeSellerScriptPubKey, ensureHex, hexToBytes, isPartialFillScriptPQ, opcodes, parsePartialFillScript, parsePartialFillScriptPQ, pushBytes, pushHex, pushInt };
|
|
2273
|
+
//# sourceMappingURL=browser.js.map
|