forked from paulmillr/scure-btc-signer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
2410 lines (2307 loc) · 93.5 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
/*! micro-btc-signer - MIT License (c) 2022 Paul Miller (paulmillr.com) */
import * as secp from '@noble/secp256k1';
import * as base from '@scure/base';
import { sha256 } from '@noble/hashes/sha256';
import { hmac } from '@noble/hashes/hmac';
import { ripemd160 } from '@noble/hashes/ripemd160';
import * as P from 'micro-packed';
// as const returns readonly stuff, remove readonly property
// TODO: update in other places
type Writable<T> = T extends {}
? T extends Uint8Array
? T
: {
-readonly [P in keyof T]: Writable<T[P]>;
}
: T;
export type Bytes = Uint8Array;
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 = base.base58check(sha256);
// Enable sync API for noble-secp256k1
secp.utils.hmacSha256Sync = (key, ...msgs) => hmac(sha256, key, concat(...msgs));
secp.utils.sha256Sync = (...msgs) => sha256(concat(...msgs));
const taggedHash = secp.utils.taggedHashSync;
enum PubT {
ecdsa,
schnorr,
}
const validatePubkey = (pub: Bytes, type: PubT) => {
const len = pub.length;
if (type === PubT.ecdsa) {
if (len === 32) throw new Error('Expected non-Schnorr key');
} else if (type === PubT.schnorr) {
if (len !== 32) throw new Error('Expected 32-byte Schnorr key');
} else {
throw new Error('Unknown key type');
}
secp.Point.fromHex(pub); // does assertValidity
return pub;
};
function isValidPubkey(pub: Bytes, type: PubT) {
try {
return !!validatePubkey(pub, type);
} catch (e) {
return false;
}
}
// Not best way, but closest to bitcoin implementation (easier to check)
const hasLowR = (sig: Bytes) => secp.Signature.fromHex(sig).toCompactRawBytes()[0] < 0x80;
// TODO: move to @noble/secp256k1?
function signECDSA(hash: Bytes, privateKey: Bytes, lowR = false): Bytes {
let sig = secp.signSync(hash, privateKey, { canonical: true });
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 = secp.signSync(hash, privateKey, { canonical: true, extraEntropy });
if (hasLowR(sig)) break;
}
}
return sig;
}
export function taprootTweakPrivKey(privKey: Uint8Array, merkleRoot = new Uint8Array()) {
const { n } = secp.CURVE;
const priv = secp.utils._normalizePrivateKey(privKey);
const point = secp.Point.fromPrivateKey(priv);
const tweak = taggedHash('TapTweak', point.toRawX(), merkleRoot);
const privWithProperY = point.hasEvenY() ? priv : n - priv;
const tweaked = secp.utils.mod(privWithProperY + secp.utils._normalizePrivateKey(tweak), n);
return secp.utils._bigintTo32Bytes(tweaked);
}
export function taprootTweakPubkey(pubKey: Uint8Array, h: Uint8Array): [Uint8Array, boolean] {
const tweak = taggedHash('TapTweak', pubKey, h);
const tweaked = secp.Point.fromHex(pubKey).add(secp.Point.fromPrivateKey(tweak));
return [tweaked.toRawX(), !tweaked.hasEvenY()];
}
// 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 = base.hex.encode(pub);
if (map[key]) throw new Error(`Multisig: non-uniq pubkey: ${pubkeys.map(base.hex.encode)}`);
map[key] = true;
}
}
export const NETWORK = {
bech32: 'bc',
pubKeyHash: 0x00,
scriptHash: 0x05,
wif: 0x80,
};
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);
type CmpType = string | number | bigint | boolean | Bytes | undefined;
export function cmp(a: CmpType, b: CmpType): number {
if (a instanceof Uint8Array && b instanceof Uint8Array) {
// -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);
} else if (a instanceof Uint8Array || b instanceof Uint8Array)
throw new Error(`cmp: wrong values a=${a} b=${b}`);
if (
(typeof a === 'bigint' && typeof b === 'number') ||
(typeof a === 'number' && typeof b === 'bigint')
) {
a = BigInt(a);
b = BigInt(b);
}
if (a === undefined || b === undefined) throw new Error(`cmp: wrong values a=${a} b=${b}`);
// Default js comparasion
return Number(a > b) - Number(a < b);
}
// 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,
}
// OP_\n to numeric value
// TODO: maybe add numbers to script parser for this case?
// prettier-ignore
export enum OPNum {
OP_0, 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,
}
function OPtoNumber(op: keyof typeof OP & keyof typeof OPNum): number | undefined {
if (typeof op === 'string' && OP[op] !== undefined && OPNum[op] !== undefined) return OPNum[op];
}
type ScriptType = (keyof typeof OP | Bytes)[];
// Converts script bytes to parsed script
// 5221030000000000000000000000000000000000000000000000000000000000000001210300000000000000000000000000000000000000000000000000000000000000022103000000000000000000000000000000000000000000000000000000000000000353ae
// =>
// OP_2
// 030000000000000000000000000000000000000000000000000000000000000001
// 030000000000000000000000000000000000000000000000000000000000000002
// 030000000000000000000000000000000000000000000000000000000000000003
// OP_3
// CHECKMULTISIG
// TODO: simplify like CompactSize?
export const Script: P.CoderType<ScriptType> = P.wrap({
encodeStream: (w: P.Writer, value: ScriptType) => {
for (const o of value) {
if (typeof o === 'string') {
if (OP[o] === undefined) throw new Error(`Unknown opcode=${o}`);
w.byte(OP[o]);
continue;
}
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 {
const op = OP[cur] as any;
if (op === undefined) throw new Error(`Unknown opcode=${cur.toString(16)}`);
out.push(op);
}
}
return out;
},
});
// 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({
hash: 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
// TODO: more tests. Unsigned tx has version=2 for some reason,
// probably we're exporting broken unsigned tx
// Related: https://github.com/bitcoin/bips/blob/master/bip-0068.mediawiki
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)),
// Need to handle that?
// < 500000000 Block number at which this transaction is unlocked
// >= 500000000 UNIX timestamp at which this transaction is unlocked
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 PSBTKeyMap = Record<
string,
readonly [number, PSBTKeyCoder, any, readonly number[], readonly number[], readonly number[]]
>;
const BIP32Der = P.struct({
fingerprint: P.U32BE,
path: P.array(null, P.U32LE),
});
// <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,
});
// {name: [tag, keyCoder, valueCoder]}
const PSBTGlobal = {
// TODO: RAW TX here
unsignedTx: [0x00, false, RawTx, [0], [2], [0]],
// The 78 byte serialized extended public key as defined by BIP 32.
xpub: [0x01, P.bytes(78), BIP32Der, [], [], [0, 2]],
txVersion: [0x02, false, P.U32LE, [2], [0], [2]],
fallbackLocktime: [0x03, false, P.U32LE, [], [0], [2]],
inputCount: [0x04, false, CompactSizeLen, [2], [0], [2]],
outputCount: [0x05, false, CompactSizeLen, [2], [0], [2]],
// bitfield
txModifiable: [0x06, false, P.U8, [], [0], [2]],
version: [0xfb, false, P.U32LE, [], [], [0, 2]],
// key = <identifierlen> <identifier> <subtype> <subkeydata>
propietary: [0xfc, P.bytes(null), P.bytes(null), [], [], [0, 2]],
} as const;
const PSBTInput = {
nonWitnessUtxo: [0x00, false, RawTx, [], [], [0, 2]],
witnessUtxo: [0x01, false, RawOutput, [], [], [0, 2]],
partialSig: [0x02, PubKeyECDSA, P.bytes(null), [], [], [0, 2]],
sighashType: [0x03, false, P.U32LE, [], [], [0, 2]],
redeemScript: [0x04, false, P.bytes(null), [], [], [0, 2]],
witnessScript: [0x05, false, P.bytes(null), [], [], [0, 2]],
bip32Derivation: [0x06, PubKeyECDSA, BIP32Der, [], [], [0, 2]],
finalScriptSig: [0x07, false, P.bytes(null), [], [], [0, 2]],
finalScriptWitness: [0x08, false, RawWitness, [], [], [0, 2]],
porCommitment: [0x09, false, P.bytes(null), [], [], [0, 2]],
ripemd160: [0x0a, P.bytes(20), P.bytes(null), [], [], [0, 2]],
sha256: [0x0b, P.bytes(32), P.bytes(null), [], [], [0, 2]],
hash160: [0x0c, P.bytes(20), P.bytes(null), [], [], [0, 2]],
hash256: [0x0d, P.bytes(32), P.bytes(null), [], [], [0, 2]],
hash: [0x0e, false, P.bytes(32), [2], [0], [2]],
index: [0x0f, false, P.U32LE, [2], [0], [2]],
sequence: [0x10, false, P.U32LE, [], [0], [2]],
requiredTimeLocktime: [0x11, false, P.U32LE, [], [0], [2]],
requiredHeightLocktime: [0x12, false, P.U32LE, [], [0], [2]],
tapKeySig: [0x13, false, SignatureSchnorr, [], [], [0, 2]],
tapScriptSig: [
0x14,
P.struct({ pubKey: PubKeySchnorr, leafHash: P.bytes(32) }),
SignatureSchnorr,
[],
[],
[0, 2],
],
// value = <bytes script> <8-bit uint leaf version>
tapLeafScript: [0x15, TaprootControlBlock, P.bytes(null), [], [], [0, 2]],
tapBip32Derivation: [0x16, P.bytes(32), TaprootBIP32Der, [], [], [0, 2]],
tapInternalKey: [0x17, false, PubKeySchnorr, [], [], [0, 2]],
tapMerkleRoot: [0x18, false, P.bytes(32), [], [], [0, 2]],
propietary: [0xfc, P.bytes(null), P.bytes(null), [], [], [0, 2]],
} as const;
// All other keys removed when finalizing
const PSBTInputFinalKeys: (keyof typeof PSBTInput)[] = [
'hash',
'sequence',
'index',
'witnessUtxo',
'nonWitnessUtxo',
'finalScriptSig',
'finalScriptWitness',
'unknown' as any,
];
// Can be modified even on signed input
const PSBTInputUnsignedKeys: (keyof typeof PSBTInput)[] = [
'partialSig',
'finalScriptSig',
'finalScriptWitness',
'tapKeySig',
'tapScriptSig',
];
const PSBTOutput = {
redeemScript: [0x00, false, P.bytes(null), [], [], [0, 2]],
witnessScript: [0x01, false, P.bytes(null), [], [], [0, 2]],
bip32Derivation: [0x02, PubKeyECDSA, BIP32Der, [], [], [0, 2]],
amount: [0x03, false, P.I64LE, [2], [0], [2]],
script: [0x04, false, P.bytes(null), [2], [0], [2]],
tapInternalKey: [0x05, false, PubKeySchnorr, [], [], [0, 2]],
/*
{<8-bit uint depth> <8-bit uint leaf version> <compact size uint scriptlen> <bytes script>}*
*/
tapTree: [
0x06,
false,
P.array(
null,
P.struct({
depth: P.U8,
version: P.U8,
script: VarBytes,
})
),
[],
[],
[0, 2],
],
tapBip32Derivation: [0x07, PubKeySchnorr, TaprootBIP32Der, [], [], [0, 2]],
propietary: [0xfc, P.bytes(null), P.bytes(null), [], [], [0, 2]],
} 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 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]>][];
};
// 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 {
// TODO: check here if there is duplicate keys
const kv: [Bytes, Bytes][] = val.map(([k, v]: [any, any]) => [
kc.encode(k),
vc.encode(v),
]);
// sort by keys
kv.sort((a, b) => cmp(a[0], b[0]));
for (const [key, value] of kv) out.push({ key: { key, type }, value });
}
}
if (value.unknown) {
value.unknown.sort((a: any, b: any) => cmp(a[0], b[0]));
for (const [k, v] of value.unknown as any)
out.push({ key: PSBTUnknownKey.decode(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=${base.hex.encode(key)} value=${base.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 = PSBTUnknownKey.encode({ 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) {
// TODO: revalidate
if (script) {
const s = OutScript.decode(script);
// TODO: ms||pk maybe work, but there will be no address
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, v] of i.partialSig) validatePubkey(k, PubT.ecdsa);
if (i.bip32Derivation) for (const [k, v] 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!');
}
}
return i;
});
const PSBTOutputCoder = P.validate(PSBTKeyMap(PSBTOutput), (o) => {
if (o.bip32Derivation) for (const [k, v] 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 [reqInc, reqExc, allowInc] = info[k].slice(-3);
if (reqExc.includes(version) || !allowInc.includes(version))
throw new Error(`PSBTv${version}: field ${k} is not allowed`);
}
for (const k in info) {
const [reqInc, reqExc, allowInc] = info[k].slice(-3);
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) {
if (k !== 'unknown') {
if (!info[k]) continue;
const [reqInc, reqExc, allowInc] = info[k].slice(-3);
if (reqExc.includes(version) || !allowInc.includes(version)) continue;
}
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;
}
// Check if object doens't have custom constructor (like Uint8Array/Array)
const isPlainObject = (obj: any) =>
Object.prototype.toString.call(obj) === '[object Object]' && obj.constructor === Object;
function type<T>(v: T) {
if (v instanceof Uint8Array) return 'bytes';
if (Array.isArray(v)) return 'array';
if (['number', 'string', 'bigint', 'boolean', 'undefined'].includes(typeof v)) return typeof v;
if (v === null) return 'null'; // typeof null=object
if (isPlainObject(v)) return 'object';
throw new Error(`Unknown type=${v}`);
}
// Basic structure merge: object = {...old, ...new}, arrays = old.concat(new). other -> replace
// function merge<T extends PSBTKeyMap>(
// psbtEnum: T,
// val: PSBTKeyMapKeys<T>,
// cur?: PSBTKeyMapKeys<T>
// ): PSBTKeyMapKeys<T> {
// }
function mergeKeyMap<T extends PSBTKeyMap>(
psbtEnum: T,
val: PSBTKeyMapKeys<T>,
cur?: PSBTKeyMapKeys<T>,
allowedFields?: (keyof PSBTKeyMapKeys<T>)[]
): PSBTKeyMapKeys<T> {
const res = { ...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(base.hex.decode(val[0])) : val[0],
typeof val[1] === 'string' ? vC.decode(base.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 = base.hex.encode(vC.encode(map[kStr][1]));
const newVal = base.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 = base.hex.encode(kC.encode(k));
add(kStr, k, v);
}
for (const [k, v] of newKV) {
const kStr = base.hex.encode(kC.encode(k));
// undefined removes previous value
if (v === undefined) 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(base.hex.decode(res[k] as any));
}
}
// 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({ hash: P.bytes(32, true), index: P.U32LE });
// /Coders
const isBytes = (b: unknown): b is Bytes => b instanceof Uint8Array;
// 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
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: base.Coder<OptScript, OutPKType | undefined> = {
encode(from: ScriptType): OutPKType | undefined {
if (
from.length !== 2 ||
!P.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),
};
export const p2pk = (pubkey: Bytes, network = NETWORK): P2Ret => {
if (!isValidPubkey(pubkey, PubT.ecdsa)) throw new Error('P2PK: invalid publicKey');
return {
type: 'pk',
script: OutScript.encode({ type: 'pk', pubkey }),
};
};
// Publick Key Hash (P2PKH)
type OutPKHType = { type: 'pkh'; hash: Bytes };
const OutPKH: base.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: base.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 => {
const hash = hash160(child.script);
const script = OutScript.encode({ type: 'sh', hash });
checkScript(script, child.script, child.witnessScript);
const res: P2Ret = {
type: 'sh',
redeemScript: child.script,
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: base.Coder<OptScript, OutWSHType | undefined> = {
encode(from: ScriptType): OutWSHType | undefined {
if (from.length !== 2 || from[0] !== 'OP_0' || !isBytes(from[1])) return;
if (from[1].length !== 32) return;
return { type: 'wsh', hash: from[1] };
},
decode: (to: OutWSHType): OptScript => (to.type === 'wsh' ? ['OP_0', to.hash] : undefined),
};
export const p2wsh = (child: P2Ret, network = NETWORK): P2Ret => {
const hash = sha256(child.script);
const script = OutScript.encode({ type: 'wsh', hash });
checkScript(script, undefined, child.script);
return {
type: 'wsh',
witnessScript: child.script,
script: OutScript.encode({ type: 'wsh', hash }),
address: Address(network).encode({ type: 'wsh', hash }),
};
};
// Witness Public Key Hash (P2WPKH)
type OutWPKHType = { type: 'wpkh'; hash: Bytes };
const OutWPKH: base.Coder<OptScript, OutWPKHType | undefined> = {
encode(from: ScriptType): OutWPKHType | undefined {
if (from.length !== 2 || from[0] !== 'OP_0' || !isBytes(from[1])) return;
if (from[1].length !== 20) return;
return { type: 'wpkh', hash: from[1] };
},
decode: (to: OutWPKHType): OptScript => (to.type === 'wpkh' ? ['OP_0', to.hash] : undefined),
};
export const p2wpkh = (publicKey: Bytes, network = NETWORK): P2Ret => {
if (!isValidPubkey(publicKey, PubT.ecdsa)) throw new Error('P2WPKH: invalid publicKey');
if (publicKey.length === 65) throw new Error('P2WPKH: uncompressed public key');
const hash = hash160(publicKey);
return {
type: 'wpkh',
script: OutScript.encode({ type: 'wpkh', hash }),
address: Address(network).encode({ type: 'wpkh', hash }),
};
};
// Multisig (P2MS)
type OutMSType = { type: 'ms'; pubkeys: Bytes[]; m: number };
const OutMS: base.Coder<OptScript, OutMSType | undefined> = {
encode(from: ScriptType): OutMSType | undefined {
const last = from.length - 1;
if (from[last] !== 'CHECKMULTISIG') return;
const m = OPtoNumber(from[0] as any);
const n = OPtoNumber(from[last - 1] as any);
if (m === undefined || n === undefined)
throw new Error('OutScript.encode/multisig wrong params');
const pubkeys: Bytes[] = from.slice(1, -2) as any; // Any is ok, check in for later
if (n !== pubkeys.length) throw new Error('OutScript.encode/multisig: wrong length');
return { type: 'ms', m, pubkeys }; // we don't need n, since it is the same as pubkeys
},
// checkmultisig(n, ..pubkeys, m)
decode: (to: OutMSType): OptScript =>
to.type === 'ms'
? [`OP_${to.m}`, ...to.pubkeys, `OP_${to.pubkeys.length}` as any, 'CHECKMULTISIG']
: undefined,
};
export const p2ms = (m: number, pubkeys: Bytes[], allowSamePubkeys = false): P2Ret => {
if (!allowSamePubkeys) uniqPubkey(pubkeys);
return { type: 'ms', script: OutScript.encode({ type: 'ms', pubkeys, m }) };
};
// Taproot (P2TR)
type OutTRType = { type: 'tr'; pubkey: Bytes };
const OutTR: base.Coder<OptScript, OutTRType | undefined> = {
encode(from: ScriptType): OutTRType | undefined {
if (from.length !== 2 || from[0] !== 'OP_1' || !isBytes(from[1])) return;
return { type: 'tr', pubkey: from[1] };
},
decode: (to: OutTRType): OptScript => (to.type === 'tr' ? ['OP_1', to.pubkey] : undefined),
};
export type TaprootNode = {
script: Bytes | string;
leafVersion?: number;
weight?: number;
} & Partial<P2TROut>;
export type TaprootScriptTree = TaprootNode | TaprootScriptTree[];
export type TaprootScriptList = TaprootNode[];
type _TaprootListInternal = (
| TaprootNode
| { weight?: number; childs: [_TaprootListInternal, _TaprootListInternal] }
)[];
// Helper for generating binary tree from list, with weights
export function taprootListToTree(taprootList: TaprootScriptList): TaprootScriptTree {
// Clone input in order to not corrupt it
const lst: _TaprootListInternal = Array.from(taprootList) as _TaprootListInternal;
// We have at least 2 elements => can create branch
while (lst.length >= 2) {
// Sort: elements with smallest weight are in the end of queue
lst.sort((a, b) => (b.weight || 1) - (a.weight || 1));
const b = lst.pop()!;
const a = lst.pop()!;
const weight = (a?.weight || 1) + (b?.weight || 1);
lst.push({
weight,
// Unwrap children array
childs: [(a as any).childs || a, (b as any).childs || b],
});
}
// At this point there is always 1 element in lst
const last = lst[0];
return ((last as any).childs || last) as TaprootScriptTree;
}
type HashedTree =