forked from paulmillr/scure-btc-signer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
2642 lines (2531 loc) · 103 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*! scure-btc-signer - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import { secp256k1 as _secp, schnorr } from '@noble/curves/secp256k1';
import { sha256 } from '@noble/hashes/sha256';
import { ripemd160 } from '@noble/hashes/ripemd160';
import { hex, base58check as _b58, bech32, bech32m } from '@scure/base';
import type { Coder } from '@scure/base';
import * as P from 'micro-packed';
const { ProjectivePoint: ProjPoint, sign: _signECDSA, getPublicKey: _pubECDSA } = _secp;
const CURVE_ORDER = _secp.CURVE.n;
// Basic utility types
export type ExtendType<T, E> = {
[K in keyof T]: K extends keyof E ? E[K] | T[K] : T[K];
};
export type RequireType<T, K extends keyof T> = T & {
[P in K]-?: T[P];
};
export type Bytes = Uint8Array;
// Same as value || def, but doesn't overwrites zero ('0', 0, 0n, etc)
const def = <T>(value: T | undefined, def: T) => (value === undefined ? def : value);
const isBytes = P.isBytes;
const hash160 = (msg: Bytes) => ripemd160(sha256(msg));
const sha256x2 = (...msgs: Bytes[]) => sha256(sha256(concat(...msgs)));
const concat = P.concatBytes;
// Make base58check work
export const base58check = _b58(sha256);
export function cloneDeep<T>(obj: T): T {
if (Array.isArray(obj)) return obj.map((i) => cloneDeep(i)) as unknown as T;
// slice of nodejs Buffer doesn't copy
else if (obj instanceof Uint8Array) return Uint8Array.from(obj) as unknown as T;
// immutable
else if (['number', 'bigint', 'boolean', 'string', 'undefined'].includes(typeof obj)) return obj;
// null is object
else if (obj === null) return obj;
// should be last, so it won't catch other types
else if (typeof obj === 'object') {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) => [k, cloneDeep(v)])
) as unknown as T;
}
throw new Error(`cloneDeep: unknown type=${obj} (${typeof obj})`);
}
enum PubT {
ecdsa,
schnorr,
}
function validatePubkey(pub: Bytes, type: PubT): Bytes {
const len = pub.length;
if (type === PubT.ecdsa) {
if (len === 32) throw new Error('Expected non-Schnorr key');
ProjPoint.fromHex(pub); // does assertValidity
return pub;
} else if (type === PubT.schnorr) {
if (len !== 32) throw new Error('Expected 32-byte Schnorr key');
schnorr.utils.lift_x(schnorr.utils.bytesToNumberBE(pub));
return pub;
} else {
throw new Error('Unknown key type');
}
}
function isValidPubkey(pub: Bytes, type: PubT): boolean {
try {
validatePubkey(pub, type);
return true;
} catch (e) {
return false;
}
}
// low-r signature grinding. Used to reduce tx size by 1 byte.
// noble/secp256k1 does not support the feature: it is not used outside of BTC.
// We implement it manually, because in BTC it's common.
// Not best way, but closest to bitcoin implementation (easier to check)
const hasLowR = (sig: { r: bigint; s: bigint }) => sig.r < CURVE_ORDER / 2n;
function signECDSA(hash: Bytes, privateKey: Bytes, lowR = false): Bytes {
let sig = _signECDSA(hash, privateKey);
if (lowR && !hasLowR(sig)) {
const extraEntropy = new Uint8Array(32);
for (let cnt = 0; cnt < Number.MAX_SAFE_INTEGER; cnt++) {
extraEntropy.set(P.U32LE.encode(cnt));
sig = _signECDSA(hash, privateKey, { extraEntropy });
if (hasLowR(sig)) break;
}
}
return sig.toDERRawBytes();
}
function tapTweak(a: Bytes, b: Bytes): bigint {
const u = schnorr.utils;
const t = u.taggedHash('TapTweak', a, b);
const tn = u.bytesToNumberBE(t);
if (tn >= CURVE_ORDER) throw new Error('tweak higher than curve order');
return tn;
}
export function taprootTweakPrivKey(privKey: Uint8Array, merkleRoot = new Uint8Array()) {
const u = schnorr.utils;
const seckey0 = u.bytesToNumberBE(privKey); // seckey0 = int_from_bytes(seckey0)
const P = ProjPoint.fromPrivateKey(seckey0); // P = point_mul(G, seckey0)
// seckey = seckey0 if has_even_y(P) else SECP256K1_ORDER - seckey0
const seckey = P.hasEvenY() ? seckey0 : u.mod(-seckey0, CURVE_ORDER);
const xP = u.pointToBytes(P);
// t = int_from_bytes(tagged_hash("TapTweak", bytes_from_int(x(P)) + h)); >= SECP256K1_ORDER check
const t = tapTweak(xP, merkleRoot);
// bytes_from_int((seckey + t) % SECP256K1_ORDER)
return u.numberToBytesBE(u.mod(seckey + t, CURVE_ORDER), 32);
}
export function taprootTweakPubkey(pubKey: Uint8Array, h: Uint8Array): [Uint8Array, number] {
const u = schnorr.utils;
const t = tapTweak(pubKey, h); // t = int_from_bytes(tagged_hash("TapTweak", pubkey + h))
const P = u.lift_x(u.bytesToNumberBE(pubKey)); // P = lift_x(int_from_bytes(pubkey))
const Q = P.add(ProjPoint.fromPrivateKey(t)); // Q = point_add(P, point_mul(G, t))
const parity = Q.hasEvenY() ? 0 : 1; // 0 if has_even_y(Q) else 1
return [u.pointToBytes(Q), parity]; // bytes_from_int(x(Q))
}
// Can be 33 or 64 bytes
const PubKeyECDSA = P.validate(P.bytes(null), (pub) => validatePubkey(pub, PubT.ecdsa));
const PubKeySchnorr = P.validate(P.bytes(32), (pub) => validatePubkey(pub, PubT.schnorr));
const SignatureSchnorr = P.validate(P.bytes(null), (sig) => {
if (sig.length !== 64 && sig.length !== 65)
throw new Error('Schnorr signature should be 64 or 65 bytes long');
return sig;
});
function uniqPubkey(pubkeys: Bytes[]) {
const map: Record<string, boolean> = {};
for (const pub of pubkeys) {
const key = hex.encode(pub);
if (map[key]) throw new Error(`Multisig: non-uniq pubkey: ${pubkeys.map(hex.encode)}`);
map[key] = true;
}
}
export const NETWORK = {
bech32: 'bc',
pubKeyHash: 0x00,
scriptHash: 0x05,
wif: 0x80,
};
export const TEST_NETWORK: typeof NETWORK = {
bech32: 'tb',
pubKeyHash: 0x6f,
scriptHash: 0xc4,
wif: 0xef,
};
export const PRECISION = 8;
export const DEFAULT_VERSION = 2;
export const DEFAULT_LOCKTIME = 0;
export const DEFAULT_SEQUENCE = 4294967295;
const EMPTY32 = new Uint8Array(32);
// Utils
export const Decimal = P.coders.decimal(PRECISION);
// Exported for tests, internal method
export function _cmpBytes(a: Bytes, b: Bytes) {
if (!isBytes(a) || !isBytes(b)) throw new Error(`cmp: wrong type a=${typeof a} b=${typeof b}`);
// -1 -> a<b, 0 -> a==b, 1 -> a>b
const len = Math.min(a.length, b.length);
for (let i = 0; i < len; i++) if (a[i] != b[i]) return Math.sign(a[i] - b[i]);
return Math.sign(a.length - b.length);
}
// Coders
// prettier-ignore
export enum OP {
OP_0 = 0x00, PUSHDATA1 = 0x4c, PUSHDATA2, PUSHDATA4, '1NEGATE',
RESERVED = 0x50,
OP_1, OP_2, OP_3, OP_4, OP_5, OP_6, OP_7, OP_8,
OP_9, OP_10, OP_11, OP_12, OP_13, OP_14, OP_15, OP_16,
// Control
NOP, VER, IF, NOTIF, VERIF, VERNOTIF, ELSE, ENDIF, VERIFY, RETURN,
// Stack
TOALTSTACK, FROMALTSTACK, '2DROP', '2DUP', '3DUP', '2OVER', '2ROT', '2SWAP',
IFDUP, DEPTH, DROP, DUP, NIP, OVER, PICK, ROLL, ROT, SWAP, TUCK,
// Splice
CAT, SUBSTR, LEFT, RIGHT, SIZE,
// Boolean logic
INVERT, AND, OR, XOR, EQUAL, EQUALVERIFY, RESERVED1, RESERVED2,
// Numbers
'1ADD', '1SUB', '2MUL', '2DIV',
NEGATE, ABS, NOT, '0NOTEQUAL',
ADD, SUB, MUL, DIV, MOD, LSHIFT, RSHIFT, BOOLAND, BOOLOR,
NUMEQUAL, NUMEQUALVERIFY, NUMNOTEQUAL, LESSTHAN, GREATERTHAN,
LESSTHANOREQUAL, GREATERTHANOREQUAL, MIN, MAX, WITHIN,
// Crypto
RIPEMD160, SHA1, SHA256, HASH160, HASH256, CODESEPARATOR,
CHECKSIG, CHECKSIGVERIFY, CHECKMULTISIG, CHECKMULTISIGVERIFY,
// Expansion
NOP1, CHECKLOCKTIMEVERIFY, CHECKSEQUENCEVERIFY, NOP4, NOP5, NOP6, NOP7, NOP8, NOP9, NOP10,
// BIP 342
CHECKSIGADD,
// Invalid
INVALID = 0xff,
}
type ScriptOP = keyof typeof OP | Bytes | number;
type ScriptType = ScriptOP[];
// Converts script bytes to parsed script
// 5221030000000000000000000000000000000000000000000000000000000000000001210300000000000000000000000000000000000000000000000000000000000000022103000000000000000000000000000000000000000000000000000000000000000353ae
// =>
// OP_2
// 030000000000000000000000000000000000000000000000000000000000000001
// 030000000000000000000000000000000000000000000000000000000000000002
// 030000000000000000000000000000000000000000000000000000000000000003
// OP_3
// CHECKMULTISIG
export const Script: P.CoderType<ScriptType> = P.wrap({
encodeStream: (w: P.Writer, value: ScriptType) => {
for (let o of value) {
if (typeof o === 'string') {
if (OP[o] === undefined) throw new Error(`Unknown opcode=${o}`);
w.byte(OP[o]);
continue;
} else if (typeof o === 'number') {
if (o === 0x00) {
w.byte(0x00);
continue;
} else if (1 <= o && o <= 16) {
w.byte(OP.OP_1 - 1 + o);
continue;
}
}
// Encode big numbers
if (typeof o === 'number') o = ScriptNum().encode(BigInt(o));
if (!isBytes(o)) throw new Error(`Wrong Script OP=${o} (${typeof o})`);
// Bytes
const len = o.length;
if (len < OP.PUSHDATA1) w.byte(len);
else if (len <= 0xff) {
w.byte(OP.PUSHDATA1);
w.byte(len);
} else if (len <= 0xffff) {
w.byte(OP.PUSHDATA2);
w.bytes(P.U16LE.encode(len));
} else {
w.byte(OP.PUSHDATA4);
w.bytes(P.U32LE.encode(len));
}
w.bytes(o);
}
},
decodeStream: (r: P.Reader): ScriptType => {
const out: ScriptType = [];
while (!r.isEnd()) {
const cur = r.byte();
// if 0 < cur < 78
if (OP.OP_0 < cur && cur <= OP.PUSHDATA4) {
let len;
if (cur < OP.PUSHDATA1) len = cur;
else if (cur === OP.PUSHDATA1) len = P.U8.decodeStream(r);
else if (cur === OP.PUSHDATA2) len = P.U16LE.decodeStream(r);
else if (cur === OP.PUSHDATA4) len = P.U32LE.decodeStream(r);
else throw new Error('Should be not possible');
out.push(r.bytes(len));
} else if (cur === 0x00) {
out.push(0);
} else if (OP.OP_1 <= cur && cur <= OP.OP_16) {
out.push(cur - (OP.OP_1 - 1));
} else {
const op = OP[cur] as keyof typeof OP;
if (op === undefined) throw new Error(`Unknown opcode=${cur.toString(16)}`);
out.push(op);
}
}
return out;
},
});
// We can encode almost any number as ScriptNum, however, parsing will be a problem
// since we can't know if buffer is a number or something else.
export function ScriptNum(bytesLimit = 6, forceMinimal = false): P.CoderType<bigint> {
return P.wrap({
encodeStream: (w: P.Writer, value: bigint) => {
if (value === 0n) return;
const neg = value < 0;
const val = BigInt(value);
const nums = [];
for (let abs = neg ? -val : val; abs; abs >>= 8n) nums.push(Number(abs & 0xffn));
if (nums[nums.length - 1] >= 0x80) nums.push(neg ? 0x80 : 0);
else if (neg) nums[nums.length - 1] |= 0x80;
w.bytes(new Uint8Array(nums));
},
decodeStream: (r: P.Reader): bigint => {
const len = r.leftBytes;
if (len > bytesLimit)
throw new Error(`ScriptNum: number (${len}) bigger than limit=${bytesLimit}`);
if (len === 0) return 0n;
if (forceMinimal) {
// MSB is zero (without sign bit) -> not minimally encoded
if ((r.data[len - 1] & 0x7f) === 0) {
// exception
if (len <= 1 || (r.data[len - 2] & 0x80) === 0)
throw new Error('Non-minimally encoded ScriptNum');
}
}
let last = 0;
let res = 0n;
for (let i = 0; i < len; ++i) {
last = r.byte();
res |= BigInt(last) << (8n * BigInt(i));
}
if (last >= 0x80) {
res &= (2n ** BigInt(len * 8) - 1n) >> 1n;
res = -res;
}
return res;
},
});
}
export function OpToNum(op: ScriptOP, bytesLimit = 4, forceMinimal = true) {
if (typeof op === 'number') return op;
if (isBytes(op)) {
try {
const val = ScriptNum(bytesLimit, forceMinimal).decode(op);
if (val > Number.MAX_SAFE_INTEGER) return;
return Number(val);
} catch (e) {
return;
}
}
return;
}
// BTC specific variable length integer encoding
// https://en.bitcoin.it/wiki/Protocol_documentation#Variable_length_integer
const CSLimits: Record<number, [number, number, bigint, bigint]> = {
0xfd: [0xfd, 2, 253n, 65535n],
0xfe: [0xfe, 4, 65536n, 4294967295n],
0xff: [0xff, 8, 4294967296n, 18446744073709551615n],
};
export const CompactSize: P.CoderType<bigint> = P.wrap({
encodeStream: (w: P.Writer, value: bigint) => {
if (typeof value === 'number') value = BigInt(value);
if (0n <= value && value <= 252n) return w.byte(Number(value));
for (const [flag, bytes, start, stop] of Object.values(CSLimits)) {
if (start > value || value > stop) continue;
w.byte(flag);
for (let i = 0; i < bytes; i++) w.byte(Number((value >> (8n * BigInt(i))) & 0xffn));
return;
}
throw w.err(`VarInt too big: ${value}`);
},
decodeStream: (r: P.Reader): bigint => {
const b0 = r.byte();
if (b0 <= 0xfc) return BigInt(b0);
const [_, bytes, start] = CSLimits[b0];
let num = 0n;
for (let i = 0; i < bytes; i++) num |= BigInt(r.byte()) << (8n * BigInt(i));
if (num < start) throw r.err(`Wrong CompactSize(${8 * bytes})`);
return num;
},
});
// Same thing, but in number instead of bigint. Checks for safe integer inside
const CompactSizeLen = P.apply(CompactSize, P.coders.number);
// Array of size <CompactSize>
export const BTCArray = <T>(t: P.CoderType<T>): P.CoderType<T[]> => P.array(CompactSize, t);
// ui8a of size <CompactSize>
export const VarBytes = P.bytes(CompactSize);
export const RawInput = P.struct({
txid: P.bytes(32, true), // hash(prev_tx),
index: P.U32LE, // output number of previous tx
finalScriptSig: VarBytes, // btc merges input and output script, executes it. If ok = tx passes
sequence: P.U32LE, // ?
});
export const RawOutput = P.struct({ amount: P.U64LE, script: VarBytes });
const EMPTY_OUTPUT: P.UnwrapCoder<typeof RawOutput> = {
amount: 0xffffffffffffffffn,
script: P.EMPTY,
};
// SegWit v0 stack of witness buffers
export const RawWitness = P.array(CompactSizeLen, VarBytes);
// https://en.bitcoin.it/wiki/Protocol_documentation#tx
const _RawTx = P.struct({
version: P.I32LE,
segwitFlag: P.flag(new Uint8Array([0x00, 0x01])),
inputs: BTCArray(RawInput),
outputs: BTCArray(RawOutput),
witnesses: P.flagged('segwitFlag', P.array('inputs/length', RawWitness)),
// < 500000000 Block number at which this transaction is unlocked
// >= 500000000 UNIX timestamp at which this transaction is unlocked
// Handled as part of PSBTv2
lockTime: P.U32LE,
});
function validateRawTx(tx: P.UnwrapCoder<typeof _RawTx>) {
if (tx.segwitFlag && tx.witnesses && !tx.witnesses.length)
throw new Error('Segwit flag with empty witnesses array');
return tx;
}
export const RawTx = P.validate(_RawTx, validateRawTx);
// PSBT BIP174, BIP370, BIP371
type PSBTKeyCoder = P.CoderType<any> | false;
type PSBTKeyMapInfo = Readonly<
[
number,
PSBTKeyCoder,
any,
readonly number[], // versionsRequiringInclusion
readonly number[], // versionsAllowsInclusion
boolean // silentIgnore
]
>;
function PSBTKeyInfo(info: PSBTKeyMapInfo) {
const [type, kc, vc, reqInc, allowInc, silentIgnore] = info;
return { type, kc, vc, reqInc, allowInc, silentIgnore };
}
type PSBTKeyMap = Record<string, PSBTKeyMapInfo>;
const BIP32Der = P.struct({
fingerprint: P.U32BE,
path: P.array(null, P.U32LE),
});
// Complex structure for PSBT fields
// <control byte with leaf version and parity bit> <internal key p> <C> <E> <AB>
const _TaprootControlBlock = P.struct({
version: P.U8, // With parity :(
internalKey: P.bytes(32),
merklePath: P.array(null, P.bytes(32)),
});
export const TaprootControlBlock = P.validate(_TaprootControlBlock, (cb) => {
if (cb.merklePath.length > 128)
throw new Error('TaprootControlBlock: merklePath should be of length 0..128 (inclusive)');
return cb;
});
const TaprootBIP32Der = P.struct({
hashes: P.array(CompactSizeLen, P.bytes(32)),
der: BIP32Der,
});
// The 78 byte serialized extended public key as defined by BIP 32.
const GlobalXPUB = P.bytes(78);
const tapScriptSigKey = P.struct({ pubKey: PubKeySchnorr, leafHash: P.bytes(32) });
// {<8-bit uint depth> <8-bit uint leaf version> <compact size uint scriptlen> <bytes script>}*
const tapTree = P.array(
null,
P.struct({
depth: P.U8,
version: P.U8,
script: VarBytes,
})
);
const BytesInf = P.bytes(null); // Bytes will conflict with Bytes type
const Bytes20 = P.bytes(20);
const Bytes32 = P.bytes(32);
// versionsRequiringExclusing = !versionsAllowsInclusion (as set)
// {name: [tag, keyCoder, valueCoder, versionsRequiringInclusion, versionsRequiringExclusing, versionsAllowsInclusion, silentIgnore]}
// SilentIgnore: we use some v2 fields for v1 representation too, so we just clean them before serialize
// Tables from BIP-0174 (https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki)
// prettier-ignore
const PSBTGlobal = {
unsignedTx: [0x00, false, RawTx, [0], [0], false],
xpub: [0x01, GlobalXPUB, BIP32Der, [], [0, 2], false],
txVersion: [0x02, false, P.U32LE, [2], [2], false],
fallbackLocktime: [0x03, false, P.U32LE, [], [2], false],
inputCount: [0x04, false, CompactSizeLen, [2], [2], false],
outputCount: [0x05, false, CompactSizeLen, [2], [2], false],
txModifiable: [0x06, false, P.U8, [], [2], false], // TODO: bitfield
version: [0xfb, false, P.U32LE, [], [0, 2], false],
proprietary: [0xfc, BytesInf, BytesInf, [], [0, 2], false],
} as const;
// prettier-ignore
const PSBTInput = {
nonWitnessUtxo: [0x00, false, RawTx, [], [0, 2], false],
witnessUtxo: [0x01, false, RawOutput, [], [0, 2], false],
partialSig: [0x02, PubKeyECDSA, BytesInf, [], [0, 2], false],
sighashType: [0x03, false, P.U32LE, [], [0, 2], false],
redeemScript: [0x04, false, BytesInf, [], [0, 2], false],
witnessScript: [0x05, false, BytesInf, [], [0, 2], false],
bip32Derivation: [0x06, PubKeyECDSA, BIP32Der, [], [0, 2], false],
finalScriptSig: [0x07, false, BytesInf, [], [0, 2], false],
finalScriptWitness: [0x08, false, RawWitness, [], [0, 2], false],
porCommitment: [0x09, false, BytesInf, [], [0, 2], false],
ripemd160: [0x0a, Bytes20, BytesInf, [], [0, 2], false],
sha256: [0x0b, Bytes32, BytesInf, [], [0, 2], false],
hash160: [0x0c, Bytes20, BytesInf, [], [0, 2], false],
hash256: [0x0d, Bytes32, BytesInf, [], [0, 2], false],
txid: [0x0e, false, Bytes32, [2], [2], true],
index: [0x0f, false, P.U32LE, [2], [2], true],
sequence: [0x10, false, P.U32LE, [], [2], true],
requiredTimeLocktime: [0x11, false, P.U32LE, [], [2], false],
requiredHeightLocktime: [0x12, false, P.U32LE, [], [2], false],
tapKeySig: [0x13, false, SignatureSchnorr, [], [0, 2], false],
tapScriptSig: [0x14, tapScriptSigKey, SignatureSchnorr, [], [0, 2], false],
tapLeafScript: [0x15, TaprootControlBlock, BytesInf, [], [0, 2], false],
tapBip32Derivation: [0x16, Bytes32, TaprootBIP32Der, [], [0, 2], false],
tapInternalKey: [0x17, false, PubKeySchnorr, [], [0, 2], false],
tapMerkleRoot: [0x18, false, Bytes32, [], [0, 2], false],
proprietary: [0xfc, BytesInf, BytesInf, [], [0, 2], false],
} as const;
// All other keys removed when finalizing
const PSBTInputFinalKeys: (keyof TransactionInput)[] = [
'txid',
'sequence',
'index',
'witnessUtxo',
'nonWitnessUtxo',
'finalScriptSig',
'finalScriptWitness',
'unknown',
];
// Can be modified even on signed input
const PSBTInputUnsignedKeys: (keyof TransactionInput)[] = [
'partialSig',
'finalScriptSig',
'finalScriptWitness',
'tapKeySig',
'tapScriptSig',
];
// prettier-ignore
const PSBTOutput = {
redeemScript: [0x00, false, BytesInf, [], [0, 2], false],
witnessScript: [0x01, false, BytesInf, [], [0, 2], false],
bip32Derivation: [0x02, PubKeyECDSA, BIP32Der, [], [0, 2], false],
amount: [0x03, false, P.I64LE, [2], [2], true],
script: [0x04, false, BytesInf, [2], [2], true],
tapInternalKey: [0x05, false, PubKeySchnorr, [], [0, 2], false],
tapTree: [0x06, false, tapTree, [], [0, 2], false],
tapBip32Derivation: [0x07, PubKeySchnorr, TaprootBIP32Der, [], [0, 2], false],
proprietary: [0xfc, BytesInf, BytesInf, [], [0, 2], false],
} as const;
// Can be modified even on signed input
const PSBTOutputUnsignedKeys: (keyof typeof PSBTOutput)[] = [];
const PSBTKeyPair = P.array(
P.NULL,
P.struct({
// <key> := <keylen> <keytype> <keydata> WHERE keylen = len(keytype)+len(keydata)
key: P.prefix(CompactSizeLen, P.struct({ type: CompactSizeLen, key: P.bytes(null) })),
// <value> := <valuelen> <valuedata>
value: P.bytes(CompactSizeLen),
})
);
const PSBTUnknownKey = P.struct({ type: CompactSizeLen, key: P.bytes(null) });
type PSBTUnknownFields = { unknown?: [P.UnwrapCoder<typeof PSBTUnknownKey>, Bytes][] };
type PSBTKeyMapKeys<T extends PSBTKeyMap> = {
-readonly [K in keyof T]?: T[K][1] extends false
? P.UnwrapCoder<T[K][2]>
: [P.UnwrapCoder<T[K][1]>, P.UnwrapCoder<T[K][2]>][];
} & PSBTUnknownFields;
// Key cannot be 'unknown', value coder cannot be array for elements with empty key
function PSBTKeyMap<T extends PSBTKeyMap>(psbtEnum: T): P.CoderType<PSBTKeyMapKeys<T>> {
// -> Record<type, [keyName, ...coders]>
const byType: Record<number, [string, PSBTKeyCoder, P.CoderType<any>]> = {};
for (const k in psbtEnum) {
const [num, kc, vc] = psbtEnum[k];
byType[num] = [k, kc, vc];
}
return P.wrap({
encodeStream: (w: P.Writer, value: PSBTKeyMapKeys<T>) => {
let out: P.UnwrapCoder<typeof PSBTKeyPair> = [];
// Because we use order of psbtEnum, keymap is sorted here
for (const name in psbtEnum) {
const val = value[name];
if (val === undefined) continue;
const [type, kc, vc] = psbtEnum[name];
if (!kc) {
out.push({ key: { type, key: P.EMPTY }, value: vc.encode(val) });
} else {
// Low level interface, returns keys as is (with duplicates). Useful for debug
const kv: [Bytes, Bytes][] = val!.map(
([k, v]: [P.UnwrapCoder<typeof kc>, P.UnwrapCoder<typeof vc>]) => [
kc.encode(k),
vc.encode(v),
]
);
// sort by keys
kv.sort((a, b) => _cmpBytes(a[0], b[0]));
for (const [key, value] of kv) out.push({ key: { key, type }, value });
}
}
if (value.unknown) {
value.unknown.sort((a, b) => _cmpBytes(a[0].key, b[0].key));
for (const [k, v] of value.unknown) out.push({ key: k, value: v });
}
PSBTKeyPair.encodeStream(w, out);
},
decodeStream: (r: P.Reader): PSBTKeyMapKeys<T> => {
const raw = PSBTKeyPair.decodeStream(r);
const out: any = {};
const noKey: Record<string, true> = {};
for (const elm of raw) {
let name = 'unknown';
let key: any = elm.key.key;
let value = elm.value;
if (byType[elm.key.type]) {
const [_name, kc, vc] = byType[elm.key.type];
name = _name;
if (!kc && key.length) {
throw new Error(
`PSBT: Non-empty key for ${name} (key=${hex.encode(key)} value=${hex.encode(value)}`
);
}
key = kc ? kc.decode(key) : undefined;
value = vc.decode(value);
if (!kc) {
if (out[name]) throw new Error(`PSBT: Same keys: ${name} (key=${key} value=${value})`);
out[name] = value;
noKey[name] = true;
continue;
}
} else {
// For unknown: add key type inside key
key = { type: elm.key.type, key: elm.key.key };
}
// Only keyed elements at this point
if (noKey[name])
throw new Error(`PSBT: Key type with empty key and no key=${name} val=${value}`);
if (!out[name]) out[name] = [];
out[name].push([key, value]);
}
return out;
},
});
}
// Basic sanity check for scripts
function checkWSH(s: OutWSHType, witnessScript: Bytes) {
if (!P.equalBytes(s.hash, sha256(witnessScript)))
throw new Error('checkScript: wsh wrong witnessScript hash');
const w = OutScript.decode(witnessScript);
if (w.type === 'tr' || w.type === 'tr_ns' || w.type === 'tr_ms')
throw new Error(`checkScript: P2${w.type} cannot be wrapped in P2SH`);
if (w.type === 'wpkh' || w.type === 'sh')
throw new Error(`checkScript: P2${w.type} cannot be wrapped in P2WSH`);
}
function checkScript(script?: Bytes, redeemScript?: Bytes, witnessScript?: Bytes) {
if (script) {
const s = OutScript.decode(script);
// ms||pk maybe work, but there will be no address, hard to spend
if (s.type === 'tr_ns' || s.type === 'tr_ms' || s.type === 'ms' || s.type == 'pk')
throw new Error(`checkScript: non-wrapped ${s.type}`);
if (s.type === 'sh' && redeemScript) {
if (!P.equalBytes(s.hash, hash160(redeemScript)))
throw new Error('checkScript: sh wrong redeemScript hash');
const r = OutScript.decode(redeemScript);
if (r.type === 'tr' || r.type === 'tr_ns' || r.type === 'tr_ms')
throw new Error(`checkScript: P2${r.type} cannot be wrapped in P2SH`);
// Not sure if this unspendable, but we cannot represent this via PSBT
if (r.type === 'sh') throw new Error('checkScript: P2SH cannot be wrapped in P2SH');
}
if (s.type === 'wsh' && witnessScript) checkWSH(s, witnessScript);
}
if (redeemScript) {
const r = OutScript.decode(redeemScript);
if (r.type === 'wsh' && witnessScript) checkWSH(r, witnessScript);
}
}
const PSBTInputCoder = P.validate(PSBTKeyMap(PSBTInput), (i) => {
if (i.finalScriptWitness && !i.finalScriptWitness.length)
throw new Error('validateInput: wmpty finalScriptWitness');
//if (i.finalScriptSig && !i.finalScriptSig.length) throw new Error('validateInput: empty finalScriptSig');
if (i.partialSig && !i.partialSig.length) throw new Error('Empty partialSig');
if (i.partialSig) for (const [k] of i.partialSig) validatePubkey(k, PubT.ecdsa);
if (i.bip32Derivation) for (const [k] of i.bip32Derivation) validatePubkey(k, PubT.ecdsa);
// Locktime = unsigned little endian integer greater than or equal to 500000000 representing
if (i.requiredTimeLocktime !== undefined && i.requiredTimeLocktime < 500000000)
throw new Error(`validateInput: wrong timeLocktime=${i.requiredTimeLocktime}`);
// unsigned little endian integer greater than 0 and less than 500000000
if (
i.requiredHeightLocktime !== undefined &&
(i.requiredHeightLocktime <= 0 || i.requiredHeightLocktime >= 500000000)
)
throw new Error(`validateInput: wrong heighLocktime=${i.requiredHeightLocktime}`);
if (i.nonWitnessUtxo && i.index !== undefined) {
const last = i.nonWitnessUtxo.outputs.length - 1;
if (i.index > last) throw new Error(`validateInput: index(${i.index}) not in nonWitnessUtxo`);
const prevOut = i.nonWitnessUtxo.outputs[i.index];
if (
i.witnessUtxo &&
(!P.equalBytes(i.witnessUtxo.script, prevOut.script) ||
i.witnessUtxo.amount !== prevOut.amount)
)
throw new Error('validateInput: witnessUtxo different from nonWitnessUtxo');
}
if (i.tapLeafScript) {
// tap leaf version appears here twice: in control block and at the end of script
for (const [k, v] of i.tapLeafScript) {
if ((k.version & 0b1111_1110) !== v[v.length - 1])
throw new Error('validateInput: tapLeafScript version mimatch');
if (v[v.length - 1] & 1)
throw new Error('validateInput: tapLeafScript version has parity bit!');
}
}
// Validate txid for nonWitnessUtxo is correct
if (i.nonWitnessUtxo && i.index && i.txid) {
const outputs = i.nonWitnessUtxo.outputs;
if (outputs.length - 1 < i.index) throw new Error('nonWitnessUtxo: incorect output index');
const tx = Transaction.fromRaw(RawTx.encode(i.nonWitnessUtxo));
const txid = hex.encode(i.txid);
if (tx.id !== txid) throw new Error(`nonWitnessUtxo: wrong txid, exp=${txid} got=${tx.id}`);
}
return i;
});
const PSBTOutputCoder = P.validate(PSBTKeyMap(PSBTOutput), (o) => {
if (o.bip32Derivation) for (const [k] of o.bip32Derivation) validatePubkey(k, PubT.ecdsa);
return o;
});
const PSBTGlobalCoder = P.validate(PSBTKeyMap(PSBTGlobal), (g) => {
const version = g.version || 0;
if (version === 0) {
if (!g.unsignedTx) throw new Error('PSBTv0: missing unsignedTx');
if (g.unsignedTx.segwitFlag || g.unsignedTx.witnesses)
throw new Error('PSBTv0: witness in unsingedTx');
for (const inp of g.unsignedTx.inputs)
if (inp.finalScriptSig && inp.finalScriptSig.length)
throw new Error('PSBTv0: input scriptSig found in unsignedTx');
}
return g;
});
export const _RawPSBTV0 = P.struct({
magic: P.magic(P.string(new Uint8Array([0xff])), 'psbt'),
global: PSBTGlobalCoder,
inputs: P.array('global/unsignedTx/inputs/length', PSBTInputCoder),
outputs: P.array(null, PSBTOutputCoder),
});
export const _RawPSBTV2 = P.struct({
magic: P.magic(P.string(new Uint8Array([0xff])), 'psbt'),
global: PSBTGlobalCoder,
inputs: P.array('global/inputCount', PSBTInputCoder),
outputs: P.array('global/outputCount', PSBTOutputCoder),
});
export type PSBTRaw = typeof _RawPSBTV0 | typeof _RawPSBTV2;
export const _DebugPSBT = P.struct({
magic: P.magic(P.string(new Uint8Array([0xff])), 'psbt'),
items: P.array(
null,
P.apply(
P.array(P.NULL, P.tuple([P.hex(CompactSizeLen), P.bytes(CompactSize)])),
P.coders.dict()
)
),
});
function validatePSBTFields<T extends PSBTKeyMap>(
version: number,
info: T,
lst: PSBTKeyMapKeys<T>
) {
for (const k in lst) {
if (k === 'unknown') continue;
if (!info[k]) continue;
const { allowInc } = PSBTKeyInfo(info[k]);
if (!allowInc.includes(version)) throw new Error(`PSBTv${version}: field ${k} is not allowed`);
}
for (const k in info) {
const { reqInc } = PSBTKeyInfo(info[k]);
if (reqInc.includes(version) && lst[k] === undefined)
throw new Error(`PSBTv${version}: missing required field ${k}`);
}
}
function cleanPSBTFields<T extends PSBTKeyMap>(version: number, info: T, lst: PSBTKeyMapKeys<T>) {
const out: PSBTKeyMapKeys<T> = {};
for (const _k in lst) {
const k = _k as string & keyof PSBTKeyMapKeys<T>;
if (k !== 'unknown') {
if (!info[k]) continue;
const { allowInc, silentIgnore } = PSBTKeyInfo(info[k]);
if (!allowInc.includes(version)) {
if (silentIgnore) continue;
throw new Error(
`Failed to serialize in PSBTv${version}: ${k} but versions allows inclusion=${allowInc}`
);
}
}
out[k] = lst[k];
}
return out;
}
function validatePSBT(tx: P.UnwrapCoder<PSBTRaw>) {
const version = (tx && tx.global && tx.global.version) || 0;
validatePSBTFields(version, PSBTGlobal, tx.global);
for (const i of tx.inputs) validatePSBTFields(version, PSBTInput, i);
for (const o of tx.outputs) validatePSBTFields(version, PSBTOutput, o);
// We allow only one empty element at the end of map (compat with bitcoinjs-lib bug)
const inputCount = !version ? tx.global.unsignedTx!.inputs.length : tx.global.inputCount!;
if (tx.inputs.length < inputCount) throw new Error('Not enough inputs');
const inputsLeft = tx.inputs.slice(inputCount);
if (inputsLeft.length > 1 || (inputsLeft.length && Object.keys(inputsLeft[0]).length))
throw new Error(`Unexpected inputs left in tx=${inputsLeft}`);
// Same for inputs
const outputCount = !version ? tx.global.unsignedTx!.outputs.length : tx.global.outputCount!;
if (tx.outputs.length < outputCount) throw new Error('Not outputs inputs');
const outputsLeft = tx.outputs.slice(outputCount);
if (outputsLeft.length > 1 || (outputsLeft.length && Object.keys(outputsLeft[0]).length))
throw new Error(`Unexpected outputs left in tx=${outputsLeft}`);
return tx;
}
function mergeKeyMap<T extends PSBTKeyMap>(
psbtEnum: T,
val: PSBTKeyMapKeys<T>,
cur?: PSBTKeyMapKeys<T>,
allowedFields?: (keyof PSBTKeyMapKeys<T>)[]
): PSBTKeyMapKeys<T> {
const res: PSBTKeyMapKeys<T> = { ...cur, ...val };
// All arguments can be provided as hex
for (const k in psbtEnum) {
const key = k as keyof typeof psbtEnum;
const [_, kC, vC] = psbtEnum[key];
type _KV = [P.UnwrapCoder<typeof kC>, P.UnwrapCoder<typeof vC>];
const cannotChange = allowedFields && !allowedFields.includes(k);
if (val[k] === undefined && k in val) {
if (cannotChange) throw new Error(`Cannot remove signed field=${k}`);
delete res[k];
} else if (kC) {
const oldKV = (cur && cur[k] ? cur[k] : []) as _KV[];
let newKV = val[key] as _KV[];
if (newKV) {
if (!Array.isArray(newKV)) throw new Error(`keyMap(${k}): KV pairs should be [k, v][]`);
// Decode hex in k-v
newKV = newKV.map((val: _KV): _KV => {
if (val.length !== 2) throw new Error(`keyMap(${k}): KV pairs should be [k, v][]`);
return [
typeof val[0] === 'string' ? kC.decode(hex.decode(val[0])) : val[0],
typeof val[1] === 'string' ? vC.decode(hex.decode(val[1])) : val[1],
];
});
const map: Record<string, _KV> = {};
const add = (kStr: string, k: _KV[0], v: _KV[1]) => {
if (map[kStr] === undefined) {
map[kStr] = [k, v];
return;
}
const oldVal = hex.encode(vC.encode(map[kStr][1]));
const newVal = hex.encode(vC.encode(v));
if (oldVal !== newVal)
throw new Error(
`keyMap(${key as string}): same key=${kStr} oldVal=${oldVal} newVal=${newVal}`
);
};
for (const [k, v] of oldKV) {
const kStr = hex.encode(kC.encode(k));
add(kStr, k, v);
}
for (const [k, v] of newKV) {
const kStr = hex.encode(kC.encode(k));
// undefined removes previous value
if (v === undefined) {
if (cannotChange) throw new Error(`Cannot remove signed field=${key as string}/${k}`);
delete map[kStr];
} else add(kStr, k, v);
}
(res as any)[key] = Object.values(map) as _KV[];
}
} else if (typeof res[k] === 'string') {
res[k] = vC.decode(hex.decode(res[k] as string));
} else if (cannotChange && k in val && cur && cur[k] !== undefined) {
if (!P.equalBytes(vC.encode(val[k]), vC.encode(cur[k])))
throw new Error(`Cannot change signed field=${k}`);
}
}
// Remove unknown keys
for (const k in res) if (!psbtEnum[k]) delete res[k];
return res;
}
export const RawPSBTV0 = P.validate(_RawPSBTV0, validatePSBT);
export const RawPSBTV2 = P.validate(_RawPSBTV2, validatePSBT);
// (TxHash, Idx)
const TxHashIdx = P.struct({ txid: P.bytes(32, true), index: P.U32LE });
// /Coders
// Payments
// We need following items:
// - encode/decode output script
// - generate input script
// - generate address/output/redeem from user input
// P2ret represents generic interface for all p2* methods
export type P2Ret = {
type: string;
script: Bytes;
address?: string;
redeemScript?: Bytes;
witnessScript?: Bytes;
};
// Public Key (P2PK)
type OutPKType = { type: 'pk'; pubkey: Bytes };
type OptScript = ScriptType | undefined;
const OutPK: Coder<OptScript, OutPKType | undefined> = {
encode(from: ScriptType): OutPKType | undefined {
if (
from.length !== 2 ||
!isBytes(from[0]) ||
!isValidPubkey(from[0], PubT.ecdsa) ||
from[1] !== 'CHECKSIG'
)
return;
return { type: 'pk', pubkey: from[0] };
},
decode: (to: OutPKType): OptScript => (to.type === 'pk' ? [to.pubkey, 'CHECKSIG'] : undefined),
};
// @ts-ignore
export const p2pk = (pubkey: Bytes, network = NETWORK): P2Ret => {
// network is unused
if (!isValidPubkey(pubkey, PubT.ecdsa)) throw new Error('P2PK: invalid publicKey');
return {
type: 'pk',
script: OutScript.encode({ type: 'pk', pubkey }),
};
};
// Public Key Hash (P2PKH)
type OutPKHType = { type: 'pkh'; hash: Bytes };
const OutPKH: Coder<OptScript, OutPKHType | undefined> = {
encode(from: ScriptType): OutPKHType | undefined {
if (from.length !== 5 || from[0] !== 'DUP' || from[1] !== 'HASH160' || !isBytes(from[2]))
return;
if (from[3] !== 'EQUALVERIFY' || from[4] !== 'CHECKSIG') return;
return { type: 'pkh', hash: from[2] };
},
decode: (to: OutPKHType): OptScript =>
to.type === 'pkh' ? ['DUP', 'HASH160', to.hash, 'EQUALVERIFY', 'CHECKSIG'] : undefined,
};
export const p2pkh = (publicKey: Bytes, network = NETWORK): P2Ret => {
if (!isValidPubkey(publicKey, PubT.ecdsa)) throw new Error('P2PKH: invalid publicKey');
const hash = hash160(publicKey);
return {
type: 'pkh',
script: OutScript.encode({ type: 'pkh', hash }),
address: Address(network).encode({ type: 'pkh', hash }),
};
};
// Script Hash (P2SH)
type OutSHType = { type: 'sh'; hash: Bytes };
const OutSH: Coder<OptScript, OutSHType | undefined> = {
encode(from: ScriptType): OutSHType | undefined {
if (from.length !== 3 || from[0] !== 'HASH160' || !isBytes(from[1]) || from[2] !== 'EQUAL')
return;
return { type: 'sh', hash: from[1] };
},
decode: (to: OutSHType): OptScript =>
to.type === 'sh' ? ['HASH160', to.hash, 'EQUAL'] : undefined,
};
export const p2sh = (child: P2Ret, network = NETWORK): P2Ret => {
// It is already tested inside noble-hashes and checkScript
const cs = child.script;
if (!isBytes(cs)) throw new Error(`Wrong script: ${typeof child.script}, expected Uint8Array`);
const hash = hash160(cs);
const script = OutScript.encode({ type: 'sh', hash });
checkScript(script, cs, child.witnessScript);
const res: P2Ret = {
type: 'sh',
redeemScript: cs,
script: OutScript.encode({ type: 'sh', hash }),
address: Address(network).encode({ type: 'sh', hash }),
};
if (child.witnessScript) res.witnessScript = child.witnessScript;
return res;
};
// Witness Script Hash (P2WSH)
type OutWSHType = { type: 'wsh'; hash: Bytes };
const OutWSH: Coder<OptScript, OutWSHType | undefined> = {
encode(from: ScriptType): OutWSHType | undefined {
if (from.length !== 2 || from[0] !== 0 || !isBytes(from[1])) return;
if (from[1].length !== 32) return;
return { type: 'wsh', hash: from[1] };
},
decode: (to: OutWSHType): OptScript => (to.type === 'wsh' ? [0, to.hash] : undefined),
};