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