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