@scure/btc-signer 1.1.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,3035 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TAP_LEAF_VERSION = exports._sortPubkeys = exports.SigHash = exports.SignatureHash = exports.Address = exports.WIF = exports.programToWitness = exports.OutScript = exports.p2tr_ms = exports.p2tr_pk = exports.p2tr_ns = exports.combinations = exports.p2tr = exports.TAPROOT_UNSPENDABLE_KEY = exports.taprootListToTree = exports.p2ms = exports.p2wpkh = exports.p2wsh = exports.p2sh = exports.p2pkh = exports.p2pk = exports.RawPSBTV2 = exports.RawPSBTV0 = exports._DebugPSBT = exports._RawPSBTV2 = exports._RawPSBTV0 = exports.TaprootControlBlock = exports.RawTx = exports.RawWitness = exports.RawOutput = exports.RawInput = exports.VarBytes = exports.BTCArray = exports.CompactSize = exports.OpToNum = exports.ScriptNum = exports.Script = exports.OP = exports._cmpBytes = exports.Decimal = exports.DEFAULT_SEQUENCE = exports.DEFAULT_LOCKTIME = exports.DEFAULT_VERSION = exports.PRECISION = exports.TEST_NETWORK = exports.NETWORK = exports.taprootTweakPubkey = exports.taprootTweakPrivKey = exports.cloneDeep = exports.base58check = void 0;
4
+ exports.selectUTXO = exports._Estimator = exports._cmpBig = exports.PSBTCombine = exports.bip32Path = exports.sortedMultisig = exports.multisig = exports.getAddress = exports.Transaction = exports.tapLeafHash = void 0;
5
+ /*! scure-btc-signer - MIT License (c) 2022 Paul Miller (paulmillr.com) */
6
+ const secp256k1_1 = require("@noble/curves/secp256k1");
7
+ const sha256_1 = require("@noble/hashes/sha256");
8
+ const ripemd160_1 = require("@noble/hashes/ripemd160");
9
+ const base_1 = require("@scure/base");
10
+ const P = require("micro-packed");
11
+ const { ProjectivePoint: ProjPoint, sign: _signECDSA, getPublicKey: _pubECDSA } = secp256k1_1.secp256k1;
12
+ const CURVE_ORDER = secp256k1_1.secp256k1.CURVE.n;
13
+ // Same as value || def, but doesn't overwrites zero ('0', 0, 0n, etc)
14
+ const def = (value, def) => (value === undefined ? def : value);
15
+ const isBytes = P.isBytes;
16
+ const hash160 = (msg) => (0, ripemd160_1.ripemd160)((0, sha256_1.sha256)(msg));
17
+ const sha256x2 = (...msgs) => (0, sha256_1.sha256)((0, sha256_1.sha256)(concat(...msgs)));
18
+ const concat = P.concatBytes;
19
+ // Make base58check work
20
+ exports.base58check = (0, base_1.createBase58check)(sha256_1.sha256);
21
+ function cloneDeep(obj) {
22
+ if (Array.isArray(obj))
23
+ return obj.map((i) => cloneDeep(i));
24
+ // slice of nodejs Buffer doesn't copy
25
+ else if (obj instanceof Uint8Array)
26
+ return Uint8Array.from(obj);
27
+ // immutable
28
+ else if (['number', 'bigint', 'boolean', 'string', 'undefined'].includes(typeof obj))
29
+ return obj;
30
+ // null is object
31
+ else if (obj === null)
32
+ return obj;
33
+ // should be last, so it won't catch other types
34
+ else if (typeof obj === 'object') {
35
+ return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, cloneDeep(v)]));
36
+ }
37
+ throw new Error(`cloneDeep: unknown type=${obj} (${typeof obj})`);
38
+ }
39
+ exports.cloneDeep = cloneDeep;
40
+ var PubT;
41
+ (function (PubT) {
42
+ PubT[PubT["ecdsa"] = 0] = "ecdsa";
43
+ PubT[PubT["schnorr"] = 1] = "schnorr";
44
+ })(PubT || (PubT = {}));
45
+ function validatePubkey(pub, type) {
46
+ const len = pub.length;
47
+ if (type === PubT.ecdsa) {
48
+ if (len === 32)
49
+ throw new Error('Expected non-Schnorr key');
50
+ ProjPoint.fromHex(pub); // does assertValidity
51
+ return pub;
52
+ }
53
+ else if (type === PubT.schnorr) {
54
+ if (len !== 32)
55
+ throw new Error('Expected 32-byte Schnorr key');
56
+ secp256k1_1.schnorr.utils.lift_x(secp256k1_1.schnorr.utils.bytesToNumberBE(pub));
57
+ return pub;
58
+ }
59
+ else {
60
+ throw new Error('Unknown key type');
61
+ }
62
+ }
63
+ function isValidPubkey(pub, type) {
64
+ try {
65
+ validatePubkey(pub, type);
66
+ return true;
67
+ }
68
+ catch (e) {
69
+ return false;
70
+ }
71
+ }
72
+ // low-r signature grinding. Used to reduce tx size by 1 byte.
73
+ // noble/secp256k1 does not support the feature: it is not used outside of BTC.
74
+ // We implement it manually, because in BTC it's common.
75
+ // Not best way, but closest to bitcoin implementation (easier to check)
76
+ const hasLowR = (sig) => sig.r < CURVE_ORDER / 2n;
77
+ function signECDSA(hash, privateKey, lowR = false) {
78
+ let sig = _signECDSA(hash, privateKey);
79
+ if (lowR && !hasLowR(sig)) {
80
+ const extraEntropy = new Uint8Array(32);
81
+ for (let cnt = 0; cnt < Number.MAX_SAFE_INTEGER; cnt++) {
82
+ extraEntropy.set(P.U32LE.encode(cnt));
83
+ sig = _signECDSA(hash, privateKey, { extraEntropy });
84
+ if (hasLowR(sig))
85
+ break;
86
+ }
87
+ }
88
+ return sig.toDERRawBytes();
89
+ }
90
+ function tapTweak(a, b) {
91
+ const u = secp256k1_1.schnorr.utils;
92
+ const t = u.taggedHash('TapTweak', a, b);
93
+ const tn = u.bytesToNumberBE(t);
94
+ if (tn >= CURVE_ORDER)
95
+ throw new Error('tweak higher than curve order');
96
+ return tn;
97
+ }
98
+ function taprootTweakPrivKey(privKey, merkleRoot = new Uint8Array()) {
99
+ const u = secp256k1_1.schnorr.utils;
100
+ const seckey0 = u.bytesToNumberBE(privKey); // seckey0 = int_from_bytes(seckey0)
101
+ const P = ProjPoint.fromPrivateKey(seckey0); // P = point_mul(G, seckey0)
102
+ // seckey = seckey0 if has_even_y(P) else SECP256K1_ORDER - seckey0
103
+ const seckey = P.hasEvenY() ? seckey0 : u.mod(-seckey0, CURVE_ORDER);
104
+ const xP = u.pointToBytes(P);
105
+ // t = int_from_bytes(tagged_hash("TapTweak", bytes_from_int(x(P)) + h)); >= SECP256K1_ORDER check
106
+ const t = tapTweak(xP, merkleRoot);
107
+ // bytes_from_int((seckey + t) % SECP256K1_ORDER)
108
+ return u.numberToBytesBE(u.mod(seckey + t, CURVE_ORDER), 32);
109
+ }
110
+ exports.taprootTweakPrivKey = taprootTweakPrivKey;
111
+ function taprootTweakPubkey(pubKey, h) {
112
+ const u = secp256k1_1.schnorr.utils;
113
+ const t = tapTweak(pubKey, h); // t = int_from_bytes(tagged_hash("TapTweak", pubkey + h))
114
+ const P = u.lift_x(u.bytesToNumberBE(pubKey)); // P = lift_x(int_from_bytes(pubkey))
115
+ const Q = P.add(ProjPoint.fromPrivateKey(t)); // Q = point_add(P, point_mul(G, t))
116
+ const parity = Q.hasEvenY() ? 0 : 1; // 0 if has_even_y(Q) else 1
117
+ return [u.pointToBytes(Q), parity]; // bytes_from_int(x(Q))
118
+ }
119
+ exports.taprootTweakPubkey = taprootTweakPubkey;
120
+ // Can be 33 or 64 bytes
121
+ const PubKeyECDSA = P.validate(P.bytes(null), (pub) => validatePubkey(pub, PubT.ecdsa));
122
+ const PubKeySchnorr = P.validate(P.bytes(32), (pub) => validatePubkey(pub, PubT.schnorr));
123
+ const SignatureSchnorr = P.validate(P.bytes(null), (sig) => {
124
+ if (sig.length !== 64 && sig.length !== 65)
125
+ throw new Error('Schnorr signature should be 64 or 65 bytes long');
126
+ return sig;
127
+ });
128
+ function uniqPubkey(pubkeys) {
129
+ const map = {};
130
+ for (const pub of pubkeys) {
131
+ const key = base_1.hex.encode(pub);
132
+ if (map[key])
133
+ throw new Error(`Multisig: non-uniq pubkey: ${pubkeys.map(base_1.hex.encode)}`);
134
+ map[key] = true;
135
+ }
136
+ }
137
+ exports.NETWORK = {
138
+ bech32: 'bc',
139
+ pubKeyHash: 0x00,
140
+ scriptHash: 0x05,
141
+ wif: 0x80,
142
+ };
143
+ exports.TEST_NETWORK = {
144
+ bech32: 'tb',
145
+ pubKeyHash: 0x6f,
146
+ scriptHash: 0xc4,
147
+ wif: 0xef,
148
+ };
149
+ exports.PRECISION = 8;
150
+ exports.DEFAULT_VERSION = 2;
151
+ exports.DEFAULT_LOCKTIME = 0;
152
+ exports.DEFAULT_SEQUENCE = 4294967295;
153
+ const EMPTY32 = new Uint8Array(32);
154
+ // Utils
155
+ exports.Decimal = P.coders.decimal(exports.PRECISION);
156
+ // Exported for tests, internal method
157
+ function _cmpBytes(a, b) {
158
+ if (!isBytes(a) || !isBytes(b))
159
+ throw new Error(`cmp: wrong type a=${typeof a} b=${typeof b}`);
160
+ // -1 -> a<b, 0 -> a==b, 1 -> a>b
161
+ const len = Math.min(a.length, b.length);
162
+ for (let i = 0; i < len; i++)
163
+ if (a[i] != b[i])
164
+ return Math.sign(a[i] - b[i]);
165
+ return Math.sign(a.length - b.length);
166
+ }
167
+ exports._cmpBytes = _cmpBytes;
168
+ // Coders
169
+ // prettier-ignore
170
+ var OP;
171
+ (function (OP) {
172
+ OP[OP["OP_0"] = 0] = "OP_0";
173
+ OP[OP["PUSHDATA1"] = 76] = "PUSHDATA1";
174
+ OP[OP["PUSHDATA2"] = 77] = "PUSHDATA2";
175
+ OP[OP["PUSHDATA4"] = 78] = "PUSHDATA4";
176
+ OP[OP["1NEGATE"] = 79] = "1NEGATE";
177
+ OP[OP["RESERVED"] = 80] = "RESERVED";
178
+ OP[OP["OP_1"] = 81] = "OP_1";
179
+ OP[OP["OP_2"] = 82] = "OP_2";
180
+ OP[OP["OP_3"] = 83] = "OP_3";
181
+ OP[OP["OP_4"] = 84] = "OP_4";
182
+ OP[OP["OP_5"] = 85] = "OP_5";
183
+ OP[OP["OP_6"] = 86] = "OP_6";
184
+ OP[OP["OP_7"] = 87] = "OP_7";
185
+ OP[OP["OP_8"] = 88] = "OP_8";
186
+ OP[OP["OP_9"] = 89] = "OP_9";
187
+ OP[OP["OP_10"] = 90] = "OP_10";
188
+ OP[OP["OP_11"] = 91] = "OP_11";
189
+ OP[OP["OP_12"] = 92] = "OP_12";
190
+ OP[OP["OP_13"] = 93] = "OP_13";
191
+ OP[OP["OP_14"] = 94] = "OP_14";
192
+ OP[OP["OP_15"] = 95] = "OP_15";
193
+ OP[OP["OP_16"] = 96] = "OP_16";
194
+ // Control
195
+ OP[OP["NOP"] = 97] = "NOP";
196
+ OP[OP["VER"] = 98] = "VER";
197
+ OP[OP["IF"] = 99] = "IF";
198
+ OP[OP["NOTIF"] = 100] = "NOTIF";
199
+ OP[OP["VERIF"] = 101] = "VERIF";
200
+ OP[OP["VERNOTIF"] = 102] = "VERNOTIF";
201
+ OP[OP["ELSE"] = 103] = "ELSE";
202
+ OP[OP["ENDIF"] = 104] = "ENDIF";
203
+ OP[OP["VERIFY"] = 105] = "VERIFY";
204
+ OP[OP["RETURN"] = 106] = "RETURN";
205
+ // Stack
206
+ OP[OP["TOALTSTACK"] = 107] = "TOALTSTACK";
207
+ OP[OP["FROMALTSTACK"] = 108] = "FROMALTSTACK";
208
+ OP[OP["2DROP"] = 109] = "2DROP";
209
+ OP[OP["2DUP"] = 110] = "2DUP";
210
+ OP[OP["3DUP"] = 111] = "3DUP";
211
+ OP[OP["2OVER"] = 112] = "2OVER";
212
+ OP[OP["2ROT"] = 113] = "2ROT";
213
+ OP[OP["2SWAP"] = 114] = "2SWAP";
214
+ OP[OP["IFDUP"] = 115] = "IFDUP";
215
+ OP[OP["DEPTH"] = 116] = "DEPTH";
216
+ OP[OP["DROP"] = 117] = "DROP";
217
+ OP[OP["DUP"] = 118] = "DUP";
218
+ OP[OP["NIP"] = 119] = "NIP";
219
+ OP[OP["OVER"] = 120] = "OVER";
220
+ OP[OP["PICK"] = 121] = "PICK";
221
+ OP[OP["ROLL"] = 122] = "ROLL";
222
+ OP[OP["ROT"] = 123] = "ROT";
223
+ OP[OP["SWAP"] = 124] = "SWAP";
224
+ OP[OP["TUCK"] = 125] = "TUCK";
225
+ // Splice
226
+ OP[OP["CAT"] = 126] = "CAT";
227
+ OP[OP["SUBSTR"] = 127] = "SUBSTR";
228
+ OP[OP["LEFT"] = 128] = "LEFT";
229
+ OP[OP["RIGHT"] = 129] = "RIGHT";
230
+ OP[OP["SIZE"] = 130] = "SIZE";
231
+ // Boolean logic
232
+ OP[OP["INVERT"] = 131] = "INVERT";
233
+ OP[OP["AND"] = 132] = "AND";
234
+ OP[OP["OR"] = 133] = "OR";
235
+ OP[OP["XOR"] = 134] = "XOR";
236
+ OP[OP["EQUAL"] = 135] = "EQUAL";
237
+ OP[OP["EQUALVERIFY"] = 136] = "EQUALVERIFY";
238
+ OP[OP["RESERVED1"] = 137] = "RESERVED1";
239
+ OP[OP["RESERVED2"] = 138] = "RESERVED2";
240
+ // Numbers
241
+ OP[OP["1ADD"] = 139] = "1ADD";
242
+ OP[OP["1SUB"] = 140] = "1SUB";
243
+ OP[OP["2MUL"] = 141] = "2MUL";
244
+ OP[OP["2DIV"] = 142] = "2DIV";
245
+ OP[OP["NEGATE"] = 143] = "NEGATE";
246
+ OP[OP["ABS"] = 144] = "ABS";
247
+ OP[OP["NOT"] = 145] = "NOT";
248
+ OP[OP["0NOTEQUAL"] = 146] = "0NOTEQUAL";
249
+ OP[OP["ADD"] = 147] = "ADD";
250
+ OP[OP["SUB"] = 148] = "SUB";
251
+ OP[OP["MUL"] = 149] = "MUL";
252
+ OP[OP["DIV"] = 150] = "DIV";
253
+ OP[OP["MOD"] = 151] = "MOD";
254
+ OP[OP["LSHIFT"] = 152] = "LSHIFT";
255
+ OP[OP["RSHIFT"] = 153] = "RSHIFT";
256
+ OP[OP["BOOLAND"] = 154] = "BOOLAND";
257
+ OP[OP["BOOLOR"] = 155] = "BOOLOR";
258
+ OP[OP["NUMEQUAL"] = 156] = "NUMEQUAL";
259
+ OP[OP["NUMEQUALVERIFY"] = 157] = "NUMEQUALVERIFY";
260
+ OP[OP["NUMNOTEQUAL"] = 158] = "NUMNOTEQUAL";
261
+ OP[OP["LESSTHAN"] = 159] = "LESSTHAN";
262
+ OP[OP["GREATERTHAN"] = 160] = "GREATERTHAN";
263
+ OP[OP["LESSTHANOREQUAL"] = 161] = "LESSTHANOREQUAL";
264
+ OP[OP["GREATERTHANOREQUAL"] = 162] = "GREATERTHANOREQUAL";
265
+ OP[OP["MIN"] = 163] = "MIN";
266
+ OP[OP["MAX"] = 164] = "MAX";
267
+ OP[OP["WITHIN"] = 165] = "WITHIN";
268
+ // Crypto
269
+ OP[OP["RIPEMD160"] = 166] = "RIPEMD160";
270
+ OP[OP["SHA1"] = 167] = "SHA1";
271
+ OP[OP["SHA256"] = 168] = "SHA256";
272
+ OP[OP["HASH160"] = 169] = "HASH160";
273
+ OP[OP["HASH256"] = 170] = "HASH256";
274
+ OP[OP["CODESEPARATOR"] = 171] = "CODESEPARATOR";
275
+ OP[OP["CHECKSIG"] = 172] = "CHECKSIG";
276
+ OP[OP["CHECKSIGVERIFY"] = 173] = "CHECKSIGVERIFY";
277
+ OP[OP["CHECKMULTISIG"] = 174] = "CHECKMULTISIG";
278
+ OP[OP["CHECKMULTISIGVERIFY"] = 175] = "CHECKMULTISIGVERIFY";
279
+ // Expansion
280
+ OP[OP["NOP1"] = 176] = "NOP1";
281
+ OP[OP["CHECKLOCKTIMEVERIFY"] = 177] = "CHECKLOCKTIMEVERIFY";
282
+ OP[OP["CHECKSEQUENCEVERIFY"] = 178] = "CHECKSEQUENCEVERIFY";
283
+ OP[OP["NOP4"] = 179] = "NOP4";
284
+ OP[OP["NOP5"] = 180] = "NOP5";
285
+ OP[OP["NOP6"] = 181] = "NOP6";
286
+ OP[OP["NOP7"] = 182] = "NOP7";
287
+ OP[OP["NOP8"] = 183] = "NOP8";
288
+ OP[OP["NOP9"] = 184] = "NOP9";
289
+ OP[OP["NOP10"] = 185] = "NOP10";
290
+ // BIP 342
291
+ OP[OP["CHECKSIGADD"] = 186] = "CHECKSIGADD";
292
+ // Invalid
293
+ OP[OP["INVALID"] = 255] = "INVALID";
294
+ })(OP || (exports.OP = OP = {}));
295
+ // Converts script bytes to parsed script
296
+ // 5221030000000000000000000000000000000000000000000000000000000000000001210300000000000000000000000000000000000000000000000000000000000000022103000000000000000000000000000000000000000000000000000000000000000353ae
297
+ // =>
298
+ // OP_2
299
+ // 030000000000000000000000000000000000000000000000000000000000000001
300
+ // 030000000000000000000000000000000000000000000000000000000000000002
301
+ // 030000000000000000000000000000000000000000000000000000000000000003
302
+ // OP_3
303
+ // CHECKMULTISIG
304
+ exports.Script = P.wrap({
305
+ encodeStream: (w, value) => {
306
+ for (let o of value) {
307
+ if (typeof o === 'string') {
308
+ if (OP[o] === undefined)
309
+ throw new Error(`Unknown opcode=${o}`);
310
+ w.byte(OP[o]);
311
+ continue;
312
+ }
313
+ else if (typeof o === 'number') {
314
+ if (o === 0x00) {
315
+ w.byte(0x00);
316
+ continue;
317
+ }
318
+ else if (1 <= o && o <= 16) {
319
+ w.byte(OP.OP_1 - 1 + o);
320
+ continue;
321
+ }
322
+ }
323
+ // Encode big numbers
324
+ if (typeof o === 'number')
325
+ o = ScriptNum().encode(BigInt(o));
326
+ if (!isBytes(o))
327
+ throw new Error(`Wrong Script OP=${o} (${typeof o})`);
328
+ // Bytes
329
+ const len = o.length;
330
+ if (len < OP.PUSHDATA1)
331
+ w.byte(len);
332
+ else if (len <= 0xff) {
333
+ w.byte(OP.PUSHDATA1);
334
+ w.byte(len);
335
+ }
336
+ else if (len <= 0xffff) {
337
+ w.byte(OP.PUSHDATA2);
338
+ w.bytes(P.U16LE.encode(len));
339
+ }
340
+ else {
341
+ w.byte(OP.PUSHDATA4);
342
+ w.bytes(P.U32LE.encode(len));
343
+ }
344
+ w.bytes(o);
345
+ }
346
+ },
347
+ decodeStream: (r) => {
348
+ const out = [];
349
+ while (!r.isEnd()) {
350
+ const cur = r.byte();
351
+ // if 0 < cur < 78
352
+ if (OP.OP_0 < cur && cur <= OP.PUSHDATA4) {
353
+ let len;
354
+ if (cur < OP.PUSHDATA1)
355
+ len = cur;
356
+ else if (cur === OP.PUSHDATA1)
357
+ len = P.U8.decodeStream(r);
358
+ else if (cur === OP.PUSHDATA2)
359
+ len = P.U16LE.decodeStream(r);
360
+ else if (cur === OP.PUSHDATA4)
361
+ len = P.U32LE.decodeStream(r);
362
+ else
363
+ throw new Error('Should be not possible');
364
+ out.push(r.bytes(len));
365
+ }
366
+ else if (cur === 0x00) {
367
+ out.push(0);
368
+ }
369
+ else if (OP.OP_1 <= cur && cur <= OP.OP_16) {
370
+ out.push(cur - (OP.OP_1 - 1));
371
+ }
372
+ else {
373
+ const op = OP[cur];
374
+ if (op === undefined)
375
+ throw new Error(`Unknown opcode=${cur.toString(16)}`);
376
+ out.push(op);
377
+ }
378
+ }
379
+ return out;
380
+ },
381
+ });
382
+ // We can encode almost any number as ScriptNum, however, parsing will be a problem
383
+ // since we can't know if buffer is a number or something else.
384
+ function ScriptNum(bytesLimit = 6, forceMinimal = false) {
385
+ return P.wrap({
386
+ encodeStream: (w, value) => {
387
+ if (value === 0n)
388
+ return;
389
+ const neg = value < 0;
390
+ const val = BigInt(value);
391
+ const nums = [];
392
+ for (let abs = neg ? -val : val; abs; abs >>= 8n)
393
+ nums.push(Number(abs & 0xffn));
394
+ if (nums[nums.length - 1] >= 0x80)
395
+ nums.push(neg ? 0x80 : 0);
396
+ else if (neg)
397
+ nums[nums.length - 1] |= 0x80;
398
+ w.bytes(new Uint8Array(nums));
399
+ },
400
+ decodeStream: (r) => {
401
+ const len = r.leftBytes;
402
+ if (len > bytesLimit)
403
+ throw new Error(`ScriptNum: number (${len}) bigger than limit=${bytesLimit}`);
404
+ if (len === 0)
405
+ return 0n;
406
+ if (forceMinimal) {
407
+ // MSB is zero (without sign bit) -> not minimally encoded
408
+ if ((r.data[len - 1] & 0x7f) === 0) {
409
+ // exception
410
+ if (len <= 1 || (r.data[len - 2] & 0x80) === 0)
411
+ throw new Error('Non-minimally encoded ScriptNum');
412
+ }
413
+ }
414
+ let last = 0;
415
+ let res = 0n;
416
+ for (let i = 0; i < len; ++i) {
417
+ last = r.byte();
418
+ res |= BigInt(last) << (8n * BigInt(i));
419
+ }
420
+ if (last >= 0x80) {
421
+ res &= (2n ** BigInt(len * 8) - 1n) >> 1n;
422
+ res = -res;
423
+ }
424
+ return res;
425
+ },
426
+ });
427
+ }
428
+ exports.ScriptNum = ScriptNum;
429
+ function OpToNum(op, bytesLimit = 4, forceMinimal = true) {
430
+ if (typeof op === 'number')
431
+ return op;
432
+ if (isBytes(op)) {
433
+ try {
434
+ const val = ScriptNum(bytesLimit, forceMinimal).decode(op);
435
+ if (val > Number.MAX_SAFE_INTEGER)
436
+ return;
437
+ return Number(val);
438
+ }
439
+ catch (e) {
440
+ return;
441
+ }
442
+ }
443
+ return;
444
+ }
445
+ exports.OpToNum = OpToNum;
446
+ // BTC specific variable length integer encoding
447
+ // https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer
448
+ const CSLimits = {
449
+ 0xfd: [0xfd, 2, 253n, 65535n],
450
+ 0xfe: [0xfe, 4, 65536n, 4294967295n],
451
+ 0xff: [0xff, 8, 4294967296n, 18446744073709551615n],
452
+ };
453
+ exports.CompactSize = P.wrap({
454
+ encodeStream: (w, value) => {
455
+ if (typeof value === 'number')
456
+ value = BigInt(value);
457
+ if (0n <= value && value <= 252n)
458
+ return w.byte(Number(value));
459
+ for (const [flag, bytes, start, stop] of Object.values(CSLimits)) {
460
+ if (start > value || value > stop)
461
+ continue;
462
+ w.byte(flag);
463
+ for (let i = 0; i < bytes; i++)
464
+ w.byte(Number((value >> (8n * BigInt(i))) & 0xffn));
465
+ return;
466
+ }
467
+ throw w.err(`VarInt too big: ${value}`);
468
+ },
469
+ decodeStream: (r) => {
470
+ const b0 = r.byte();
471
+ if (b0 <= 0xfc)
472
+ return BigInt(b0);
473
+ const [_, bytes, start] = CSLimits[b0];
474
+ let num = 0n;
475
+ for (let i = 0; i < bytes; i++)
476
+ num |= BigInt(r.byte()) << (8n * BigInt(i));
477
+ if (num < start)
478
+ throw r.err(`Wrong CompactSize(${8 * bytes})`);
479
+ return num;
480
+ },
481
+ });
482
+ // Same thing, but in number instead of bigint. Checks for safe integer inside
483
+ const CompactSizeLen = P.apply(exports.CompactSize, P.coders.number);
484
+ // Array of size <CompactSize>
485
+ const BTCArray = (t) => P.array(exports.CompactSize, t);
486
+ exports.BTCArray = BTCArray;
487
+ // ui8a of size <CompactSize>
488
+ exports.VarBytes = P.bytes(exports.CompactSize);
489
+ exports.RawInput = P.struct({
490
+ txid: P.bytes(32, true), // hash(prev_tx),
491
+ index: P.U32LE, // output number of previous tx
492
+ finalScriptSig: exports.VarBytes, // btc merges input and output script, executes it. If ok = tx passes
493
+ sequence: P.U32LE, // ?
494
+ });
495
+ exports.RawOutput = P.struct({ amount: P.U64LE, script: exports.VarBytes });
496
+ const EMPTY_OUTPUT = {
497
+ amount: 0xffffffffffffffffn,
498
+ script: P.EMPTY,
499
+ };
500
+ // SegWit v0 stack of witness buffers
501
+ exports.RawWitness = P.array(CompactSizeLen, exports.VarBytes);
502
+ // https://en.bitcoin.it/wiki/Protocol_documentation#tx
503
+ const _RawTx = P.struct({
504
+ version: P.I32LE,
505
+ segwitFlag: P.flag(new Uint8Array([0x00, 0x01])),
506
+ inputs: (0, exports.BTCArray)(exports.RawInput),
507
+ outputs: (0, exports.BTCArray)(exports.RawOutput),
508
+ witnesses: P.flagged('segwitFlag', P.array('inputs/length', exports.RawWitness)),
509
+ // < 500000000 Block number at which this transaction is unlocked
510
+ // >= 500000000 UNIX timestamp at which this transaction is unlocked
511
+ // Handled as part of PSBTv2
512
+ lockTime: P.U32LE,
513
+ });
514
+ function validateRawTx(tx) {
515
+ if (tx.segwitFlag && tx.witnesses && !tx.witnesses.length)
516
+ throw new Error('Segwit flag with empty witnesses array');
517
+ return tx;
518
+ }
519
+ exports.RawTx = P.validate(_RawTx, validateRawTx);
520
+ function PSBTKeyInfo(info) {
521
+ const [type, kc, vc, reqInc, allowInc, silentIgnore] = info;
522
+ return { type, kc, vc, reqInc, allowInc, silentIgnore };
523
+ }
524
+ const BIP32Der = P.struct({
525
+ fingerprint: P.U32BE,
526
+ path: P.array(null, P.U32LE),
527
+ });
528
+ // Complex structure for PSBT fields
529
+ // <control byte with leaf version and parity bit> <internal key p> <C> <E> <AB>
530
+ const _TaprootControlBlock = P.struct({
531
+ version: P.U8, // With parity :(
532
+ internalKey: P.bytes(32),
533
+ merklePath: P.array(null, P.bytes(32)),
534
+ });
535
+ exports.TaprootControlBlock = P.validate(_TaprootControlBlock, (cb) => {
536
+ if (cb.merklePath.length > 128)
537
+ throw new Error('TaprootControlBlock: merklePath should be of length 0..128 (inclusive)');
538
+ return cb;
539
+ });
540
+ const TaprootBIP32Der = P.struct({
541
+ hashes: P.array(CompactSizeLen, P.bytes(32)),
542
+ der: BIP32Der,
543
+ });
544
+ // The 78 byte serialized extended public key as defined by BIP 32.
545
+ const GlobalXPUB = P.bytes(78);
546
+ const tapScriptSigKey = P.struct({ pubKey: PubKeySchnorr, leafHash: P.bytes(32) });
547
+ // {<8-bit uint depth> <8-bit uint leaf version> <compact size uint scriptlen> <bytes script>}*
548
+ const tapTree = P.array(null, P.struct({
549
+ depth: P.U8,
550
+ version: P.U8,
551
+ script: exports.VarBytes,
552
+ }));
553
+ const BytesInf = P.bytes(null); // Bytes will conflict with Bytes type
554
+ const Bytes20 = P.bytes(20);
555
+ const Bytes32 = P.bytes(32);
556
+ // versionsRequiringExclusing = !versionsAllowsInclusion (as set)
557
+ // {name: [tag, keyCoder, valueCoder, versionsRequiringInclusion, versionsRequiringExclusing, versionsAllowsInclusion, silentIgnore]}
558
+ // SilentIgnore: we use some v2 fields for v1 representation too, so we just clean them before serialize
559
+ // Tables from BIP-0174 (https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki)
560
+ // prettier-ignore
561
+ const PSBTGlobal = {
562
+ unsignedTx: [0x00, false, exports.RawTx, [0], [0], false],
563
+ xpub: [0x01, GlobalXPUB, BIP32Der, [], [0, 2], false],
564
+ txVersion: [0x02, false, P.U32LE, [2], [2], false],
565
+ fallbackLocktime: [0x03, false, P.U32LE, [], [2], false],
566
+ inputCount: [0x04, false, CompactSizeLen, [2], [2], false],
567
+ outputCount: [0x05, false, CompactSizeLen, [2], [2], false],
568
+ txModifiable: [0x06, false, P.U8, [], [2], false], // TODO: bitfield
569
+ version: [0xfb, false, P.U32LE, [], [0, 2], false],
570
+ proprietary: [0xfc, BytesInf, BytesInf, [], [0, 2], false],
571
+ };
572
+ // prettier-ignore
573
+ const PSBTInput = {
574
+ nonWitnessUtxo: [0x00, false, exports.RawTx, [], [0, 2], false],
575
+ witnessUtxo: [0x01, false, exports.RawOutput, [], [0, 2], false],
576
+ partialSig: [0x02, PubKeyECDSA, BytesInf, [], [0, 2], false],
577
+ sighashType: [0x03, false, P.U32LE, [], [0, 2], false],
578
+ redeemScript: [0x04, false, BytesInf, [], [0, 2], false],
579
+ witnessScript: [0x05, false, BytesInf, [], [0, 2], false],
580
+ bip32Derivation: [0x06, PubKeyECDSA, BIP32Der, [], [0, 2], false],
581
+ finalScriptSig: [0x07, false, BytesInf, [], [0, 2], false],
582
+ finalScriptWitness: [0x08, false, exports.RawWitness, [], [0, 2], false],
583
+ porCommitment: [0x09, false, BytesInf, [], [0, 2], false],
584
+ ripemd160: [0x0a, Bytes20, BytesInf, [], [0, 2], false],
585
+ sha256: [0x0b, Bytes32, BytesInf, [], [0, 2], false],
586
+ hash160: [0x0c, Bytes20, BytesInf, [], [0, 2], false],
587
+ hash256: [0x0d, Bytes32, BytesInf, [], [0, 2], false],
588
+ txid: [0x0e, false, Bytes32, [2], [2], true],
589
+ index: [0x0f, false, P.U32LE, [2], [2], true],
590
+ sequence: [0x10, false, P.U32LE, [], [2], true],
591
+ requiredTimeLocktime: [0x11, false, P.U32LE, [], [2], false],
592
+ requiredHeightLocktime: [0x12, false, P.U32LE, [], [2], false],
593
+ tapKeySig: [0x13, false, SignatureSchnorr, [], [0, 2], false],
594
+ tapScriptSig: [0x14, tapScriptSigKey, SignatureSchnorr, [], [0, 2], false],
595
+ tapLeafScript: [0x15, exports.TaprootControlBlock, BytesInf, [], [0, 2], false],
596
+ tapBip32Derivation: [0x16, Bytes32, TaprootBIP32Der, [], [0, 2], false],
597
+ tapInternalKey: [0x17, false, PubKeySchnorr, [], [0, 2], false],
598
+ tapMerkleRoot: [0x18, false, Bytes32, [], [0, 2], false],
599
+ proprietary: [0xfc, BytesInf, BytesInf, [], [0, 2], false],
600
+ };
601
+ // All other keys removed when finalizing
602
+ const PSBTInputFinalKeys = [
603
+ 'txid',
604
+ 'sequence',
605
+ 'index',
606
+ 'witnessUtxo',
607
+ 'nonWitnessUtxo',
608
+ 'finalScriptSig',
609
+ 'finalScriptWitness',
610
+ 'unknown',
611
+ ];
612
+ // Can be modified even on signed input
613
+ const PSBTInputUnsignedKeys = [
614
+ 'partialSig',
615
+ 'finalScriptSig',
616
+ 'finalScriptWitness',
617
+ 'tapKeySig',
618
+ 'tapScriptSig',
619
+ ];
620
+ // prettier-ignore
621
+ const PSBTOutput = {
622
+ redeemScript: [0x00, false, BytesInf, [], [0, 2], false],
623
+ witnessScript: [0x01, false, BytesInf, [], [0, 2], false],
624
+ bip32Derivation: [0x02, PubKeyECDSA, BIP32Der, [], [0, 2], false],
625
+ amount: [0x03, false, P.I64LE, [2], [2], true],
626
+ script: [0x04, false, BytesInf, [2], [2], true],
627
+ tapInternalKey: [0x05, false, PubKeySchnorr, [], [0, 2], false],
628
+ tapTree: [0x06, false, tapTree, [], [0, 2], false],
629
+ tapBip32Derivation: [0x07, PubKeySchnorr, TaprootBIP32Der, [], [0, 2], false],
630
+ proprietary: [0xfc, BytesInf, BytesInf, [], [0, 2], false],
631
+ };
632
+ // Can be modified even on signed input
633
+ const PSBTOutputUnsignedKeys = [];
634
+ const PSBTKeyPair = P.array(P.NULL, P.struct({
635
+ // <key> := <keylen> <keytype> <keydata> WHERE keylen = len(keytype)+len(keydata)
636
+ key: P.prefix(CompactSizeLen, P.struct({ type: CompactSizeLen, key: P.bytes(null) })),
637
+ // <value> := <valuelen> <valuedata>
638
+ value: P.bytes(CompactSizeLen),
639
+ }));
640
+ const PSBTUnknownKey = P.struct({ type: CompactSizeLen, key: P.bytes(null) });
641
+ // Key cannot be 'unknown', value coder cannot be array for elements with empty key
642
+ function PSBTKeyMap(psbtEnum) {
643
+ // -> Record<type, [keyName, ...coders]>
644
+ const byType = {};
645
+ for (const k in psbtEnum) {
646
+ const [num, kc, vc] = psbtEnum[k];
647
+ byType[num] = [k, kc, vc];
648
+ }
649
+ return P.wrap({
650
+ encodeStream: (w, value) => {
651
+ let out = [];
652
+ // Because we use order of psbtEnum, keymap is sorted here
653
+ for (const name in psbtEnum) {
654
+ const val = value[name];
655
+ if (val === undefined)
656
+ continue;
657
+ const [type, kc, vc] = psbtEnum[name];
658
+ if (!kc) {
659
+ out.push({ key: { type, key: P.EMPTY }, value: vc.encode(val) });
660
+ }
661
+ else {
662
+ // Low level interface, returns keys as is (with duplicates). Useful for debug
663
+ const kv = val.map(([k, v]) => [
664
+ kc.encode(k),
665
+ vc.encode(v),
666
+ ]);
667
+ // sort by keys
668
+ kv.sort((a, b) => _cmpBytes(a[0], b[0]));
669
+ for (const [key, value] of kv)
670
+ out.push({ key: { key, type }, value });
671
+ }
672
+ }
673
+ if (value.unknown) {
674
+ value.unknown.sort((a, b) => _cmpBytes(a[0].key, b[0].key));
675
+ for (const [k, v] of value.unknown)
676
+ out.push({ key: k, value: v });
677
+ }
678
+ PSBTKeyPair.encodeStream(w, out);
679
+ },
680
+ decodeStream: (r) => {
681
+ const raw = PSBTKeyPair.decodeStream(r);
682
+ const out = {};
683
+ const noKey = {};
684
+ for (const elm of raw) {
685
+ let name = 'unknown';
686
+ let key = elm.key.key;
687
+ let value = elm.value;
688
+ if (byType[elm.key.type]) {
689
+ const [_name, kc, vc] = byType[elm.key.type];
690
+ name = _name;
691
+ if (!kc && key.length) {
692
+ throw new Error(`PSBT: Non-empty key for ${name} (key=${base_1.hex.encode(key)} value=${base_1.hex.encode(value)}`);
693
+ }
694
+ key = kc ? kc.decode(key) : undefined;
695
+ value = vc.decode(value);
696
+ if (!kc) {
697
+ if (out[name])
698
+ throw new Error(`PSBT: Same keys: ${name} (key=${key} value=${value})`);
699
+ out[name] = value;
700
+ noKey[name] = true;
701
+ continue;
702
+ }
703
+ }
704
+ else {
705
+ // For unknown: add key type inside key
706
+ key = { type: elm.key.type, key: elm.key.key };
707
+ }
708
+ // Only keyed elements at this point
709
+ if (noKey[name])
710
+ throw new Error(`PSBT: Key type with empty key and no key=${name} val=${value}`);
711
+ if (!out[name])
712
+ out[name] = [];
713
+ out[name].push([key, value]);
714
+ }
715
+ return out;
716
+ },
717
+ });
718
+ }
719
+ // Basic sanity check for scripts
720
+ function checkWSH(s, witnessScript) {
721
+ if (!P.equalBytes(s.hash, (0, sha256_1.sha256)(witnessScript)))
722
+ throw new Error('checkScript: wsh wrong witnessScript hash');
723
+ const w = exports.OutScript.decode(witnessScript);
724
+ if (w.type === 'tr' || w.type === 'tr_ns' || w.type === 'tr_ms')
725
+ throw new Error(`checkScript: P2${w.type} cannot be wrapped in P2SH`);
726
+ if (w.type === 'wpkh' || w.type === 'sh')
727
+ throw new Error(`checkScript: P2${w.type} cannot be wrapped in P2WSH`);
728
+ }
729
+ function checkScript(script, redeemScript, witnessScript) {
730
+ if (script) {
731
+ const s = exports.OutScript.decode(script);
732
+ // ms||pk maybe work, but there will be no address, hard to spend
733
+ if (s.type === 'tr_ns' || s.type === 'tr_ms' || s.type === 'ms' || s.type == 'pk')
734
+ throw new Error(`checkScript: non-wrapped ${s.type}`);
735
+ if (s.type === 'sh' && redeemScript) {
736
+ if (!P.equalBytes(s.hash, hash160(redeemScript)))
737
+ throw new Error('checkScript: sh wrong redeemScript hash');
738
+ const r = exports.OutScript.decode(redeemScript);
739
+ if (r.type === 'tr' || r.type === 'tr_ns' || r.type === 'tr_ms')
740
+ throw new Error(`checkScript: P2${r.type} cannot be wrapped in P2SH`);
741
+ // Not sure if this unspendable, but we cannot represent this via PSBT
742
+ if (r.type === 'sh')
743
+ throw new Error('checkScript: P2SH cannot be wrapped in P2SH');
744
+ }
745
+ if (s.type === 'wsh' && witnessScript)
746
+ checkWSH(s, witnessScript);
747
+ }
748
+ if (redeemScript) {
749
+ const r = exports.OutScript.decode(redeemScript);
750
+ if (r.type === 'wsh' && witnessScript)
751
+ checkWSH(r, witnessScript);
752
+ }
753
+ }
754
+ const PSBTInputCoder = P.validate(PSBTKeyMap(PSBTInput), (i) => {
755
+ if (i.finalScriptWitness && !i.finalScriptWitness.length)
756
+ throw new Error('validateInput: wmpty finalScriptWitness');
757
+ //if (i.finalScriptSig && !i.finalScriptSig.length) throw new Error('validateInput: empty finalScriptSig');
758
+ if (i.partialSig && !i.partialSig.length)
759
+ throw new Error('Empty partialSig');
760
+ if (i.partialSig)
761
+ for (const [k] of i.partialSig)
762
+ validatePubkey(k, PubT.ecdsa);
763
+ if (i.bip32Derivation)
764
+ for (const [k] of i.bip32Derivation)
765
+ validatePubkey(k, PubT.ecdsa);
766
+ // Locktime = unsigned little endian integer greater than or equal to 500000000 representing
767
+ if (i.requiredTimeLocktime !== undefined && i.requiredTimeLocktime < 500000000)
768
+ throw new Error(`validateInput: wrong timeLocktime=${i.requiredTimeLocktime}`);
769
+ // unsigned little endian integer greater than 0 and less than 500000000
770
+ if (i.requiredHeightLocktime !== undefined &&
771
+ (i.requiredHeightLocktime <= 0 || i.requiredHeightLocktime >= 500000000))
772
+ throw new Error(`validateInput: wrong heighLocktime=${i.requiredHeightLocktime}`);
773
+ if (i.nonWitnessUtxo && i.index !== undefined) {
774
+ const last = i.nonWitnessUtxo.outputs.length - 1;
775
+ if (i.index > last)
776
+ throw new Error(`validateInput: index(${i.index}) not in nonWitnessUtxo`);
777
+ const prevOut = i.nonWitnessUtxo.outputs[i.index];
778
+ if (i.witnessUtxo &&
779
+ (!P.equalBytes(i.witnessUtxo.script, prevOut.script) ||
780
+ i.witnessUtxo.amount !== prevOut.amount))
781
+ throw new Error('validateInput: witnessUtxo different from nonWitnessUtxo');
782
+ }
783
+ if (i.tapLeafScript) {
784
+ // tap leaf version appears here twice: in control block and at the end of script
785
+ for (const [k, v] of i.tapLeafScript) {
786
+ if ((k.version & 254) !== v[v.length - 1])
787
+ throw new Error('validateInput: tapLeafScript version mimatch');
788
+ if (v[v.length - 1] & 1)
789
+ throw new Error('validateInput: tapLeafScript version has parity bit!');
790
+ }
791
+ }
792
+ // Validate txid for nonWitnessUtxo is correct
793
+ if (i.nonWitnessUtxo && i.index && i.txid) {
794
+ const outputs = i.nonWitnessUtxo.outputs;
795
+ if (outputs.length - 1 < i.index)
796
+ throw new Error('nonWitnessUtxo: incorect output index');
797
+ const tx = Transaction.fromRaw(exports.RawTx.encode(i.nonWitnessUtxo));
798
+ const txid = base_1.hex.encode(i.txid);
799
+ if (tx.id !== txid)
800
+ throw new Error(`nonWitnessUtxo: wrong txid, exp=${txid} got=${tx.id}`);
801
+ }
802
+ return i;
803
+ });
804
+ const PSBTOutputCoder = P.validate(PSBTKeyMap(PSBTOutput), (o) => {
805
+ if (o.bip32Derivation)
806
+ for (const [k] of o.bip32Derivation)
807
+ validatePubkey(k, PubT.ecdsa);
808
+ return o;
809
+ });
810
+ const PSBTGlobalCoder = P.validate(PSBTKeyMap(PSBTGlobal), (g) => {
811
+ const version = g.version || 0;
812
+ if (version === 0) {
813
+ if (!g.unsignedTx)
814
+ throw new Error('PSBTv0: missing unsignedTx');
815
+ if (g.unsignedTx.segwitFlag || g.unsignedTx.witnesses)
816
+ throw new Error('PSBTv0: witness in unsingedTx');
817
+ for (const inp of g.unsignedTx.inputs)
818
+ if (inp.finalScriptSig && inp.finalScriptSig.length)
819
+ throw new Error('PSBTv0: input scriptSig found in unsignedTx');
820
+ }
821
+ return g;
822
+ });
823
+ exports._RawPSBTV0 = P.struct({
824
+ magic: P.magic(P.string(new Uint8Array([0xff])), 'psbt'),
825
+ global: PSBTGlobalCoder,
826
+ inputs: P.array('global/unsignedTx/inputs/length', PSBTInputCoder),
827
+ outputs: P.array(null, PSBTOutputCoder),
828
+ });
829
+ exports._RawPSBTV2 = P.struct({
830
+ magic: P.magic(P.string(new Uint8Array([0xff])), 'psbt'),
831
+ global: PSBTGlobalCoder,
832
+ inputs: P.array('global/inputCount', PSBTInputCoder),
833
+ outputs: P.array('global/outputCount', PSBTOutputCoder),
834
+ });
835
+ exports._DebugPSBT = P.struct({
836
+ magic: P.magic(P.string(new Uint8Array([0xff])), 'psbt'),
837
+ items: P.array(null, P.apply(P.array(P.NULL, P.tuple([P.hex(CompactSizeLen), P.bytes(exports.CompactSize)])), P.coders.dict())),
838
+ });
839
+ function validatePSBTFields(version, info, lst) {
840
+ for (const k in lst) {
841
+ if (k === 'unknown')
842
+ continue;
843
+ if (!info[k])
844
+ continue;
845
+ const { allowInc } = PSBTKeyInfo(info[k]);
846
+ if (!allowInc.includes(version))
847
+ throw new Error(`PSBTv${version}: field ${k} is not allowed`);
848
+ }
849
+ for (const k in info) {
850
+ const { reqInc } = PSBTKeyInfo(info[k]);
851
+ if (reqInc.includes(version) && lst[k] === undefined)
852
+ throw new Error(`PSBTv${version}: missing required field ${k}`);
853
+ }
854
+ }
855
+ function cleanPSBTFields(version, info, lst) {
856
+ const out = {};
857
+ for (const _k in lst) {
858
+ const k = _k;
859
+ if (k !== 'unknown') {
860
+ if (!info[k])
861
+ continue;
862
+ const { allowInc, silentIgnore } = PSBTKeyInfo(info[k]);
863
+ if (!allowInc.includes(version)) {
864
+ if (silentIgnore)
865
+ continue;
866
+ throw new Error(`Failed to serialize in PSBTv${version}: ${k} but versions allows inclusion=${allowInc}`);
867
+ }
868
+ }
869
+ out[k] = lst[k];
870
+ }
871
+ return out;
872
+ }
873
+ function validatePSBT(tx) {
874
+ const version = (tx && tx.global && tx.global.version) || 0;
875
+ validatePSBTFields(version, PSBTGlobal, tx.global);
876
+ for (const i of tx.inputs)
877
+ validatePSBTFields(version, PSBTInput, i);
878
+ for (const o of tx.outputs)
879
+ validatePSBTFields(version, PSBTOutput, o);
880
+ // We allow only one empty element at the end of map (compat with bitcoinjs-lib bug)
881
+ const inputCount = !version ? tx.global.unsignedTx.inputs.length : tx.global.inputCount;
882
+ if (tx.inputs.length < inputCount)
883
+ throw new Error('Not enough inputs');
884
+ const inputsLeft = tx.inputs.slice(inputCount);
885
+ if (inputsLeft.length > 1 || (inputsLeft.length && Object.keys(inputsLeft[0]).length))
886
+ throw new Error(`Unexpected inputs left in tx=${inputsLeft}`);
887
+ // Same for inputs
888
+ const outputCount = !version ? tx.global.unsignedTx.outputs.length : tx.global.outputCount;
889
+ if (tx.outputs.length < outputCount)
890
+ throw new Error('Not outputs inputs');
891
+ const outputsLeft = tx.outputs.slice(outputCount);
892
+ if (outputsLeft.length > 1 || (outputsLeft.length && Object.keys(outputsLeft[0]).length))
893
+ throw new Error(`Unexpected outputs left in tx=${outputsLeft}`);
894
+ return tx;
895
+ }
896
+ function mergeKeyMap(psbtEnum, val, cur, allowedFields) {
897
+ const res = { ...cur, ...val };
898
+ // All arguments can be provided as hex
899
+ for (const k in psbtEnum) {
900
+ const key = k;
901
+ const [_, kC, vC] = psbtEnum[key];
902
+ const cannotChange = allowedFields && !allowedFields.includes(k);
903
+ if (val[k] === undefined && k in val) {
904
+ if (cannotChange)
905
+ throw new Error(`Cannot remove signed field=${k}`);
906
+ delete res[k];
907
+ }
908
+ else if (kC) {
909
+ const oldKV = (cur && cur[k] ? cur[k] : []);
910
+ let newKV = val[key];
911
+ if (newKV) {
912
+ if (!Array.isArray(newKV))
913
+ throw new Error(`keyMap(${k}): KV pairs should be [k, v][]`);
914
+ // Decode hex in k-v
915
+ newKV = newKV.map((val) => {
916
+ if (val.length !== 2)
917
+ throw new Error(`keyMap(${k}): KV pairs should be [k, v][]`);
918
+ return [
919
+ typeof val[0] === 'string' ? kC.decode(base_1.hex.decode(val[0])) : val[0],
920
+ typeof val[1] === 'string' ? vC.decode(base_1.hex.decode(val[1])) : val[1],
921
+ ];
922
+ });
923
+ const map = {};
924
+ const add = (kStr, k, v) => {
925
+ if (map[kStr] === undefined) {
926
+ map[kStr] = [k, v];
927
+ return;
928
+ }
929
+ const oldVal = base_1.hex.encode(vC.encode(map[kStr][1]));
930
+ const newVal = base_1.hex.encode(vC.encode(v));
931
+ if (oldVal !== newVal)
932
+ throw new Error(`keyMap(${key}): same key=${kStr} oldVal=${oldVal} newVal=${newVal}`);
933
+ };
934
+ for (const [k, v] of oldKV) {
935
+ const kStr = base_1.hex.encode(kC.encode(k));
936
+ add(kStr, k, v);
937
+ }
938
+ for (const [k, v] of newKV) {
939
+ const kStr = base_1.hex.encode(kC.encode(k));
940
+ // undefined removes previous value
941
+ if (v === undefined) {
942
+ if (cannotChange)
943
+ throw new Error(`Cannot remove signed field=${key}/${k}`);
944
+ delete map[kStr];
945
+ }
946
+ else
947
+ add(kStr, k, v);
948
+ }
949
+ res[key] = Object.values(map);
950
+ }
951
+ }
952
+ else if (typeof res[k] === 'string') {
953
+ res[k] = vC.decode(base_1.hex.decode(res[k]));
954
+ }
955
+ else if (cannotChange && k in val && cur && cur[k] !== undefined) {
956
+ if (!P.equalBytes(vC.encode(val[k]), vC.encode(cur[k])))
957
+ throw new Error(`Cannot change signed field=${k}`);
958
+ }
959
+ }
960
+ // Remove unknown keys
961
+ for (const k in res)
962
+ if (!psbtEnum[k])
963
+ delete res[k];
964
+ return res;
965
+ }
966
+ exports.RawPSBTV0 = P.validate(exports._RawPSBTV0, validatePSBT);
967
+ exports.RawPSBTV2 = P.validate(exports._RawPSBTV2, validatePSBT);
968
+ // (TxHash, Idx)
969
+ const TxHashIdx = P.struct({ txid: P.bytes(32, true), index: P.U32LE });
970
+ const OutPK = {
971
+ encode(from) {
972
+ if (from.length !== 2 ||
973
+ !isBytes(from[0]) ||
974
+ !isValidPubkey(from[0], PubT.ecdsa) ||
975
+ from[1] !== 'CHECKSIG')
976
+ return;
977
+ return { type: 'pk', pubkey: from[0] };
978
+ },
979
+ decode: (to) => (to.type === 'pk' ? [to.pubkey, 'CHECKSIG'] : undefined),
980
+ };
981
+ // @ts-ignore
982
+ const p2pk = (pubkey, network = exports.NETWORK) => {
983
+ // network is unused
984
+ if (!isValidPubkey(pubkey, PubT.ecdsa))
985
+ throw new Error('P2PK: invalid publicKey');
986
+ return {
987
+ type: 'pk',
988
+ script: exports.OutScript.encode({ type: 'pk', pubkey }),
989
+ };
990
+ };
991
+ exports.p2pk = p2pk;
992
+ const OutPKH = {
993
+ encode(from) {
994
+ if (from.length !== 5 || from[0] !== 'DUP' || from[1] !== 'HASH160' || !isBytes(from[2]))
995
+ return;
996
+ if (from[3] !== 'EQUALVERIFY' || from[4] !== 'CHECKSIG')
997
+ return;
998
+ return { type: 'pkh', hash: from[2] };
999
+ },
1000
+ decode: (to) => to.type === 'pkh' ? ['DUP', 'HASH160', to.hash, 'EQUALVERIFY', 'CHECKSIG'] : undefined,
1001
+ };
1002
+ const p2pkh = (publicKey, network = exports.NETWORK) => {
1003
+ if (!isValidPubkey(publicKey, PubT.ecdsa))
1004
+ throw new Error('P2PKH: invalid publicKey');
1005
+ const hash = hash160(publicKey);
1006
+ return {
1007
+ type: 'pkh',
1008
+ script: exports.OutScript.encode({ type: 'pkh', hash }),
1009
+ address: Address(network).encode({ type: 'pkh', hash }),
1010
+ };
1011
+ };
1012
+ exports.p2pkh = p2pkh;
1013
+ const OutSH = {
1014
+ encode(from) {
1015
+ if (from.length !== 3 || from[0] !== 'HASH160' || !isBytes(from[1]) || from[2] !== 'EQUAL')
1016
+ return;
1017
+ return { type: 'sh', hash: from[1] };
1018
+ },
1019
+ decode: (to) => to.type === 'sh' ? ['HASH160', to.hash, 'EQUAL'] : undefined,
1020
+ };
1021
+ const p2sh = (child, network = exports.NETWORK) => {
1022
+ // It is already tested inside noble-hashes and checkScript
1023
+ const cs = child.script;
1024
+ if (!isBytes(cs))
1025
+ throw new Error(`Wrong script: ${typeof child.script}, expected Uint8Array`);
1026
+ const hash = hash160(cs);
1027
+ const script = exports.OutScript.encode({ type: 'sh', hash });
1028
+ checkScript(script, cs, child.witnessScript);
1029
+ const res = {
1030
+ type: 'sh',
1031
+ redeemScript: cs,
1032
+ script: exports.OutScript.encode({ type: 'sh', hash }),
1033
+ address: Address(network).encode({ type: 'sh', hash }),
1034
+ };
1035
+ if (child.witnessScript)
1036
+ res.witnessScript = child.witnessScript;
1037
+ return res;
1038
+ };
1039
+ exports.p2sh = p2sh;
1040
+ const OutWSH = {
1041
+ encode(from) {
1042
+ if (from.length !== 2 || from[0] !== 0 || !isBytes(from[1]))
1043
+ return;
1044
+ if (from[1].length !== 32)
1045
+ return;
1046
+ return { type: 'wsh', hash: from[1] };
1047
+ },
1048
+ decode: (to) => (to.type === 'wsh' ? [0, to.hash] : undefined),
1049
+ };
1050
+ const p2wsh = (child, network = exports.NETWORK) => {
1051
+ const cs = child.script;
1052
+ if (!isBytes(cs))
1053
+ throw new Error(`Wrong script: ${typeof cs}, expected Uint8Array`);
1054
+ const hash = (0, sha256_1.sha256)(cs);
1055
+ const script = exports.OutScript.encode({ type: 'wsh', hash });
1056
+ checkScript(script, undefined, cs);
1057
+ return {
1058
+ type: 'wsh',
1059
+ witnessScript: cs,
1060
+ script: exports.OutScript.encode({ type: 'wsh', hash }),
1061
+ address: Address(network).encode({ type: 'wsh', hash }),
1062
+ };
1063
+ };
1064
+ exports.p2wsh = p2wsh;
1065
+ const OutWPKH = {
1066
+ encode(from) {
1067
+ if (from.length !== 2 || from[0] !== 0 || !isBytes(from[1]))
1068
+ return;
1069
+ if (from[1].length !== 20)
1070
+ return;
1071
+ return { type: 'wpkh', hash: from[1] };
1072
+ },
1073
+ decode: (to) => (to.type === 'wpkh' ? [0, to.hash] : undefined),
1074
+ };
1075
+ const p2wpkh = (publicKey, network = exports.NETWORK) => {
1076
+ if (!isValidPubkey(publicKey, PubT.ecdsa))
1077
+ throw new Error('P2WPKH: invalid publicKey');
1078
+ if (publicKey.length === 65)
1079
+ throw new Error('P2WPKH: uncompressed public key');
1080
+ const hash = hash160(publicKey);
1081
+ return {
1082
+ type: 'wpkh',
1083
+ script: exports.OutScript.encode({ type: 'wpkh', hash }),
1084
+ address: Address(network).encode({ type: 'wpkh', hash }),
1085
+ };
1086
+ };
1087
+ exports.p2wpkh = p2wpkh;
1088
+ const OutMS = {
1089
+ encode(from) {
1090
+ const last = from.length - 1;
1091
+ if (from[last] !== 'CHECKMULTISIG')
1092
+ return;
1093
+ const m = from[0];
1094
+ const n = from[last - 1];
1095
+ if (typeof m !== 'number' || typeof n !== 'number')
1096
+ return;
1097
+ const pubkeys = from.slice(1, -2);
1098
+ if (n !== pubkeys.length)
1099
+ return;
1100
+ for (const pub of pubkeys)
1101
+ if (!isBytes(pub))
1102
+ return;
1103
+ return { type: 'ms', m, pubkeys: pubkeys }; // we don't need n, since it is the same as pubkeys
1104
+ },
1105
+ // checkmultisig(n, ..pubkeys, m)
1106
+ decode: (to) => to.type === 'ms' ? [to.m, ...to.pubkeys, to.pubkeys.length, 'CHECKMULTISIG'] : undefined,
1107
+ };
1108
+ const p2ms = (m, pubkeys, allowSamePubkeys = false) => {
1109
+ if (!allowSamePubkeys)
1110
+ uniqPubkey(pubkeys);
1111
+ return { type: 'ms', script: exports.OutScript.encode({ type: 'ms', pubkeys, m }) };
1112
+ };
1113
+ exports.p2ms = p2ms;
1114
+ const OutTR = {
1115
+ encode(from) {
1116
+ if (from.length !== 2 || from[0] !== 1 || !isBytes(from[1]))
1117
+ return;
1118
+ return { type: 'tr', pubkey: from[1] };
1119
+ },
1120
+ decode: (to) => (to.type === 'tr' ? [1, to.pubkey] : undefined),
1121
+ };
1122
+ // Helper for generating binary tree from list, with weights
1123
+ function taprootListToTree(taprootList) {
1124
+ // Clone input in order to not corrupt it
1125
+ const lst = Array.from(taprootList);
1126
+ // We have at least 2 elements => can create branch
1127
+ while (lst.length >= 2) {
1128
+ // Sort: elements with smallest weight are in the end of queue
1129
+ lst.sort((a, b) => (b.weight || 1) - (a.weight || 1));
1130
+ const b = lst.pop();
1131
+ const a = lst.pop();
1132
+ const weight = (a?.weight || 1) + (b?.weight || 1);
1133
+ lst.push({
1134
+ weight,
1135
+ // Unwrap children array
1136
+ // TODO: Very hard to remove any here
1137
+ childs: [a?.childs || a, b?.childs || b],
1138
+ });
1139
+ }
1140
+ // At this point there is always 1 element in lst
1141
+ const last = lst[0];
1142
+ return (last?.childs || last);
1143
+ }
1144
+ exports.taprootListToTree = taprootListToTree;
1145
+ function checkTaprootScript(script, internalPubKey, allowUnknownOutputs = false) {
1146
+ const out = exports.OutScript.decode(script);
1147
+ if (out.type === 'unknown' && allowUnknownOutputs)
1148
+ return;
1149
+ if (!['tr_ns', 'tr_ms'].includes(out.type))
1150
+ throw new Error(`P2TR: invalid leaf script=${out.type}`);
1151
+ const outms = out;
1152
+ if (!allowUnknownOutputs && outms.pubkeys) {
1153
+ for (const p of outms.pubkeys) {
1154
+ if (P.equalBytes(p, exports.TAPROOT_UNSPENDABLE_KEY))
1155
+ throw new Error('Unspendable taproot key in leaf script');
1156
+ // It's likely a mistake at this point:
1157
+ // 1. p2tr(A, p2tr_ns(2, [A, B])) == p2tr(A, p2tr_pk(B)) (A or B key)
1158
+ // but will take more space and fees.
1159
+ // 2. For multi-sig p2tr(A, p2tr_ns(2, [A, B, C])) it's probably a security issue:
1160
+ // User creates 2 of 3 multisig of keys [A, B, C],
1161
+ // but key A always can spend whole output without signatures from other keys.
1162
+ // p2tr(A, p2tr_ns(2, [B, C, D])) is ok: A or (B and C) or (B and D) or (C and D)
1163
+ if (P.equalBytes(p, internalPubKey)) {
1164
+ throw new Error('Using P2TR with leaf script with same key as internal key is not supported');
1165
+ }
1166
+ }
1167
+ }
1168
+ }
1169
+ function taprootHashTree(tree, internalPubKey, allowUnknownOutputs = false) {
1170
+ if (!tree)
1171
+ throw new Error('taprootHashTree: empty tree');
1172
+ if (Array.isArray(tree) && tree.length === 1)
1173
+ tree = tree[0];
1174
+ // Terminal node (leaf)
1175
+ if (!Array.isArray(tree)) {
1176
+ const { leafVersion: version, script: leafScript } = tree;
1177
+ // Earliest tree walk where we can validate tapScripts
1178
+ if (tree.tapLeafScript || (tree.tapMerkleRoot && !P.equalBytes(tree.tapMerkleRoot, P.EMPTY)))
1179
+ throw new Error('P2TR: tapRoot leafScript cannot have tree');
1180
+ const script = typeof leafScript === 'string' ? base_1.hex.decode(leafScript) : leafScript;
1181
+ if (!isBytes(script))
1182
+ throw new Error(`checkScript: wrong script type=${script}`);
1183
+ checkTaprootScript(script, internalPubKey, allowUnknownOutputs);
1184
+ return {
1185
+ type: 'leaf',
1186
+ version,
1187
+ script,
1188
+ hash: (0, exports.tapLeafHash)(script, version),
1189
+ };
1190
+ }
1191
+ // If tree / branch is not binary tree, convert it
1192
+ if (tree.length !== 2)
1193
+ tree = taprootListToTree(tree);
1194
+ if (tree.length !== 2)
1195
+ throw new Error('hashTree: non binary tree!');
1196
+ // branch
1197
+ // Both nodes should exist
1198
+ const left = taprootHashTree(tree[0], internalPubKey, allowUnknownOutputs);
1199
+ const right = taprootHashTree(tree[1], internalPubKey, allowUnknownOutputs);
1200
+ // We cannot swap left/right here, since it will change structure of tree
1201
+ let [lH, rH] = [left.hash, right.hash];
1202
+ if (_cmpBytes(rH, lH) === -1)
1203
+ [lH, rH] = [rH, lH];
1204
+ return { type: 'branch', left, right, hash: secp256k1_1.schnorr.utils.taggedHash('TapBranch', lH, rH) };
1205
+ }
1206
+ function taprootAddPath(tree, path = []) {
1207
+ if (!tree)
1208
+ throw new Error(`taprootAddPath: empty tree`);
1209
+ if (tree.type === 'leaf')
1210
+ return { ...tree, path };
1211
+ if (tree.type !== 'branch')
1212
+ throw new Error(`taprootAddPath: wrong type=${tree}`);
1213
+ return {
1214
+ ...tree,
1215
+ path,
1216
+ // Left element has right hash in path and otherwise
1217
+ left: taprootAddPath(tree.left, [tree.right.hash, ...path]),
1218
+ right: taprootAddPath(tree.right, [tree.left.hash, ...path]),
1219
+ };
1220
+ }
1221
+ function taprootWalkTree(tree) {
1222
+ if (!tree)
1223
+ throw new Error(`taprootAddPath: empty tree`);
1224
+ if (tree.type === 'leaf')
1225
+ return [tree];
1226
+ if (tree.type !== 'branch')
1227
+ throw new Error(`taprootWalkTree: wrong type=${tree}`);
1228
+ return [...taprootWalkTree(tree.left), ...taprootWalkTree(tree.right)];
1229
+ }
1230
+ // Another stupid decision, where lack of standard affects security.
1231
+ // Multisig needs to be generated with some key.
1232
+ // We are using approach from BIP 341/bitcoinjs-lib: SHA256(uncompressedDER(SECP256K1_GENERATOR_POINT))
1233
+ // It is possible to switch SECP256K1_GENERATOR_POINT with some random point;
1234
+ // but it's too complex to prove.
1235
+ // Also used by bitcoin-core and bitcoinjs-lib
1236
+ exports.TAPROOT_UNSPENDABLE_KEY = (0, sha256_1.sha256)(ProjPoint.BASE.toRawBytes(false));
1237
+ // Works as key OR tree.
1238
+ // If we only have tree, need to add unspendable key, otherwise
1239
+ // complex multisig wallet can be spent by owner of key only. See TAPROOT_UNSPENDABLE_KEY
1240
+ function p2tr(internalPubKey, tree, network = exports.NETWORK, allowUnknownOutputs = false) {
1241
+ // Unspendable
1242
+ if (!internalPubKey && !tree)
1243
+ throw new Error('p2tr: should have pubKey or scriptTree (or both)');
1244
+ const pubKey = typeof internalPubKey === 'string'
1245
+ ? base_1.hex.decode(internalPubKey)
1246
+ : internalPubKey || exports.TAPROOT_UNSPENDABLE_KEY;
1247
+ if (!isValidPubkey(pubKey, PubT.schnorr))
1248
+ throw new Error('p2tr: non-schnorr pubkey');
1249
+ let hashedTree = tree
1250
+ ? taprootAddPath(taprootHashTree(tree, pubKey, allowUnknownOutputs))
1251
+ : undefined;
1252
+ const tapMerkleRoot = hashedTree ? hashedTree.hash : undefined;
1253
+ const [tweakedPubkey, parity] = taprootTweakPubkey(pubKey, tapMerkleRoot || P.EMPTY);
1254
+ let leaves;
1255
+ if (hashedTree) {
1256
+ leaves = taprootWalkTree(hashedTree).map((l) => ({
1257
+ ...l,
1258
+ controlBlock: exports.TaprootControlBlock.encode({
1259
+ version: (l.version || exports.TAP_LEAF_VERSION) + parity,
1260
+ internalKey: pubKey,
1261
+ merklePath: l.path,
1262
+ }),
1263
+ }));
1264
+ }
1265
+ let tapLeafScript;
1266
+ if (leaves) {
1267
+ tapLeafScript = leaves.map((l) => [
1268
+ exports.TaprootControlBlock.decode(l.controlBlock),
1269
+ concat(l.script, new Uint8Array([l.version || exports.TAP_LEAF_VERSION])),
1270
+ ]);
1271
+ }
1272
+ const res = {
1273
+ type: 'tr',
1274
+ script: exports.OutScript.encode({ type: 'tr', pubkey: tweakedPubkey }),
1275
+ address: Address(network).encode({ type: 'tr', pubkey: tweakedPubkey }),
1276
+ // For tests
1277
+ tweakedPubkey,
1278
+ // PSBT stuff
1279
+ tapInternalKey: pubKey,
1280
+ };
1281
+ // Just in case someone would want to select a specific script
1282
+ if (leaves)
1283
+ res.leaves = leaves;
1284
+ if (tapLeafScript)
1285
+ res.tapLeafScript = tapLeafScript;
1286
+ if (tapMerkleRoot)
1287
+ res.tapMerkleRoot = tapMerkleRoot;
1288
+ return res;
1289
+ }
1290
+ exports.p2tr = p2tr;
1291
+ const OutTRNS = {
1292
+ encode(from) {
1293
+ const last = from.length - 1;
1294
+ if (from[last] !== 'CHECKSIG')
1295
+ return;
1296
+ const pubkeys = [];
1297
+ // On error return, since it can be different script
1298
+ for (let i = 0; i < last; i++) {
1299
+ const elm = from[i];
1300
+ if (i & 1) {
1301
+ if (elm !== 'CHECKSIGVERIFY' || i === last - 1)
1302
+ return;
1303
+ continue;
1304
+ }
1305
+ if (!isBytes(elm))
1306
+ return;
1307
+ pubkeys.push(elm);
1308
+ }
1309
+ return { type: 'tr_ns', pubkeys };
1310
+ },
1311
+ decode: (to) => {
1312
+ if (to.type !== 'tr_ns')
1313
+ return;
1314
+ const out = [];
1315
+ for (let i = 0; i < to.pubkeys.length - 1; i++)
1316
+ out.push(to.pubkeys[i], 'CHECKSIGVERIFY');
1317
+ out.push(to.pubkeys[to.pubkeys.length - 1], 'CHECKSIG');
1318
+ return out;
1319
+ },
1320
+ };
1321
+ // Returns all combinations of size M from lst
1322
+ function combinations(m, list) {
1323
+ const res = [];
1324
+ if (!Array.isArray(list))
1325
+ throw new Error('combinations: lst arg should be array');
1326
+ const n = list.length;
1327
+ if (m > n)
1328
+ throw new Error('combinations: m > lst.length, no combinations possible');
1329
+ /*
1330
+ Basically works as M nested loops like:
1331
+ for (;idx[0]<lst.length;idx[0]++) for (idx[1]=idx[0]+1;idx[1]<lst.length;idx[1]++)
1332
+ but since we cannot create nested loops dynamically, we unroll it to a single loop
1333
+ */
1334
+ const idx = Array.from({ length: m }, (_, i) => i);
1335
+ const last = idx.length - 1;
1336
+ main: for (;;) {
1337
+ res.push(idx.map((i) => list[i]));
1338
+ idx[last] += 1;
1339
+ let i = last;
1340
+ // Propagate increment
1341
+ // idx[i] cannot be bigger than n-m+i, otherwise last elements in right part will overflow
1342
+ for (; i >= 0 && idx[i] > n - m + i; i--) {
1343
+ idx[i] = 0;
1344
+ // Overflow in idx[0], break
1345
+ if (i === 0)
1346
+ break main;
1347
+ idx[i - 1] += 1;
1348
+ }
1349
+ // Propagate: idx[i+1] = idx[idx]+1
1350
+ for (i += 1; i < idx.length; i++)
1351
+ idx[i] = idx[i - 1] + 1;
1352
+ }
1353
+ return res;
1354
+ }
1355
+ exports.combinations = combinations;
1356
+ /**
1357
+ * M-of-N multi-leaf wallet via p2tr_ns. If m == n, single script is emitted.
1358
+ * Takes O(n^2) if m != n. 99-of-100 is ok, 5-of-100 is not.
1359
+ * `2-of-[A,B,C] => [A,B] | [A,C] | [B,C]`
1360
+ */
1361
+ const p2tr_ns = (m, pubkeys, allowSamePubkeys = false) => {
1362
+ if (!allowSamePubkeys)
1363
+ uniqPubkey(pubkeys);
1364
+ return combinations(m, pubkeys).map((i) => ({
1365
+ type: 'tr_ns',
1366
+ script: exports.OutScript.encode({ type: 'tr_ns', pubkeys: i }),
1367
+ }));
1368
+ };
1369
+ exports.p2tr_ns = p2tr_ns;
1370
+ // Taproot public key (case of p2tr_ns)
1371
+ const p2tr_pk = (pubkey) => (0, exports.p2tr_ns)(1, [pubkey], undefined)[0];
1372
+ exports.p2tr_pk = p2tr_pk;
1373
+ const OutTRMS = {
1374
+ encode(from) {
1375
+ const last = from.length - 1;
1376
+ if (from[last] !== 'NUMEQUAL' || from[1] !== 'CHECKSIG')
1377
+ return;
1378
+ const pubkeys = [];
1379
+ const m = OpToNum(from[last - 1]);
1380
+ if (typeof m !== 'number')
1381
+ return;
1382
+ for (let i = 0; i < last - 1; i++) {
1383
+ const elm = from[i];
1384
+ if (i & 1) {
1385
+ if (elm !== (i === 1 ? 'CHECKSIG' : 'CHECKSIGADD'))
1386
+ throw new Error('OutScript.encode/tr_ms: wrong element');
1387
+ continue;
1388
+ }
1389
+ if (!isBytes(elm))
1390
+ throw new Error('OutScript.encode/tr_ms: wrong key element');
1391
+ pubkeys.push(elm);
1392
+ }
1393
+ return { type: 'tr_ms', pubkeys, m };
1394
+ },
1395
+ decode: (to) => {
1396
+ if (to.type !== 'tr_ms')
1397
+ return;
1398
+ const out = [to.pubkeys[0], 'CHECKSIG'];
1399
+ for (let i = 1; i < to.pubkeys.length; i++)
1400
+ out.push(to.pubkeys[i], 'CHECKSIGADD');
1401
+ out.push(to.m, 'NUMEQUAL');
1402
+ return out;
1403
+ },
1404
+ };
1405
+ function p2tr_ms(m, pubkeys, allowSamePubkeys = false) {
1406
+ if (!allowSamePubkeys)
1407
+ uniqPubkey(pubkeys);
1408
+ return {
1409
+ type: 'tr_ms',
1410
+ script: exports.OutScript.encode({ type: 'tr_ms', pubkeys, m }),
1411
+ };
1412
+ }
1413
+ exports.p2tr_ms = p2tr_ms;
1414
+ const OutUnknown = {
1415
+ encode(from) {
1416
+ return { type: 'unknown', script: exports.Script.encode(from) };
1417
+ },
1418
+ decode: (to) => to.type === 'unknown' ? exports.Script.decode(to.script) : undefined,
1419
+ };
1420
+ // /Payments
1421
+ const OutScripts = [
1422
+ OutPK,
1423
+ OutPKH,
1424
+ OutSH,
1425
+ OutWSH,
1426
+ OutWPKH,
1427
+ OutMS,
1428
+ OutTR,
1429
+ OutTRNS,
1430
+ OutTRMS,
1431
+ OutUnknown,
1432
+ ];
1433
+ // TODO: we can support user supplied output scripts now
1434
+ // - addOutScript
1435
+ // - removeOutScript
1436
+ // - We can do that as log we modify array in-place
1437
+ // - Actually is very hard, since there is sign/finalize logic
1438
+ const _OutScript = P.apply(exports.Script, P.coders.match(OutScripts));
1439
+ // We can validate this once, because of packed & coders
1440
+ exports.OutScript = P.validate(_OutScript, (i) => {
1441
+ if (i.type === 'pk' && !isValidPubkey(i.pubkey, PubT.ecdsa))
1442
+ throw new Error('OutScript/pk: wrong key');
1443
+ if ((i.type === 'pkh' || i.type === 'sh' || i.type === 'wpkh') &&
1444
+ (!isBytes(i.hash) || i.hash.length !== 20))
1445
+ throw new Error(`OutScript/${i.type}: wrong hash`);
1446
+ if (i.type === 'wsh' && (!isBytes(i.hash) || i.hash.length !== 32))
1447
+ throw new Error(`OutScript/wsh: wrong hash`);
1448
+ if (i.type === 'tr' && (!isBytes(i.pubkey) || !isValidPubkey(i.pubkey, PubT.schnorr)))
1449
+ throw new Error('OutScript/tr: wrong taproot public key');
1450
+ if (i.type === 'ms' || i.type === 'tr_ns' || i.type === 'tr_ms')
1451
+ if (!Array.isArray(i.pubkeys))
1452
+ throw new Error('OutScript/multisig: wrong pubkeys array');
1453
+ if (i.type === 'ms') {
1454
+ const n = i.pubkeys.length;
1455
+ for (const p of i.pubkeys)
1456
+ if (!isValidPubkey(p, PubT.ecdsa))
1457
+ throw new Error('OutScript/multisig: wrong pubkey');
1458
+ if (i.m <= 0 || n > 16 || i.m > n)
1459
+ throw new Error('OutScript/multisig: invalid params');
1460
+ }
1461
+ if (i.type === 'tr_ns' || i.type === 'tr_ms') {
1462
+ for (const p of i.pubkeys)
1463
+ if (!isValidPubkey(p, PubT.schnorr))
1464
+ throw new Error(`OutScript/${i.type}: wrong pubkey`);
1465
+ }
1466
+ if (i.type === 'tr_ms') {
1467
+ const n = i.pubkeys.length;
1468
+ if (i.m <= 0 || n > 999 || i.m > n)
1469
+ throw new Error('OutScript/tr_ms: invalid params');
1470
+ }
1471
+ return i;
1472
+ });
1473
+ // Address
1474
+ function validateWitness(version, data) {
1475
+ if (data.length < 2 || data.length > 40)
1476
+ throw new Error('Witness: invalid length');
1477
+ if (version > 16)
1478
+ throw new Error('Witness: invalid version');
1479
+ if (version === 0 && !(data.length === 20 || data.length === 32))
1480
+ throw new Error('Witness: invalid length for version');
1481
+ }
1482
+ function programToWitness(version, data, network = exports.NETWORK) {
1483
+ validateWitness(version, data);
1484
+ const coder = version === 0 ? base_1.bech32 : base_1.bech32m;
1485
+ return coder.encode(network.bech32, [version].concat(coder.toWords(data)));
1486
+ }
1487
+ exports.programToWitness = programToWitness;
1488
+ function formatKey(hashed, prefix) {
1489
+ return exports.base58check.encode(concat(Uint8Array.from(prefix), hashed));
1490
+ }
1491
+ function WIF(network = exports.NETWORK) {
1492
+ return {
1493
+ encode(privKey) {
1494
+ const compressed = concat(privKey, new Uint8Array([0x01]));
1495
+ return formatKey(compressed.subarray(0, 33), [network.wif]);
1496
+ },
1497
+ decode(wif) {
1498
+ let parsed = exports.base58check.decode(wif);
1499
+ if (parsed[0] !== network.wif)
1500
+ throw new Error('Wrong WIF prefix');
1501
+ parsed = parsed.subarray(1);
1502
+ // Check what it is. Compressed flag?
1503
+ if (parsed.length !== 33)
1504
+ throw new Error('Wrong WIF length');
1505
+ if (parsed[32] !== 0x01)
1506
+ throw new Error('Wrong WIF postfix');
1507
+ return parsed.subarray(0, -1);
1508
+ },
1509
+ };
1510
+ }
1511
+ exports.WIF = WIF;
1512
+ // Returns OutType, which can be used to create outscript
1513
+ function Address(network = exports.NETWORK) {
1514
+ return {
1515
+ encode(from) {
1516
+ const { type } = from;
1517
+ if (type === 'wpkh')
1518
+ return programToWitness(0, from.hash, network);
1519
+ else if (type === 'wsh')
1520
+ return programToWitness(0, from.hash, network);
1521
+ else if (type === 'tr')
1522
+ return programToWitness(1, from.pubkey, network);
1523
+ else if (type === 'pkh')
1524
+ return formatKey(from.hash, [network.pubKeyHash]);
1525
+ else if (type === 'sh')
1526
+ return formatKey(from.hash, [network.scriptHash]);
1527
+ throw new Error(`Unknown address type=${type}`);
1528
+ },
1529
+ decode(address) {
1530
+ if (address.length < 14 || address.length > 74)
1531
+ throw new Error('Invalid address length');
1532
+ // Bech32
1533
+ if (network.bech32 && address.toLowerCase().startsWith(network.bech32)) {
1534
+ let res;
1535
+ try {
1536
+ res = base_1.bech32.decode(address);
1537
+ if (res.words[0] !== 0)
1538
+ throw new Error(`bech32: wrong version=${res.words[0]}`);
1539
+ }
1540
+ catch (_) {
1541
+ // Starting from version 1 it is decoded as bech32m
1542
+ res = base_1.bech32m.decode(address);
1543
+ if (res.words[0] === 0)
1544
+ throw new Error(`bech32m: wrong version=${res.words[0]}`);
1545
+ }
1546
+ if (res.prefix !== network.bech32)
1547
+ throw new Error(`wrong bech32 prefix=${res.prefix}`);
1548
+ const [version, ...program] = res.words;
1549
+ const data = base_1.bech32.fromWords(program);
1550
+ validateWitness(version, data);
1551
+ if (version === 0 && data.length === 32)
1552
+ return { type: 'wsh', hash: data };
1553
+ else if (version === 0 && data.length === 20)
1554
+ return { type: 'wpkh', hash: data };
1555
+ else if (version === 1 && data.length === 32)
1556
+ return { type: 'tr', pubkey: data };
1557
+ else
1558
+ throw new Error('Unknown witness program');
1559
+ }
1560
+ const data = exports.base58check.decode(address);
1561
+ if (data.length !== 21)
1562
+ throw new Error('Invalid base58 address');
1563
+ // Pay To Public Key Hash
1564
+ if (data[0] === network.pubKeyHash) {
1565
+ return { type: 'pkh', hash: data.slice(1) };
1566
+ }
1567
+ else if (data[0] === network.scriptHash) {
1568
+ return {
1569
+ type: 'sh',
1570
+ hash: data.slice(1),
1571
+ };
1572
+ }
1573
+ throw new Error(`Invalid address prefix=${data[0]}`);
1574
+ },
1575
+ };
1576
+ }
1577
+ exports.Address = Address;
1578
+ // /Address
1579
+ /**
1580
+ * Internal, exported only for backwards-compat. Use `SigHash` instead.
1581
+ * @deprecated
1582
+ */
1583
+ var SignatureHash;
1584
+ (function (SignatureHash) {
1585
+ SignatureHash[SignatureHash["DEFAULT"] = 0] = "DEFAULT";
1586
+ SignatureHash[SignatureHash["ALL"] = 1] = "ALL";
1587
+ SignatureHash[SignatureHash["NONE"] = 2] = "NONE";
1588
+ SignatureHash[SignatureHash["SINGLE"] = 3] = "SINGLE";
1589
+ SignatureHash[SignatureHash["ANYONECANPAY"] = 128] = "ANYONECANPAY";
1590
+ })(SignatureHash || (exports.SignatureHash = SignatureHash = {}));
1591
+ var SigHash;
1592
+ (function (SigHash) {
1593
+ SigHash[SigHash["DEFAULT"] = 0] = "DEFAULT";
1594
+ SigHash[SigHash["ALL"] = 1] = "ALL";
1595
+ SigHash[SigHash["NONE"] = 2] = "NONE";
1596
+ SigHash[SigHash["SINGLE"] = 3] = "SINGLE";
1597
+ SigHash[SigHash["DEFAULT_ANYONECANPAY"] = 128] = "DEFAULT_ANYONECANPAY";
1598
+ SigHash[SigHash["ALL_ANYONECANPAY"] = 129] = "ALL_ANYONECANPAY";
1599
+ SigHash[SigHash["NONE_ANYONECANPAY"] = 130] = "NONE_ANYONECANPAY";
1600
+ SigHash[SigHash["SINGLE_ANYONECANPAY"] = 131] = "SINGLE_ANYONECANPAY";
1601
+ })(SigHash || (exports.SigHash = SigHash = {}));
1602
+ function validateSigHash(s) {
1603
+ if (typeof s !== 'number' || typeof SigHash[s] !== 'string')
1604
+ throw new Error(`Invalid SigHash=${s}`);
1605
+ return s;
1606
+ }
1607
+ function unpackSighash(hashType) {
1608
+ const masked = hashType & 0b0011111;
1609
+ return {
1610
+ isAny: !!(hashType & SignatureHash.ANYONECANPAY),
1611
+ isNone: masked === SignatureHash.NONE,
1612
+ isSingle: masked === SignatureHash.SINGLE,
1613
+ };
1614
+ }
1615
+ const _sortPubkeys = (pubkeys) => Array.from(pubkeys).sort(_cmpBytes);
1616
+ exports._sortPubkeys = _sortPubkeys;
1617
+ // Force check index/txid/sequence
1618
+ function inputBeforeSign(i) {
1619
+ if (i.txid === undefined || i.index === undefined)
1620
+ throw new Error('Transaction/input: txid and index required');
1621
+ return {
1622
+ txid: i.txid,
1623
+ index: i.index,
1624
+ sequence: def(i.sequence, exports.DEFAULT_SEQUENCE),
1625
+ finalScriptSig: def(i.finalScriptSig, P.EMPTY),
1626
+ };
1627
+ }
1628
+ function cleanFinalInput(i) {
1629
+ for (const _k in i) {
1630
+ const k = _k;
1631
+ if (!PSBTInputFinalKeys.includes(k))
1632
+ delete i[k];
1633
+ }
1634
+ }
1635
+ // Force check amount/script
1636
+ function outputBeforeSign(i) {
1637
+ if (i.script === undefined || i.amount === undefined)
1638
+ throw new Error('Transaction/output: script and amount required');
1639
+ return { script: i.script, amount: i.amount };
1640
+ }
1641
+ exports.TAP_LEAF_VERSION = 0xc0;
1642
+ const tapLeafHash = (script, version = exports.TAP_LEAF_VERSION) => secp256k1_1.schnorr.utils.taggedHash('TapLeaf', new Uint8Array([version]), exports.VarBytes.encode(script));
1643
+ exports.tapLeafHash = tapLeafHash;
1644
+ function getTaprootKeys(privKey, pubKey, internalKey, merkleRoot = P.EMPTY) {
1645
+ if (P.equalBytes(internalKey, pubKey)) {
1646
+ privKey = taprootTweakPrivKey(privKey, merkleRoot);
1647
+ pubKey = secp256k1_1.schnorr.getPublicKey(privKey);
1648
+ }
1649
+ return { privKey, pubKey };
1650
+ }
1651
+ const toStr = {}.toString;
1652
+ function validateOpts(opts) {
1653
+ if (opts !== undefined && toStr.call(opts) !== '[object Object]')
1654
+ throw new Error(`Wrong object type for transaction options: ${opts}`);
1655
+ const _opts = {
1656
+ ...opts,
1657
+ // Defaults
1658
+ version: def(opts.version, exports.DEFAULT_VERSION),
1659
+ lockTime: def(opts.lockTime, 0),
1660
+ PSBTVersion: def(opts.PSBTVersion, 0),
1661
+ };
1662
+ if (typeof _opts.allowUnknowInput !== 'undefined')
1663
+ opts.allowUnknownInputs = _opts.allowUnknowInput;
1664
+ if (typeof _opts.allowUnknowOutput !== 'undefined')
1665
+ opts.allowUnknownOutputs = _opts.allowUnknowOutput;
1666
+ // 0 and -1 happens in tests
1667
+ if (![-1, 0, 1, 2].includes(_opts.version))
1668
+ throw new Error(`Unknown version: ${_opts.version}`);
1669
+ if (typeof _opts.lockTime !== 'number')
1670
+ throw new Error('Transaction lock time should be number');
1671
+ P.U32LE.encode(_opts.lockTime); // Additional range checks that lockTime
1672
+ // There is no PSBT v1, and any new version will probably have fields which we don't know how to parse, which
1673
+ // can lead to constructing broken transactions
1674
+ if (_opts.PSBTVersion !== 0 && _opts.PSBTVersion !== 2)
1675
+ throw new Error(`Unknown PSBT version ${_opts.PSBTVersion}`);
1676
+ // Flags
1677
+ for (const k of [
1678
+ 'allowUnknownOutputs',
1679
+ 'allowUnknownInputs',
1680
+ 'disableScriptCheck',
1681
+ 'bip174jsCompat',
1682
+ 'allowLegacyWitnessUtxo',
1683
+ 'lowR',
1684
+ ]) {
1685
+ const v = _opts[k];
1686
+ if (v === undefined)
1687
+ continue; // optional
1688
+ if (typeof v !== 'boolean')
1689
+ throw new Error(`Transation options wrong type: ${k}=${v} (${typeof v})`);
1690
+ }
1691
+ return Object.freeze(_opts);
1692
+ }
1693
+ // Normalizes input
1694
+ function getPrevOut(input) {
1695
+ if (input.nonWitnessUtxo) {
1696
+ if (input.index === undefined)
1697
+ throw new Error('Unknown input index');
1698
+ return input.nonWitnessUtxo.outputs[input.index];
1699
+ }
1700
+ else if (input.witnessUtxo)
1701
+ return input.witnessUtxo;
1702
+ else
1703
+ throw new Error('Cannot find previous output info');
1704
+ }
1705
+ function normalizeInput(i, cur, allowedFields, disableScriptCheck = false) {
1706
+ let { nonWitnessUtxo, txid } = i;
1707
+ // String support for common fields. We usually prefer Uint8Array to avoid errors
1708
+ // like hex looking string accidentally passed, however, in case of nonWitnessUtxo
1709
+ // it is better to expect string, since constructing this complex object will be
1710
+ // difficult for user
1711
+ if (typeof nonWitnessUtxo === 'string')
1712
+ nonWitnessUtxo = base_1.hex.decode(nonWitnessUtxo);
1713
+ if (isBytes(nonWitnessUtxo))
1714
+ nonWitnessUtxo = exports.RawTx.decode(nonWitnessUtxo);
1715
+ if (!('nonWitnessUtxo' in i) && nonWitnessUtxo === undefined)
1716
+ nonWitnessUtxo = cur?.nonWitnessUtxo;
1717
+ if (typeof txid === 'string')
1718
+ txid = base_1.hex.decode(txid);
1719
+ // TODO: if we have nonWitnessUtxo, we can extract txId from here
1720
+ if (txid === undefined)
1721
+ txid = cur?.txid;
1722
+ let res = { ...cur, ...i, nonWitnessUtxo, txid };
1723
+ if (!('nonWitnessUtxo' in i) && res.nonWitnessUtxo === undefined)
1724
+ delete res.nonWitnessUtxo;
1725
+ if (res.sequence === undefined)
1726
+ res.sequence = exports.DEFAULT_SEQUENCE;
1727
+ if (res.tapMerkleRoot === null)
1728
+ delete res.tapMerkleRoot;
1729
+ res = mergeKeyMap(PSBTInput, res, cur, allowedFields);
1730
+ PSBTInputCoder.encode(res); // Validates that everything is correct at this point
1731
+ let prevOut;
1732
+ if (res.nonWitnessUtxo && res.index !== undefined)
1733
+ prevOut = res.nonWitnessUtxo.outputs[res.index];
1734
+ else if (res.witnessUtxo)
1735
+ prevOut = res.witnessUtxo;
1736
+ if (prevOut && !disableScriptCheck)
1737
+ checkScript(prevOut && prevOut.script, res.redeemScript, res.witnessScript);
1738
+ return res;
1739
+ }
1740
+ function getInputType(input, allowLegacyWitnessUtxo = false) {
1741
+ let txType = 'legacy';
1742
+ let defaultSighash = SignatureHash.ALL;
1743
+ const prevOut = getPrevOut(input);
1744
+ const first = exports.OutScript.decode(prevOut.script);
1745
+ let type = first.type;
1746
+ let cur = first;
1747
+ const stack = [first];
1748
+ if (first.type === 'tr') {
1749
+ defaultSighash = SignatureHash.DEFAULT;
1750
+ return {
1751
+ txType: 'taproot',
1752
+ type: 'tr',
1753
+ last: first,
1754
+ lastScript: prevOut.script,
1755
+ defaultSighash,
1756
+ sighash: input.sighashType || defaultSighash,
1757
+ };
1758
+ }
1759
+ else {
1760
+ if (first.type === 'wpkh' || first.type === 'wsh')
1761
+ txType = 'segwit';
1762
+ if (first.type === 'sh') {
1763
+ if (!input.redeemScript)
1764
+ throw new Error('inputType: sh without redeemScript');
1765
+ let child = exports.OutScript.decode(input.redeemScript);
1766
+ if (child.type === 'wpkh' || child.type === 'wsh')
1767
+ txType = 'segwit';
1768
+ stack.push(child);
1769
+ cur = child;
1770
+ type += `-${child.type}`;
1771
+ }
1772
+ // wsh can be inside sh
1773
+ if (cur.type === 'wsh') {
1774
+ if (!input.witnessScript)
1775
+ throw new Error('inputType: wsh without witnessScript');
1776
+ let child = exports.OutScript.decode(input.witnessScript);
1777
+ if (child.type === 'wsh')
1778
+ txType = 'segwit';
1779
+ stack.push(child);
1780
+ cur = child;
1781
+ type += `-${child.type}`;
1782
+ }
1783
+ const last = stack[stack.length - 1];
1784
+ if (last.type === 'sh' || last.type === 'wsh')
1785
+ throw new Error('inputType: sh/wsh cannot be terminal type');
1786
+ const lastScript = exports.OutScript.encode(last);
1787
+ const res = {
1788
+ type,
1789
+ txType,
1790
+ last,
1791
+ lastScript,
1792
+ defaultSighash,
1793
+ sighash: input.sighashType || defaultSighash,
1794
+ };
1795
+ if (txType === 'legacy' && !allowLegacyWitnessUtxo && !input.nonWitnessUtxo) {
1796
+ throw new Error(`Transaction/sign: legacy input without nonWitnessUtxo, can result in attack that forces paying higher fees. Pass allowLegacyWitnessUtxo=true, if you sure`);
1797
+ }
1798
+ return res;
1799
+ }
1800
+ }
1801
+ const toVsize = (weight) => Math.ceil(weight / 4);
1802
+ class Transaction {
1803
+ constructor(opts = {}) {
1804
+ this.global = {};
1805
+ this.inputs = []; // use getInput()
1806
+ this.outputs = []; // use getOutput()
1807
+ const _opts = (this.opts = validateOpts(opts));
1808
+ // Merge with global structure of PSBTv2
1809
+ if (_opts.lockTime !== exports.DEFAULT_LOCKTIME)
1810
+ this.global.fallbackLocktime = _opts.lockTime;
1811
+ this.global.txVersion = _opts.version;
1812
+ }
1813
+ // Import
1814
+ static fromRaw(raw, opts = {}) {
1815
+ const parsed = exports.RawTx.decode(raw);
1816
+ const tx = new Transaction({ ...opts, version: parsed.version, lockTime: parsed.lockTime });
1817
+ for (const o of parsed.outputs)
1818
+ tx.addOutput(o);
1819
+ tx.outputs = parsed.outputs;
1820
+ tx.inputs = parsed.inputs;
1821
+ if (parsed.witnesses) {
1822
+ for (let i = 0; i < parsed.witnesses.length; i++)
1823
+ tx.inputs[i].finalScriptWitness = parsed.witnesses[i];
1824
+ }
1825
+ return tx;
1826
+ }
1827
+ // PSBT
1828
+ static fromPSBT(psbt, opts = {}) {
1829
+ let parsed;
1830
+ try {
1831
+ parsed = exports.RawPSBTV0.decode(psbt);
1832
+ }
1833
+ catch (e0) {
1834
+ try {
1835
+ parsed = exports.RawPSBTV2.decode(psbt);
1836
+ }
1837
+ catch (e2) {
1838
+ // Throw error for v0 parsing, since it popular, otherwise it would be shadowed by v2 error
1839
+ throw e0;
1840
+ }
1841
+ }
1842
+ const PSBTVersion = parsed.global.version || 0;
1843
+ if (PSBTVersion !== 0 && PSBTVersion !== 2)
1844
+ throw new Error(`Wrong PSBT version=${PSBTVersion}`);
1845
+ const unsigned = parsed.global.unsignedTx;
1846
+ const version = PSBTVersion === 0 ? unsigned?.version : parsed.global.txVersion;
1847
+ const lockTime = PSBTVersion === 0 ? unsigned?.lockTime : parsed.global.fallbackLocktime;
1848
+ const tx = new Transaction({ ...opts, version, lockTime, PSBTVersion });
1849
+ // We need slice here, because otherwise
1850
+ const inputCount = PSBTVersion === 0 ? unsigned?.inputs.length : parsed.global.inputCount;
1851
+ tx.inputs = parsed.inputs.slice(0, inputCount).map((i, j) => ({
1852
+ finalScriptSig: P.EMPTY,
1853
+ ...parsed.global.unsignedTx?.inputs[j],
1854
+ ...i,
1855
+ }));
1856
+ const outputCount = PSBTVersion === 0 ? unsigned?.outputs.length : parsed.global.outputCount;
1857
+ tx.outputs = parsed.outputs.slice(0, outputCount).map((i, j) => ({
1858
+ ...i,
1859
+ ...parsed.global.unsignedTx?.outputs[j],
1860
+ }));
1861
+ tx.global = { ...parsed.global, txVersion: version }; // just in case proprietary/unknown fields
1862
+ if (lockTime !== exports.DEFAULT_LOCKTIME)
1863
+ tx.global.fallbackLocktime = lockTime;
1864
+ return tx;
1865
+ }
1866
+ toPSBT(PSBTVersion = this.opts.PSBTVersion) {
1867
+ if (PSBTVersion !== 0 && PSBTVersion !== 2)
1868
+ throw new Error(`Wrong PSBT version=${PSBTVersion}`);
1869
+ const inputs = this.inputs.map((i) => cleanPSBTFields(PSBTVersion, PSBTInput, i));
1870
+ for (const inp of inputs) {
1871
+ // Don't serialize empty fields
1872
+ if (inp.partialSig && !inp.partialSig.length)
1873
+ delete inp.partialSig;
1874
+ if (inp.finalScriptSig && !inp.finalScriptSig.length)
1875
+ delete inp.finalScriptSig;
1876
+ if (inp.finalScriptWitness && !inp.finalScriptWitness.length)
1877
+ delete inp.finalScriptWitness;
1878
+ }
1879
+ const outputs = this.outputs.map((i) => cleanPSBTFields(PSBTVersion, PSBTOutput, i));
1880
+ const global = { ...this.global };
1881
+ if (PSBTVersion === 0) {
1882
+ global.unsignedTx = exports.RawTx.decode(this.unsignedTx);
1883
+ delete global.fallbackLocktime;
1884
+ delete global.txVersion;
1885
+ }
1886
+ else {
1887
+ global.version = PSBTVersion;
1888
+ global.txVersion = this.version;
1889
+ global.inputCount = this.inputs.length;
1890
+ global.outputCount = this.outputs.length;
1891
+ if (global.fallbackLocktime && global.fallbackLocktime === exports.DEFAULT_LOCKTIME)
1892
+ delete global.fallbackLocktime;
1893
+ }
1894
+ if (this.opts.bip174jsCompat) {
1895
+ if (!inputs.length)
1896
+ inputs.push({});
1897
+ if (!outputs.length)
1898
+ outputs.push({});
1899
+ }
1900
+ return (PSBTVersion === 0 ? exports.RawPSBTV0 : exports.RawPSBTV2).encode({
1901
+ global,
1902
+ inputs,
1903
+ outputs,
1904
+ });
1905
+ }
1906
+ // BIP370 lockTime (https://github.com/bitcoin/bips/blob/master/bip-0370.mediawiki#determining-lock-time)
1907
+ get lockTime() {
1908
+ let height = exports.DEFAULT_LOCKTIME;
1909
+ let heightCnt = 0;
1910
+ let time = exports.DEFAULT_LOCKTIME;
1911
+ let timeCnt = 0;
1912
+ for (const i of this.inputs) {
1913
+ if (i.requiredHeightLocktime) {
1914
+ height = Math.max(height, i.requiredHeightLocktime);
1915
+ heightCnt++;
1916
+ }
1917
+ if (i.requiredTimeLocktime) {
1918
+ time = Math.max(time, i.requiredTimeLocktime);
1919
+ timeCnt++;
1920
+ }
1921
+ }
1922
+ if (heightCnt && heightCnt >= timeCnt)
1923
+ return height;
1924
+ if (time !== exports.DEFAULT_LOCKTIME)
1925
+ return time;
1926
+ return this.global.fallbackLocktime || exports.DEFAULT_LOCKTIME;
1927
+ }
1928
+ get version() {
1929
+ // Should be not possible
1930
+ if (this.global.txVersion === undefined)
1931
+ throw new Error('No global.txVersion');
1932
+ return this.global.txVersion;
1933
+ }
1934
+ inputStatus(idx) {
1935
+ this.checkInputIdx(idx);
1936
+ const input = this.inputs[idx];
1937
+ // Finalized
1938
+ if (input.finalScriptSig && input.finalScriptSig.length)
1939
+ return 'finalized';
1940
+ if (input.finalScriptWitness && input.finalScriptWitness.length)
1941
+ return 'finalized';
1942
+ // Signed taproot
1943
+ if (input.tapKeySig)
1944
+ return 'signed';
1945
+ if (input.tapScriptSig && input.tapScriptSig.length)
1946
+ return 'signed';
1947
+ // Signed
1948
+ if (input.partialSig && input.partialSig.length)
1949
+ return 'signed';
1950
+ return 'unsigned';
1951
+ }
1952
+ // Cannot replace unpackSighash, tests rely on very generic implemenetation with signing inputs outside of range
1953
+ // We will lose some vectors -> smaller test coverage of preimages (very important!)
1954
+ inputSighash(idx) {
1955
+ this.checkInputIdx(idx);
1956
+ const sighash = getInputType(this.inputs[idx], this.opts.allowLegacyWitnessUtxo).sighash;
1957
+ // ALL or DEFAULT -- everything signed
1958
+ // NONE -- all inputs + no outputs
1959
+ // SINGLE -- all inputs + output with same index
1960
+ // ALL + ANYONE -- specific input + all outputs
1961
+ // NONE + ANYONE -- specific input + no outputs
1962
+ // SINGLE -- specific inputs + output with same index
1963
+ const sigOutputs = sighash === SignatureHash.DEFAULT ? SignatureHash.ALL : sighash & 0b11;
1964
+ const sigInputs = sighash & SignatureHash.ANYONECANPAY;
1965
+ return { sigInputs, sigOutputs };
1966
+ }
1967
+ // Very nice for debug purposes, but slow. If there is too much inputs/outputs to add, will be quadratic.
1968
+ // Some cache will be nice, but there chance to have bugs with cache invalidation
1969
+ signStatus() {
1970
+ // if addInput or addOutput is not possible, then all inputs or outputs are signed
1971
+ let addInput = true, addOutput = true;
1972
+ let inputs = [], outputs = [];
1973
+ for (let idx = 0; idx < this.inputs.length; idx++) {
1974
+ const status = this.inputStatus(idx);
1975
+ // Unsigned input doesn't affect anything
1976
+ if (status === 'unsigned')
1977
+ continue;
1978
+ const { sigInputs, sigOutputs } = this.inputSighash(idx);
1979
+ // Input type
1980
+ if (sigInputs === SignatureHash.ANYONECANPAY)
1981
+ inputs.push(idx);
1982
+ else
1983
+ addInput = false;
1984
+ // Output type
1985
+ if (sigOutputs === SignatureHash.ALL)
1986
+ addOutput = false;
1987
+ else if (sigOutputs === SignatureHash.SINGLE)
1988
+ outputs.push(idx);
1989
+ else if (sigOutputs === SignatureHash.NONE) {
1990
+ // Doesn't affect any outputs at all
1991
+ }
1992
+ else
1993
+ throw new Error(`Wrong signature hash output type: ${sigOutputs}`);
1994
+ }
1995
+ return { addInput, addOutput, inputs, outputs };
1996
+ }
1997
+ get isFinal() {
1998
+ for (let idx = 0; idx < this.inputs.length; idx++)
1999
+ if (this.inputStatus(idx) !== 'finalized')
2000
+ return false;
2001
+ return true;
2002
+ }
2003
+ // Info utils
2004
+ get hasWitnesses() {
2005
+ let out = false;
2006
+ for (const i of this.inputs)
2007
+ if (i.finalScriptWitness && i.finalScriptWitness.length)
2008
+ out = true;
2009
+ return out;
2010
+ }
2011
+ // https://en.bitcoin.it/wiki/Weight_units
2012
+ get weight() {
2013
+ if (!this.isFinal)
2014
+ throw new Error('Transaction is not finalized');
2015
+ let out = 32;
2016
+ // Outputs
2017
+ const outputs = this.outputs.map(outputBeforeSign);
2018
+ out += 4 * CompactSizeLen.encode(this.outputs.length).length;
2019
+ for (const o of outputs)
2020
+ out += 32 + 4 * exports.VarBytes.encode(o.script).length;
2021
+ // Inputs
2022
+ if (this.hasWitnesses)
2023
+ out += 2;
2024
+ out += 4 * CompactSizeLen.encode(this.inputs.length).length;
2025
+ for (const i of this.inputs) {
2026
+ out += 160 + 4 * exports.VarBytes.encode(i.finalScriptSig || P.EMPTY).length;
2027
+ if (this.hasWitnesses && i.finalScriptWitness)
2028
+ out += exports.RawWitness.encode(i.finalScriptWitness).length;
2029
+ }
2030
+ return out;
2031
+ }
2032
+ get vsize() {
2033
+ return toVsize(this.weight);
2034
+ }
2035
+ toBytes(withScriptSig = false, withWitness = false) {
2036
+ return exports.RawTx.encode({
2037
+ version: this.version,
2038
+ lockTime: this.lockTime,
2039
+ inputs: this.inputs.map(inputBeforeSign).map((i) => ({
2040
+ ...i,
2041
+ finalScriptSig: (withScriptSig && i.finalScriptSig) || P.EMPTY,
2042
+ })),
2043
+ outputs: this.outputs.map(outputBeforeSign),
2044
+ witnesses: this.inputs.map((i) => i.finalScriptWitness || []),
2045
+ segwitFlag: withWitness && this.hasWitnesses,
2046
+ });
2047
+ }
2048
+ get unsignedTx() {
2049
+ return this.toBytes(false, false);
2050
+ }
2051
+ get hex() {
2052
+ return base_1.hex.encode(this.toBytes(true, this.hasWitnesses));
2053
+ }
2054
+ get hash() {
2055
+ if (!this.isFinal)
2056
+ throw new Error('Transaction is not finalized');
2057
+ return base_1.hex.encode(sha256x2(this.toBytes(true)));
2058
+ }
2059
+ get id() {
2060
+ if (!this.isFinal)
2061
+ throw new Error('Transaction is not finalized');
2062
+ return base_1.hex.encode(sha256x2(this.toBytes(true)).reverse());
2063
+ }
2064
+ // Input stuff
2065
+ checkInputIdx(idx) {
2066
+ if (!Number.isSafeInteger(idx) || 0 > idx || idx >= this.inputs.length)
2067
+ throw new Error(`Wrong input index=${idx}`);
2068
+ }
2069
+ getInput(idx) {
2070
+ this.checkInputIdx(idx);
2071
+ return cloneDeep(this.inputs[idx]);
2072
+ }
2073
+ get inputsLength() {
2074
+ return this.inputs.length;
2075
+ }
2076
+ // Modification
2077
+ addInput(input, _ignoreSignStatus = false) {
2078
+ if (!_ignoreSignStatus && !this.signStatus().addInput)
2079
+ throw new Error('Tx has signed inputs, cannot add new one');
2080
+ this.inputs.push(normalizeInput(input, undefined, undefined, this.opts.disableScriptCheck));
2081
+ return this.inputs.length - 1;
2082
+ }
2083
+ updateInput(idx, input, _ignoreSignStatus = false) {
2084
+ this.checkInputIdx(idx);
2085
+ let allowedFields = undefined;
2086
+ if (!_ignoreSignStatus) {
2087
+ const status = this.signStatus();
2088
+ if (!status.addInput || status.inputs.includes(idx))
2089
+ allowedFields = PSBTInputUnsignedKeys;
2090
+ }
2091
+ this.inputs[idx] = normalizeInput(input, this.inputs[idx], allowedFields, this.opts.disableScriptCheck);
2092
+ }
2093
+ // Output stuff
2094
+ checkOutputIdx(idx) {
2095
+ if (!Number.isSafeInteger(idx) || 0 > idx || idx >= this.outputs.length)
2096
+ throw new Error(`Wrong output index=${idx}`);
2097
+ }
2098
+ getOutput(idx) {
2099
+ this.checkOutputIdx(idx);
2100
+ return cloneDeep(this.outputs[idx]);
2101
+ }
2102
+ get outputsLength() {
2103
+ return this.outputs.length;
2104
+ }
2105
+ normalizeOutput(o, cur, allowedFields) {
2106
+ let { amount, script } = o;
2107
+ if (amount === undefined)
2108
+ amount = cur?.amount;
2109
+ if (typeof amount !== 'bigint')
2110
+ throw new Error('amount must be bigint sats');
2111
+ if (typeof script === 'string')
2112
+ script = base_1.hex.decode(script);
2113
+ if (script === undefined)
2114
+ script = cur?.script;
2115
+ let res = { ...cur, ...o, amount, script };
2116
+ if (res.amount === undefined)
2117
+ delete res.amount;
2118
+ res = mergeKeyMap(PSBTOutput, res, cur, allowedFields);
2119
+ PSBTOutputCoder.encode(res);
2120
+ if (res.script &&
2121
+ !this.opts.allowUnknownOutputs &&
2122
+ exports.OutScript.decode(res.script).type === 'unknown') {
2123
+ throw new Error('Transaction/output: unknown output script type, there is a chance that input is unspendable. Pass allowUnknownOutputs=true, if you sure');
2124
+ }
2125
+ if (!this.opts.disableScriptCheck)
2126
+ checkScript(res.script, res.redeemScript, res.witnessScript);
2127
+ return res;
2128
+ }
2129
+ addOutput(o, _ignoreSignStatus = false) {
2130
+ if (!_ignoreSignStatus && !this.signStatus().addOutput)
2131
+ throw new Error('Tx has signed outputs, cannot add new one');
2132
+ this.outputs.push(this.normalizeOutput(o));
2133
+ return this.outputs.length - 1;
2134
+ }
2135
+ updateOutput(idx, output, _ignoreSignStatus = false) {
2136
+ this.checkOutputIdx(idx);
2137
+ let allowedFields = undefined;
2138
+ if (!_ignoreSignStatus) {
2139
+ const status = this.signStatus();
2140
+ if (!status.addOutput || status.outputs.includes(idx))
2141
+ allowedFields = PSBTOutputUnsignedKeys;
2142
+ }
2143
+ this.outputs[idx] = this.normalizeOutput(output, this.outputs[idx], allowedFields);
2144
+ }
2145
+ addOutputAddress(address, amount, network = exports.NETWORK) {
2146
+ return this.addOutput({ script: exports.OutScript.encode(Address(network).decode(address)), amount });
2147
+ }
2148
+ // Utils
2149
+ get fee() {
2150
+ let res = 0n;
2151
+ for (const i of this.inputs) {
2152
+ const prevOut = getPrevOut(i);
2153
+ if (!prevOut)
2154
+ throw new Error('Empty input amount');
2155
+ res += prevOut.amount;
2156
+ }
2157
+ const outputs = this.outputs.map(outputBeforeSign);
2158
+ for (const o of outputs)
2159
+ res -= o.amount;
2160
+ return res;
2161
+ }
2162
+ // Signing
2163
+ // Based on https://github.com/bitcoin/bitcoin/blob/5871b5b5ab57a0caf9b7514eb162c491c83281d5/test/functional/test_framework/script.py#L624
2164
+ // There is optimization opportunity to re-use hashes for multiple inputs for witness v0/v1,
2165
+ // but we are trying to be less complicated for audit purpose for now.
2166
+ preimageLegacy(idx, prevOutScript, hashType) {
2167
+ const { isAny, isNone, isSingle } = unpackSighash(hashType);
2168
+ if (idx < 0 || !Number.isSafeInteger(idx))
2169
+ throw new Error(`Invalid input idx=${idx}`);
2170
+ if ((isSingle && idx >= this.outputs.length) || idx >= this.inputs.length)
2171
+ return P.U256BE.encode(1n);
2172
+ prevOutScript = exports.Script.encode(exports.Script.decode(prevOutScript).filter((i) => i !== 'CODESEPARATOR'));
2173
+ let inputs = this.inputs
2174
+ .map(inputBeforeSign)
2175
+ .map((input, inputIdx) => ({
2176
+ ...input,
2177
+ finalScriptSig: inputIdx === idx ? prevOutScript : P.EMPTY,
2178
+ }));
2179
+ if (isAny)
2180
+ inputs = [inputs[idx]];
2181
+ else if (isNone || isSingle) {
2182
+ inputs = inputs.map((input, inputIdx) => ({
2183
+ ...input,
2184
+ sequence: inputIdx === idx ? input.sequence : 0,
2185
+ }));
2186
+ }
2187
+ let outputs = this.outputs.map(outputBeforeSign);
2188
+ if (isNone)
2189
+ outputs = [];
2190
+ else if (isSingle) {
2191
+ outputs = outputs.slice(0, idx).fill(EMPTY_OUTPUT).concat([outputs[idx]]);
2192
+ }
2193
+ const tmpTx = exports.RawTx.encode({
2194
+ lockTime: this.lockTime,
2195
+ version: this.version,
2196
+ segwitFlag: false,
2197
+ inputs,
2198
+ outputs,
2199
+ });
2200
+ return sha256x2(tmpTx, P.I32LE.encode(hashType));
2201
+ }
2202
+ preimageWitnessV0(idx, prevOutScript, hashType, amount) {
2203
+ const { isAny, isNone, isSingle } = unpackSighash(hashType);
2204
+ let inputHash = EMPTY32;
2205
+ let sequenceHash = EMPTY32;
2206
+ let outputHash = EMPTY32;
2207
+ const inputs = this.inputs.map(inputBeforeSign);
2208
+ const outputs = this.outputs.map(outputBeforeSign);
2209
+ if (!isAny)
2210
+ inputHash = sha256x2(...inputs.map(TxHashIdx.encode));
2211
+ if (!isAny && !isSingle && !isNone)
2212
+ sequenceHash = sha256x2(...inputs.map((i) => P.U32LE.encode(i.sequence)));
2213
+ if (!isSingle && !isNone) {
2214
+ outputHash = sha256x2(...outputs.map(exports.RawOutput.encode));
2215
+ }
2216
+ else if (isSingle && idx < outputs.length)
2217
+ outputHash = sha256x2(exports.RawOutput.encode(outputs[idx]));
2218
+ const input = inputs[idx];
2219
+ return sha256x2(P.I32LE.encode(this.version), inputHash, sequenceHash, P.bytes(32, true).encode(input.txid), P.U32LE.encode(input.index), exports.VarBytes.encode(prevOutScript), P.U64LE.encode(amount), P.U32LE.encode(input.sequence), outputHash, P.U32LE.encode(this.lockTime), P.U32LE.encode(hashType));
2220
+ }
2221
+ preimageWitnessV1(idx, prevOutScript, hashType, amount, codeSeparator = -1, leafScript, leafVer = 0xc0, annex) {
2222
+ if (!Array.isArray(amount) || this.inputs.length !== amount.length)
2223
+ throw new Error(`Invalid amounts array=${amount}`);
2224
+ if (!Array.isArray(prevOutScript) || this.inputs.length !== prevOutScript.length)
2225
+ throw new Error(`Invalid prevOutScript array=${prevOutScript}`);
2226
+ const out = [
2227
+ P.U8.encode(0),
2228
+ P.U8.encode(hashType), // U8 sigHash
2229
+ P.I32LE.encode(this.version),
2230
+ P.U32LE.encode(this.lockTime),
2231
+ ];
2232
+ const outType = hashType === SignatureHash.DEFAULT ? SignatureHash.ALL : hashType & 0b11;
2233
+ const inType = hashType & SignatureHash.ANYONECANPAY;
2234
+ const inputs = this.inputs.map(inputBeforeSign);
2235
+ const outputs = this.outputs.map(outputBeforeSign);
2236
+ if (inType !== SignatureHash.ANYONECANPAY) {
2237
+ out.push(...[
2238
+ inputs.map(TxHashIdx.encode),
2239
+ amount.map(P.U64LE.encode),
2240
+ prevOutScript.map(exports.VarBytes.encode),
2241
+ inputs.map((i) => P.U32LE.encode(i.sequence)),
2242
+ ].map((i) => (0, sha256_1.sha256)(concat(...i))));
2243
+ }
2244
+ if (outType === SignatureHash.ALL) {
2245
+ out.push((0, sha256_1.sha256)(concat(...outputs.map(exports.RawOutput.encode))));
2246
+ }
2247
+ const spendType = (annex ? 1 : 0) | (leafScript ? 2 : 0);
2248
+ out.push(new Uint8Array([spendType]));
2249
+ if (inType === SignatureHash.ANYONECANPAY) {
2250
+ const inp = inputs[idx];
2251
+ out.push(TxHashIdx.encode(inp), P.U64LE.encode(amount[idx]), exports.VarBytes.encode(prevOutScript[idx]), P.U32LE.encode(inp.sequence));
2252
+ }
2253
+ else
2254
+ out.push(P.U32LE.encode(idx));
2255
+ if (spendType & 1)
2256
+ out.push((0, sha256_1.sha256)(exports.VarBytes.encode(annex || P.EMPTY)));
2257
+ if (outType === SignatureHash.SINGLE)
2258
+ out.push(idx < outputs.length ? (0, sha256_1.sha256)(exports.RawOutput.encode(outputs[idx])) : EMPTY32);
2259
+ if (leafScript)
2260
+ out.push((0, exports.tapLeafHash)(leafScript, leafVer), P.U8.encode(0), P.I32LE.encode(codeSeparator));
2261
+ return secp256k1_1.schnorr.utils.taggedHash('TapSighash', ...out);
2262
+ }
2263
+ // Signer can be privateKey OR instance of bip32 HD stuff
2264
+ signIdx(privateKey, idx, allowedSighash, _auxRand) {
2265
+ this.checkInputIdx(idx);
2266
+ const input = this.inputs[idx];
2267
+ const inputType = getInputType(input, this.opts.allowLegacyWitnessUtxo);
2268
+ // Handle BIP32 HDKey
2269
+ if (!isBytes(privateKey)) {
2270
+ if (!input.bip32Derivation || !input.bip32Derivation.length)
2271
+ throw new Error('bip32Derivation: empty');
2272
+ const signers = input.bip32Derivation
2273
+ .filter((i) => i[1].fingerprint == privateKey.fingerprint)
2274
+ .map(([pubKey, { path }]) => {
2275
+ let s = privateKey;
2276
+ for (const i of path)
2277
+ s = s.deriveChild(i);
2278
+ if (!P.equalBytes(s.publicKey, pubKey))
2279
+ throw new Error('bip32Derivation: wrong pubKey');
2280
+ if (!s.privateKey)
2281
+ throw new Error('bip32Derivation: no privateKey');
2282
+ return s;
2283
+ });
2284
+ if (!signers.length)
2285
+ throw new Error(`bip32Derivation: no items with fingerprint=${privateKey.fingerprint}`);
2286
+ let signed = false;
2287
+ for (const s of signers)
2288
+ if (this.signIdx(s.privateKey, idx))
2289
+ signed = true;
2290
+ return signed;
2291
+ }
2292
+ // Sighash checks
2293
+ // Just for compat with bitcoinjs-lib, so users won't face unexpected behaviour.
2294
+ if (!allowedSighash)
2295
+ allowedSighash = [inputType.defaultSighash];
2296
+ else
2297
+ allowedSighash.forEach(validateSigHash);
2298
+ const sighash = inputType.sighash;
2299
+ if (!allowedSighash.includes(sighash)) {
2300
+ throw new Error(`Input with not allowed sigHash=${sighash}. Allowed: ${allowedSighash.join(', ')}`);
2301
+ }
2302
+ // It is possible to sign these inputs for legacy/segwit v0 (but no taproot!),
2303
+ // however this was because of bug in bitcoin-core, which remains here because of consensus.
2304
+ // If this is absolutely neccessary for your case, please open issue.
2305
+ // We disable it to avoid complicated workflow where SINGLE will block adding new outputs
2306
+ const { sigOutputs } = this.inputSighash(idx);
2307
+ if (sigOutputs === SignatureHash.SINGLE && idx >= this.outputs.length) {
2308
+ throw new Error(`Input with sighash SINGLE, but there is no output with corresponding index=${idx}`);
2309
+ }
2310
+ // Actual signing
2311
+ // Taproot
2312
+ const prevOut = getPrevOut(input);
2313
+ if (inputType.txType === 'taproot') {
2314
+ if (input.tapBip32Derivation)
2315
+ throw new Error('tapBip32Derivation unsupported');
2316
+ const prevOuts = this.inputs.map(getPrevOut);
2317
+ const prevOutScript = prevOuts.map((i) => i.script);
2318
+ const amount = prevOuts.map((i) => i.amount);
2319
+ let signed = false;
2320
+ let schnorrPub = secp256k1_1.schnorr.getPublicKey(privateKey);
2321
+ let merkleRoot = input.tapMerkleRoot || P.EMPTY;
2322
+ if (input.tapInternalKey) {
2323
+ // internal + tweak = tweaked key
2324
+ // if internal key == current public key, we need to tweak private key,
2325
+ // otherwise sign as is. bitcoinjs implementation always wants tweaked
2326
+ // priv key to be provided
2327
+ const { pubKey, privKey } = getTaprootKeys(privateKey, schnorrPub, input.tapInternalKey, merkleRoot);
2328
+ const [taprootPubKey, _] = taprootTweakPubkey(input.tapInternalKey, merkleRoot);
2329
+ if (P.equalBytes(taprootPubKey, pubKey)) {
2330
+ const hash = this.preimageWitnessV1(idx, prevOutScript, sighash, amount);
2331
+ const sig = concat(secp256k1_1.schnorr.sign(hash, privKey, _auxRand), sighash !== SignatureHash.DEFAULT ? new Uint8Array([sighash]) : P.EMPTY);
2332
+ this.updateInput(idx, { tapKeySig: sig }, true);
2333
+ signed = true;
2334
+ }
2335
+ }
2336
+ if (input.tapLeafScript) {
2337
+ input.tapScriptSig = input.tapScriptSig || [];
2338
+ for (const [_, _script] of input.tapLeafScript) {
2339
+ const script = _script.subarray(0, -1);
2340
+ const scriptDecoded = exports.Script.decode(script);
2341
+ const ver = _script[_script.length - 1];
2342
+ const hash = (0, exports.tapLeafHash)(script, ver);
2343
+ // NOTE: no need to tweak internal key here, since we don't support nested p2tr
2344
+ const pos = scriptDecoded.findIndex((i) => isBytes(i) && P.equalBytes(i, schnorrPub));
2345
+ // Skip if there is no public key in tapLeafScript
2346
+ if (pos === -1)
2347
+ continue;
2348
+ const msg = this.preimageWitnessV1(idx, prevOutScript, sighash, amount, undefined, script, ver);
2349
+ const sig = concat(secp256k1_1.schnorr.sign(msg, privateKey, _auxRand), sighash !== SignatureHash.DEFAULT ? new Uint8Array([sighash]) : P.EMPTY);
2350
+ this.updateInput(idx, { tapScriptSig: [[{ pubKey: schnorrPub, leafHash: hash }, sig]] }, true);
2351
+ signed = true;
2352
+ }
2353
+ }
2354
+ if (!signed)
2355
+ throw new Error('No taproot scripts signed');
2356
+ return true;
2357
+ }
2358
+ else {
2359
+ // only compressed keys are supported for now
2360
+ const pubKey = _pubECDSA(privateKey);
2361
+ // TODO: replace with explicit checks
2362
+ // Check if script has public key or its has inside
2363
+ let hasPubkey = false;
2364
+ const pubKeyHash = hash160(pubKey);
2365
+ for (const i of exports.Script.decode(inputType.lastScript)) {
2366
+ if (isBytes(i) && (P.equalBytes(i, pubKey) || P.equalBytes(i, pubKeyHash)))
2367
+ hasPubkey = true;
2368
+ }
2369
+ if (!hasPubkey)
2370
+ throw new Error(`Input script doesn't have pubKey: ${inputType.lastScript}`);
2371
+ let hash;
2372
+ if (inputType.txType === 'legacy') {
2373
+ hash = this.preimageLegacy(idx, inputType.lastScript, sighash);
2374
+ }
2375
+ else if (inputType.txType === 'segwit') {
2376
+ let script = inputType.lastScript;
2377
+ // If wpkh OR sh-wpkh, wsh-wpkh is impossible, so looks ok
2378
+ if (inputType.last.type === 'wpkh')
2379
+ script = exports.OutScript.encode({ type: 'pkh', hash: inputType.last.hash });
2380
+ hash = this.preimageWitnessV0(idx, script, sighash, prevOut.amount);
2381
+ }
2382
+ else
2383
+ throw new Error(`Transaction/sign: unknown tx type: ${inputType.txType}`);
2384
+ const sig = signECDSA(hash, privateKey, this.opts.lowR);
2385
+ this.updateInput(idx, {
2386
+ partialSig: [[pubKey, concat(sig, new Uint8Array([sighash]))]],
2387
+ }, true);
2388
+ }
2389
+ return true;
2390
+ }
2391
+ // This is bad API. Will work if user creates and signs tx, but if
2392
+ // there is some complex workflow with exchanging PSBT and signing them,
2393
+ // then it is better to validate which output user signs. How could a better API look like?
2394
+ // Example: user adds input, sends to another party, then signs received input (mixer etc),
2395
+ // another user can add different input for same key and user will sign it.
2396
+ // Even worse: another user can add bip32 derivation, and spend money from different address.
2397
+ // Better api: signIdx
2398
+ sign(privateKey, allowedSighash, _auxRand) {
2399
+ let num = 0;
2400
+ for (let i = 0; i < this.inputs.length; i++) {
2401
+ try {
2402
+ if (this.signIdx(privateKey, i, allowedSighash, _auxRand))
2403
+ num++;
2404
+ }
2405
+ catch (e) { }
2406
+ }
2407
+ if (!num)
2408
+ throw new Error('No inputs signed');
2409
+ return num;
2410
+ }
2411
+ finalizeIdx(idx) {
2412
+ this.checkInputIdx(idx);
2413
+ if (this.fee < 0n)
2414
+ throw new Error('Outputs spends more than inputs amount');
2415
+ const input = this.inputs[idx];
2416
+ const inputType = getInputType(input, this.opts.allowLegacyWitnessUtxo);
2417
+ // Taproot finalize
2418
+ if (inputType.txType === 'taproot') {
2419
+ if (input.tapKeySig)
2420
+ input.finalScriptWitness = [input.tapKeySig];
2421
+ else if (input.tapLeafScript && input.tapScriptSig) {
2422
+ // Sort leafs by control block length.
2423
+ const leafs = input.tapLeafScript.sort((a, b) => exports.TaprootControlBlock.encode(a[0]).length - exports.TaprootControlBlock.encode(b[0]).length);
2424
+ for (const [cb, _script] of leafs) {
2425
+ // Last byte is version
2426
+ const script = _script.slice(0, -1);
2427
+ const ver = _script[_script.length - 1];
2428
+ const outScript = exports.OutScript.decode(script);
2429
+ const hash = (0, exports.tapLeafHash)(script, ver);
2430
+ const scriptSig = input.tapScriptSig.filter((i) => P.equalBytes(i[0].leafHash, hash));
2431
+ let signatures = [];
2432
+ if (outScript.type === 'tr_ms') {
2433
+ const m = outScript.m;
2434
+ const pubkeys = outScript.pubkeys;
2435
+ let added = 0;
2436
+ for (const pub of pubkeys) {
2437
+ const sigIdx = scriptSig.findIndex((i) => P.equalBytes(i[0].pubKey, pub));
2438
+ // Should have exact amount of signatures (more -- will fail)
2439
+ if (added === m || sigIdx === -1) {
2440
+ signatures.push(P.EMPTY);
2441
+ continue;
2442
+ }
2443
+ signatures.push(scriptSig[sigIdx][1]);
2444
+ added++;
2445
+ }
2446
+ // Should be exact same as m
2447
+ if (added !== m)
2448
+ continue;
2449
+ }
2450
+ else if (outScript.type === 'tr_ns') {
2451
+ for (const pub of outScript.pubkeys) {
2452
+ const sigIdx = scriptSig.findIndex((i) => P.equalBytes(i[0].pubKey, pub));
2453
+ if (sigIdx === -1)
2454
+ continue;
2455
+ signatures.push(scriptSig[sigIdx][1]);
2456
+ }
2457
+ if (signatures.length !== outScript.pubkeys.length)
2458
+ continue;
2459
+ }
2460
+ else if (outScript.type === 'unknown' && this.opts.allowUnknownInputs) {
2461
+ // Trying our best to sign what we can
2462
+ const scriptDecoded = exports.Script.decode(script);
2463
+ signatures = scriptSig
2464
+ .map(([{ pubKey }, signature]) => {
2465
+ const pos = scriptDecoded.findIndex((i) => isBytes(i) && P.equalBytes(i, pubKey));
2466
+ if (pos === -1)
2467
+ throw new Error('finalize/taproot: cannot find position of pubkey in script');
2468
+ return { signature, pos };
2469
+ })
2470
+ // Reverse order (because witness is stack and we take last element first from it)
2471
+ .sort((a, b) => a.pos - b.pos)
2472
+ .map((i) => i.signature);
2473
+ if (!signatures.length)
2474
+ continue;
2475
+ }
2476
+ else
2477
+ throw new Error('Finalize: Unknown tapLeafScript');
2478
+ // Witness is stack, so last element will be used first
2479
+ input.finalScriptWitness = signatures
2480
+ .reverse()
2481
+ .concat([script, exports.TaprootControlBlock.encode(cb)]);
2482
+ break;
2483
+ }
2484
+ if (!input.finalScriptWitness)
2485
+ throw new Error('finalize/taproot: empty witness');
2486
+ }
2487
+ else
2488
+ throw new Error('finalize/taproot: unknown input');
2489
+ input.finalScriptSig = P.EMPTY;
2490
+ cleanFinalInput(input);
2491
+ return;
2492
+ }
2493
+ if (!input.partialSig || !input.partialSig.length)
2494
+ throw new Error('Not enough partial sign');
2495
+ let inputScript = P.EMPTY;
2496
+ let witness = [];
2497
+ // TODO: move input scripts closer to payments/output scripts
2498
+ // Multisig
2499
+ if (inputType.last.type === 'ms') {
2500
+ const m = inputType.last.m;
2501
+ const pubkeys = inputType.last.pubkeys;
2502
+ let signatures = [];
2503
+ // partial: [pubkey, sign]
2504
+ for (const pub of pubkeys) {
2505
+ const sign = input.partialSig.find((s) => P.equalBytes(pub, s[0]));
2506
+ if (!sign)
2507
+ continue;
2508
+ signatures.push(sign[1]);
2509
+ }
2510
+ signatures = signatures.slice(0, m);
2511
+ if (signatures.length !== m) {
2512
+ throw new Error(`Multisig: wrong signatures count, m=${m} n=${pubkeys.length} signatures=${signatures.length}`);
2513
+ }
2514
+ inputScript = exports.Script.encode([0, ...signatures]);
2515
+ }
2516
+ else if (inputType.last.type === 'pk') {
2517
+ inputScript = exports.Script.encode([input.partialSig[0][1]]);
2518
+ }
2519
+ else if (inputType.last.type === 'pkh') {
2520
+ inputScript = exports.Script.encode([input.partialSig[0][1], input.partialSig[0][0]]);
2521
+ }
2522
+ else if (inputType.last.type === 'wpkh') {
2523
+ inputScript = P.EMPTY;
2524
+ witness = [input.partialSig[0][1], input.partialSig[0][0]];
2525
+ }
2526
+ else if (inputType.last.type === 'unknown' && !this.opts.allowUnknownInputs)
2527
+ throw new Error('Unknown inputs not allowed');
2528
+ // Create final scripts (generic part)
2529
+ let finalScriptSig, finalScriptWitness;
2530
+ if (inputType.type.includes('wsh-')) {
2531
+ // P2WSH
2532
+ if (inputScript.length && inputType.lastScript.length) {
2533
+ witness = exports.Script.decode(inputScript).map((i) => {
2534
+ if (i === 0)
2535
+ return P.EMPTY;
2536
+ if (isBytes(i))
2537
+ return i;
2538
+ throw new Error(`Wrong witness op=${i}`);
2539
+ });
2540
+ }
2541
+ witness = witness.concat(inputType.lastScript);
2542
+ }
2543
+ if (inputType.txType === 'segwit')
2544
+ finalScriptWitness = witness;
2545
+ if (inputType.type.startsWith('sh-wsh-')) {
2546
+ finalScriptSig = exports.Script.encode([exports.Script.encode([0, (0, sha256_1.sha256)(inputType.lastScript)])]);
2547
+ }
2548
+ else if (inputType.type.startsWith('sh-')) {
2549
+ finalScriptSig = exports.Script.encode([...exports.Script.decode(inputScript), inputType.lastScript]);
2550
+ }
2551
+ else if (inputType.type.startsWith('wsh-')) {
2552
+ }
2553
+ else if (inputType.txType !== 'segwit')
2554
+ finalScriptSig = inputScript;
2555
+ if (!finalScriptSig && !finalScriptWitness)
2556
+ throw new Error('Unknown error finalizing input');
2557
+ if (finalScriptSig)
2558
+ input.finalScriptSig = finalScriptSig;
2559
+ if (finalScriptWitness)
2560
+ input.finalScriptWitness = finalScriptWitness;
2561
+ cleanFinalInput(input);
2562
+ }
2563
+ finalize() {
2564
+ for (let i = 0; i < this.inputs.length; i++)
2565
+ this.finalizeIdx(i);
2566
+ }
2567
+ extract() {
2568
+ if (!this.isFinal)
2569
+ throw new Error('Transaction has unfinalized inputs');
2570
+ if (!this.outputs.length)
2571
+ throw new Error('Transaction has no outputs');
2572
+ if (this.fee < 0n)
2573
+ throw new Error('Outputs spends more than inputs amount');
2574
+ return this.toBytes(true, true);
2575
+ }
2576
+ combine(other) {
2577
+ for (const k of ['PSBTVersion', 'version', 'lockTime']) {
2578
+ if (this.opts[k] !== other.opts[k]) {
2579
+ throw new Error(`Transaction/combine: different ${k} this=${this.opts[k]} other=${other.opts[k]}`);
2580
+ }
2581
+ }
2582
+ for (const k of ['inputs', 'outputs']) {
2583
+ if (this[k].length !== other[k].length) {
2584
+ throw new Error(`Transaction/combine: different ${k} length this=${this[k].length} other=${other[k].length}`);
2585
+ }
2586
+ }
2587
+ const thisUnsigned = this.global.unsignedTx ? exports.RawTx.encode(this.global.unsignedTx) : P.EMPTY;
2588
+ const otherUnsigned = other.global.unsignedTx ? exports.RawTx.encode(other.global.unsignedTx) : P.EMPTY;
2589
+ if (!P.equalBytes(thisUnsigned, otherUnsigned))
2590
+ throw new Error(`Transaction/combine: different unsigned tx`);
2591
+ this.global = mergeKeyMap(PSBTGlobal, this.global, other.global);
2592
+ for (let i = 0; i < this.inputs.length; i++)
2593
+ this.updateInput(i, other.inputs[i], true);
2594
+ for (let i = 0; i < this.outputs.length; i++)
2595
+ this.updateOutput(i, other.outputs[i], true);
2596
+ return this;
2597
+ }
2598
+ clone() {
2599
+ // deepClone probably faster, but this enforces that encoding is valid
2600
+ return Transaction.fromPSBT(this.toPSBT(this.opts.PSBTVersion), this.opts);
2601
+ }
2602
+ }
2603
+ exports.Transaction = Transaction;
2604
+ // User facing API?
2605
+ // Simple pubkey address, without complex scripts
2606
+ function getAddress(type, privKey, network = exports.NETWORK) {
2607
+ if (type === 'tr') {
2608
+ return p2tr(secp256k1_1.schnorr.getPublicKey(privKey), undefined, network).address;
2609
+ }
2610
+ const pubKey = _pubECDSA(privKey);
2611
+ if (type === 'pkh')
2612
+ return (0, exports.p2pkh)(pubKey, network).address;
2613
+ if (type === 'wpkh')
2614
+ return (0, exports.p2wpkh)(pubKey, network).address;
2615
+ throw new Error(`getAddress: unknown type=${type}`);
2616
+ }
2617
+ exports.getAddress = getAddress;
2618
+ function multisig(m, pubkeys, sorted = false, witness = false) {
2619
+ const ms = (0, exports.p2ms)(m, sorted ? (0, exports._sortPubkeys)(pubkeys) : pubkeys);
2620
+ return witness ? (0, exports.p2wsh)(ms) : (0, exports.p2sh)(ms);
2621
+ }
2622
+ exports.multisig = multisig;
2623
+ function sortedMultisig(m, pubkeys, witness = false) {
2624
+ return multisig(m, pubkeys, true, witness);
2625
+ }
2626
+ exports.sortedMultisig = sortedMultisig;
2627
+ // Copy-pasted from bip32 derive, maybe do something like 'bip32.parsePath'?
2628
+ const HARDENED_OFFSET = 0x80000000;
2629
+ function bip32Path(path) {
2630
+ const out = [];
2631
+ if (!/^[mM]'?/.test(path))
2632
+ throw new Error('Path must start with "m" or "M"');
2633
+ if (/^[mM]'?$/.test(path))
2634
+ return out;
2635
+ const parts = path.replace(/^[mM]'?\//, '').split('/');
2636
+ for (const c of parts) {
2637
+ const m = /^(\d+)('?)$/.exec(c);
2638
+ if (!m || m.length !== 3)
2639
+ throw new Error(`Invalid child index: ${c}`);
2640
+ let idx = +m[1];
2641
+ if (!Number.isSafeInteger(idx) || idx >= HARDENED_OFFSET)
2642
+ throw new Error('Invalid index');
2643
+ // hardened key
2644
+ if (m[2] === "'")
2645
+ idx += HARDENED_OFFSET;
2646
+ out.push(idx);
2647
+ }
2648
+ return out;
2649
+ }
2650
+ exports.bip32Path = bip32Path;
2651
+ function PSBTCombine(psbts) {
2652
+ if (!psbts || !Array.isArray(psbts) || !psbts.length)
2653
+ throw new Error('PSBTCombine: wrong PSBT list');
2654
+ const tx = Transaction.fromPSBT(psbts[0]);
2655
+ for (let i = 1; i < psbts.length; i++)
2656
+ tx.combine(Transaction.fromPSBT(psbts[i]));
2657
+ return tx.toPSBT();
2658
+ }
2659
+ exports.PSBTCombine = PSBTCombine;
2660
+ function estimateInput(inputType, input, opts) {
2661
+ let script = P.EMPTY, witness;
2662
+ // schnorr sig is always 64 bytes. except for cases when sighash is not default!
2663
+ if (inputType.txType === 'taproot') {
2664
+ const SCHNORR_SIG_SIZE = inputType.sighash !== SignatureHash.DEFAULT ? 65 : 64;
2665
+ if (input.tapInternalKey && !P.equalBytes(input.tapInternalKey, exports.TAPROOT_UNSPENDABLE_KEY)) {
2666
+ witness = [new Uint8Array(SCHNORR_SIG_SIZE)];
2667
+ }
2668
+ else if (input.tapLeafScript) {
2669
+ // If user want to select specific leaf (which can signed, it is possible to remove all other leafs manually);
2670
+ // Sort leafs by control block length.
2671
+ const leafs = input.tapLeafScript.sort((a, b) => exports.TaprootControlBlock.encode(a[0]).length - exports.TaprootControlBlock.encode(b[0]).length);
2672
+ for (const [cb, _script] of leafs) {
2673
+ // Last byte is version
2674
+ const script = _script.slice(0, -1);
2675
+ const outScript = exports.OutScript.decode(script);
2676
+ let signatures = [];
2677
+ if (outScript.type === 'tr_ms') {
2678
+ const m = outScript.m;
2679
+ for (let i = 0; i < m; i++)
2680
+ signatures.push(new Uint8Array(SCHNORR_SIG_SIZE));
2681
+ const n = outScript.pubkeys.length - m;
2682
+ for (let i = 0; i < n; i++)
2683
+ signatures.push(P.EMPTY);
2684
+ }
2685
+ else if (outScript.type === 'tr_ns') {
2686
+ for (const _pub of outScript.pubkeys)
2687
+ signatures.push(new Uint8Array(SCHNORR_SIG_SIZE));
2688
+ }
2689
+ else
2690
+ throw new Error('Finalize: Unknown tapLeafScript');
2691
+ // Witness is stack, so last element will be used first
2692
+ witness = signatures.reverse().concat([script, exports.TaprootControlBlock.encode(cb)]);
2693
+ break;
2694
+ }
2695
+ }
2696
+ else
2697
+ throw new Error('estimateInput/taproot: unknown input');
2698
+ }
2699
+ else {
2700
+ // It is possible to grind signatures until it has minimal size (but changing fee value +N satoshi),
2701
+ // which will make estimations exact. But will be very hard for multi sig (need to make sure all signatures has small size).
2702
+ const SIG_SIZE = 72; // Maximum size of signatures
2703
+ const PUB_KEY_SIZE = 33;
2704
+ let inputScript = P.EMPTY;
2705
+ let inputWitness = [];
2706
+ if (inputType.last.type === 'ms') {
2707
+ const m = inputType.last.m;
2708
+ const sig = [0];
2709
+ for (let i = 0; i < m; i++)
2710
+ sig.push(new Uint8Array(SIG_SIZE));
2711
+ inputScript = exports.Script.encode(sig);
2712
+ }
2713
+ else if (inputType.last.type === 'pk') {
2714
+ // 71 sig + 1 sighash
2715
+ inputScript = exports.Script.encode([new Uint8Array(SIG_SIZE)]);
2716
+ }
2717
+ else if (inputType.last.type === 'pkh') {
2718
+ inputScript = exports.Script.encode([new Uint8Array(SIG_SIZE), new Uint8Array(PUB_KEY_SIZE)]);
2719
+ }
2720
+ else if (inputType.last.type === 'wpkh') {
2721
+ inputScript = P.EMPTY;
2722
+ inputWitness = [new Uint8Array(SIG_SIZE), new Uint8Array(PUB_KEY_SIZE)];
2723
+ }
2724
+ else if (inputType.last.type === 'unknown' && !opts.allowUnknownInputs)
2725
+ throw new Error('Unknown inputs not allowed');
2726
+ if (inputType.type.includes('wsh-')) {
2727
+ // P2WSH
2728
+ if (inputScript.length && inputType.lastScript.length) {
2729
+ inputWitness = exports.Script.decode(inputScript).map((i) => {
2730
+ if (i === 0)
2731
+ return P.EMPTY;
2732
+ if (isBytes(i))
2733
+ return i;
2734
+ throw new Error(`Wrong witness op=${i}`);
2735
+ });
2736
+ }
2737
+ inputWitness = inputWitness.concat(inputType.lastScript);
2738
+ }
2739
+ if (inputType.txType === 'segwit')
2740
+ witness = inputWitness;
2741
+ if (inputType.type.startsWith('sh-wsh-')) {
2742
+ script = exports.Script.encode([exports.Script.encode([0, new Uint8Array(sha256_1.sha256.outputLen)])]);
2743
+ }
2744
+ else if (inputType.type.startsWith('sh-')) {
2745
+ script = exports.Script.encode([...exports.Script.decode(inputScript), inputType.lastScript]);
2746
+ }
2747
+ else if (inputType.type.startsWith('wsh-')) {
2748
+ }
2749
+ else if (inputType.txType !== 'segwit')
2750
+ script = inputScript;
2751
+ }
2752
+ let weight = 160 + 4 * exports.VarBytes.encode(script).length;
2753
+ let hasWitnesses = false;
2754
+ if (witness) {
2755
+ weight += exports.RawWitness.encode(witness).length;
2756
+ hasWitnesses = true;
2757
+ }
2758
+ return { weight, hasWitnesses };
2759
+ }
2760
+ // Exported for tests, internal method
2761
+ const _cmpBig = (a, b) => {
2762
+ const n = a - b;
2763
+ if (n < 0n)
2764
+ return -1;
2765
+ else if (n > 0n)
2766
+ return 1;
2767
+ return 0;
2768
+ };
2769
+ exports._cmpBig = _cmpBig;
2770
+ function getScript(o, opts = {}, network = exports.NETWORK) {
2771
+ let script;
2772
+ if ('script' in o && o.script instanceof Uint8Array) {
2773
+ script = o.script;
2774
+ }
2775
+ if ('address' in o) {
2776
+ if (typeof o.address !== 'string')
2777
+ throw new Error(`Estimator: wrong output address=${o.address}`);
2778
+ script = exports.OutScript.encode(Address(network).decode(o.address));
2779
+ }
2780
+ if (!script)
2781
+ throw new Error('Estimator: wrong output script');
2782
+ if (typeof o.amount !== 'bigint')
2783
+ throw new Error(`Estimator: wrong output amount=${o.amount}`);
2784
+ if (script && !opts.allowUnknownOutputs && exports.OutScript.decode(script).type === 'unknown') {
2785
+ throw new Error('Estimator: unknown output script type, there is a chance that input is unspendable. Pass allowUnknownOutputs=true, if you sure');
2786
+ }
2787
+ if (!opts.disableScriptCheck)
2788
+ checkScript(script);
2789
+ return script;
2790
+ }
2791
+ // class, because we need to re-use normalized inputs, instead of parsing each time
2792
+ // internal stuff, exported for tests only
2793
+ class _Estimator {
2794
+ constructor(inputs, outputs, opts) {
2795
+ this.inputs = inputs;
2796
+ this.outputs = outputs;
2797
+ this.opts = opts;
2798
+ // https://github.com/bitcoin/bitcoin/blob/f90603ac6d24f5263649675d51233f1fce8b2ecd/src/policy/policy.cpp#L44
2799
+ // 32 + 4 + 1 + 107 + 4
2800
+ // Dust used in accumExact + change address algo
2801
+ // - change address: can be smaller for segwit
2802
+ // - accumExact: ???
2803
+ this.dust = 148n; // compat with coinselect
2804
+ if (typeof opts.feePerByte !== 'bigint')
2805
+ throw new Error(`Estimator: wrong feePerByte=${opts.feePerByte}`);
2806
+ if (opts.dust) {
2807
+ if (typeof opts.dust !== 'bigint')
2808
+ throw new Error(`Estimator: wrong dust=${opts.dust}`);
2809
+ this.dust = opts.dust;
2810
+ }
2811
+ const network = opts.network || exports.NETWORK;
2812
+ let amount = 0n;
2813
+ // Base weight: tx with outputs, no inputs
2814
+ let baseWeight = 32;
2815
+ for (const o of outputs) {
2816
+ const script = getScript(o, opts, opts.network);
2817
+ baseWeight += 32 + 4 * exports.VarBytes.encode(script).length;
2818
+ amount += o.amount;
2819
+ }
2820
+ if (typeof opts.changeAddress !== 'string')
2821
+ throw new Error(`Estimator: wrong change address=${opts.changeAddress}`);
2822
+ let changeWeight = baseWeight +
2823
+ 32 +
2824
+ 4 * exports.VarBytes.encode(exports.OutScript.encode(Address(network).decode(opts.changeAddress))).length;
2825
+ baseWeight += 4 * CompactSizeLen.encode(outputs.length).length;
2826
+ // If there a lot of outputs change can change fee
2827
+ changeWeight += 4 * CompactSizeLen.encode(outputs.length + 1).length;
2828
+ this.baseWeight = baseWeight;
2829
+ this.changeWeight = changeWeight;
2830
+ this.amount = amount;
2831
+ this.normalizedInputs = this.inputs.map((i) => {
2832
+ const normalized = normalizeInput(i, undefined, undefined, opts.disableScriptCheck);
2833
+ inputBeforeSign(normalized); // check fields
2834
+ const inputType = getInputType(normalized, opts.allowLegacyWitnessUtxo);
2835
+ const prev = getPrevOut(normalized);
2836
+ const estimate = estimateInput(inputType, normalized, this.opts);
2837
+ const value = prev.amount - opts.feePerByte * BigInt(toVsize(estimate.weight)); // value = amount-fee
2838
+ return { inputType, normalized, amount: prev.amount, value, estimate };
2839
+ });
2840
+ }
2841
+ checkInputIdx(idx) {
2842
+ if (!Number.isSafeInteger(idx) || 0 > idx || idx >= this.inputs.length)
2843
+ throw new Error(`Wrong input index=${idx}`);
2844
+ return idx;
2845
+ }
2846
+ sortIndices(indices) {
2847
+ return indices.slice().sort((a, b) => {
2848
+ const ai = this.normalizedInputs[this.checkInputIdx(a)];
2849
+ const bi = this.normalizedInputs[this.checkInputIdx(b)];
2850
+ const out = _cmpBytes(ai.normalized.txid, bi.normalized.txid);
2851
+ if (out !== 0)
2852
+ return out;
2853
+ return ai.normalized.index - bi.normalized.index;
2854
+ });
2855
+ }
2856
+ sortOutputs(outputs) {
2857
+ const scripts = outputs.map((o) => getScript(o, this.opts, this.opts.network));
2858
+ const indices = outputs.map((_, j) => j);
2859
+ return indices.sort((a, b) => {
2860
+ const aa = outputs[a].amount;
2861
+ const ba = outputs[b].amount;
2862
+ const out = (0, exports._cmpBig)(aa, ba);
2863
+ if (out !== 0)
2864
+ return out;
2865
+ return _cmpBytes(scripts[a], scripts[b]);
2866
+ });
2867
+ }
2868
+ getSatoshi(weigth) {
2869
+ return this.opts.feePerByte * BigInt(toVsize(weigth));
2870
+ }
2871
+ // Sort by value instead of amount
2872
+ get biggest() {
2873
+ return this.inputs
2874
+ .map((_i, j) => j)
2875
+ .sort((a, b) => (0, exports._cmpBig)(this.normalizedInputs[b].value, this.normalizedInputs[a].value));
2876
+ }
2877
+ get smallest() {
2878
+ return this.biggest.reverse();
2879
+ }
2880
+ // These assume that UTXO array has historical order.
2881
+ // Otherwise, we have no way to know which tx is oldest
2882
+ // Explorers usually give UTXO in this order.
2883
+ get oldest() {
2884
+ return this.inputs.map((_i, j) => j);
2885
+ }
2886
+ get newest() {
2887
+ return this.oldest.reverse();
2888
+ }
2889
+ // exact - like blackjack from coinselect.
2890
+ // exact(biggest) will select one big utxo which is closer to targetValue+dust, if possible.
2891
+ // If not, it will accumulate largest utxo until value is close to targetValue+dust.
2892
+ accumulate(indices, exact = false, skipNegative = true, all = false) {
2893
+ const { feePerByte } = this.opts;
2894
+ // TODO: how to handle change addresses?
2895
+ // - cost of input
2896
+ // - cost of change output (if input requires change)
2897
+ // - cost of output spending
2898
+ // Dust threshold should be significantly bigger, no point in
2899
+ // creating an output, which cannot be spent.
2900
+ // coinselect doesn't consider cost of output address for dust.
2901
+ // Changing that can actually reduce privacy
2902
+ let weight = this.opts.alwaysChange ? this.changeWeight : this.baseWeight;
2903
+ let hasWitnesses = false;
2904
+ let num = 0;
2905
+ let inputsAmount = 0n;
2906
+ const targetAmount = this.amount;
2907
+ const res = [];
2908
+ let fee;
2909
+ for (const idx of indices) {
2910
+ this.checkInputIdx(idx);
2911
+ const { estimate, amount, value } = this.normalizedInputs[idx];
2912
+ let newWeight = weight + estimate.weight;
2913
+ if (!hasWitnesses && estimate.hasWitnesses)
2914
+ newWeight += 2; // enable witness if needed
2915
+ const totalWeight = newWeight + 4 * CompactSizeLen.encode(num).length; // number of outputs can change weight
2916
+ fee = this.getSatoshi(totalWeight);
2917
+ // Best case scenario exact(biggest) -> we find biggest output, less than target+threshold
2918
+ if (exact) {
2919
+ const dust = this.dust * feePerByte;
2920
+ // skip if added value is bigger than dust
2921
+ if (amount + inputsAmount > targetAmount + fee + dust)
2922
+ continue;
2923
+ }
2924
+ // Negative: cost of using input is more than value provided (negative)
2925
+ // By default 'blackjack' mode in coinselect doesn't use that, which means
2926
+ // it will use negative output if sorted by 'smallest'
2927
+ if (skipNegative && value <= 0n)
2928
+ continue;
2929
+ weight = newWeight;
2930
+ if (estimate.hasWitnesses)
2931
+ hasWitnesses = true;
2932
+ num++;
2933
+ inputsAmount += amount;
2934
+ res.push(idx);
2935
+ // inputsAmount is enough to cover cost of tx
2936
+ if (!all && targetAmount + fee < inputsAmount)
2937
+ return { indices: res, fee, weight: totalWeight, total: inputsAmount };
2938
+ }
2939
+ if (all) {
2940
+ const newWeight = weight + 4 * CompactSizeLen.encode(num).length;
2941
+ return { indices: res, fee, weight: newWeight, total: inputsAmount };
2942
+ }
2943
+ return undefined;
2944
+ }
2945
+ // Works like coinselect default method
2946
+ default() {
2947
+ const { biggest } = this;
2948
+ const exact = this.accumulate(biggest, true, false);
2949
+ if (exact)
2950
+ return exact;
2951
+ return this.accumulate(biggest);
2952
+ }
2953
+ select(strategy) {
2954
+ if (strategy === 'all') {
2955
+ return this.accumulate(this.inputs.map((_, j) => j), false, true, true);
2956
+ }
2957
+ if (strategy === 'default')
2958
+ return this.default();
2959
+ const data = {
2960
+ Oldest: () => this.oldest,
2961
+ Newest: () => this.newest,
2962
+ Smallest: () => this.smallest,
2963
+ Biggest: () => this.biggest,
2964
+ };
2965
+ if (strategy.startsWith('exact')) {
2966
+ const [exactData, left] = strategy.slice(5).split('/');
2967
+ if (!data[exactData])
2968
+ throw new Error(`Estimator.select: wrong strategy=${strategy}`);
2969
+ strategy = left;
2970
+ const exact = this.accumulate(data[exactData](), true, true);
2971
+ if (exact)
2972
+ return exact;
2973
+ }
2974
+ if (strategy.startsWith('accum')) {
2975
+ const accumData = strategy.slice(5);
2976
+ if (!data[accumData])
2977
+ throw new Error(`Estimator.select: wrong strategy=${strategy}`);
2978
+ return this.accumulate(data[accumData]());
2979
+ }
2980
+ throw new Error(`Estimator.select: wrong strategy=${strategy}`);
2981
+ }
2982
+ result(strategy) {
2983
+ const s = this.select(strategy);
2984
+ if (!s)
2985
+ return;
2986
+ const { indices, weight, total } = s;
2987
+ let needChange = this.opts.alwaysChange;
2988
+ const changeWeight = this.opts.alwaysChange
2989
+ ? weight
2990
+ : weight + (this.changeWeight - this.baseWeight);
2991
+ const changeFee = this.getSatoshi(changeWeight);
2992
+ let fee = s.fee;
2993
+ const change = total - this.amount - changeFee;
2994
+ if (change > this.dust)
2995
+ needChange = true;
2996
+ let inputs = indices;
2997
+ let outputs = Array.from(this.outputs);
2998
+ if (needChange) {
2999
+ fee = changeFee;
3000
+ // this shouldn't happen!
3001
+ if (change < 0n)
3002
+ throw new Error(`Estimator.result: negative change=${change}`);
3003
+ outputs.push({ address: this.opts.changeAddress, amount: change });
3004
+ }
3005
+ if (this.opts.bip69) {
3006
+ inputs = this.sortIndices(inputs);
3007
+ outputs = this.sortOutputs(outputs).map((i) => outputs[i]);
3008
+ }
3009
+ const res = {
3010
+ inputs: inputs.map((i) => this.inputs[i]),
3011
+ outputs,
3012
+ fee,
3013
+ weight: this.opts.alwaysChange ? s.weight : changeWeight,
3014
+ change: !!needChange,
3015
+ };
3016
+ let tx;
3017
+ if (this.opts.createTx) {
3018
+ const { inputs, outputs } = res;
3019
+ tx = new Transaction(this.opts);
3020
+ for (const i of inputs)
3021
+ tx.addInput(i);
3022
+ for (const o of outputs)
3023
+ tx.addOutput({ ...o, script: getScript(o, this.opts, this.opts.network) });
3024
+ }
3025
+ return { ...res, tx };
3026
+ }
3027
+ }
3028
+ exports._Estimator = _Estimator;
3029
+ function selectUTXO(inputs, outputs, strategy, opts) {
3030
+ // Defaults: do we want bip69 by default?
3031
+ const _opts = { createTx: true, bip69: true, ...opts };
3032
+ const est = new _Estimator(inputs, outputs, _opts);
3033
+ return est.result(strategy);
3034
+ }
3035
+ exports.selectUTXO = selectUTXO;