This repository has been archived by the owner on Nov 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
bitcoinjs-lib.js
16433 lines (15329 loc) · 504 KB
/
bitcoinjs-lib.js
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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.bitcoinjs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
module.exports = require('bitcoinjs-lib');
},{"bitcoinjs-lib":41}],2:[function(require,module,exports){
'use strict'
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
// @ts-ignore
var _Buffer = require('safe-buffer').Buffer
function base (ALPHABET) {
if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }
var BASE_MAP = new Uint8Array(256)
for (var j = 0; j < BASE_MAP.length; j++) {
BASE_MAP[j] = 255
}
for (var i = 0; i < ALPHABET.length; i++) {
var x = ALPHABET.charAt(i)
var xc = x.charCodeAt(0)
if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }
BASE_MAP[xc] = i
}
var BASE = ALPHABET.length
var LEADER = ALPHABET.charAt(0)
var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up
var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up
function encode (source) {
if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer.from(source) }
if (!_Buffer.isBuffer(source)) { throw new TypeError('Expected Buffer') }
if (source.length === 0) { return '' }
// Skip & count leading zeroes.
var zeroes = 0
var length = 0
var pbegin = 0
var pend = source.length
while (pbegin !== pend && source[pbegin] === 0) {
pbegin++
zeroes++
}
// Allocate enough space in big-endian base58 representation.
var size = ((pend - pbegin) * iFACTOR + 1) >>> 0
var b58 = new Uint8Array(size)
// Process the bytes.
while (pbegin !== pend) {
var carry = source[pbegin]
// Apply "b58 = b58 * 256 + ch".
var i = 0
for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
carry += (256 * b58[it1]) >>> 0
b58[it1] = (carry % BASE) >>> 0
carry = (carry / BASE) >>> 0
}
if (carry !== 0) { throw new Error('Non-zero carry') }
length = i
pbegin++
}
// Skip leading zeroes in base58 result.
var it2 = size - length
while (it2 !== size && b58[it2] === 0) {
it2++
}
// Translate the result into a string.
var str = LEADER.repeat(zeroes)
for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }
return str
}
function decodeUnsafe (source) {
if (typeof source !== 'string') { throw new TypeError('Expected String') }
if (source.length === 0) { return _Buffer.alloc(0) }
var psz = 0
// Skip and count leading '1's.
var zeroes = 0
var length = 0
while (source[psz] === LEADER) {
zeroes++
psz++
}
// Allocate enough space in big-endian base256 representation.
var size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.
var b256 = new Uint8Array(size)
// Process the characters.
while (source[psz]) {
// Decode character
var carry = BASE_MAP[source.charCodeAt(psz)]
// Invalid character
if (carry === 255) { return }
var i = 0
for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
carry += (BASE * b256[it3]) >>> 0
b256[it3] = (carry % 256) >>> 0
carry = (carry / 256) >>> 0
}
if (carry !== 0) { throw new Error('Non-zero carry') }
length = i
psz++
}
// Skip leading zeroes in b256.
var it4 = size - length
while (it4 !== size && b256[it4] === 0) {
it4++
}
var vch = _Buffer.allocUnsafe(zeroes + (size - it4))
vch.fill(0x00, 0, zeroes)
var j = zeroes
while (it4 !== size) {
vch[j++] = b256[it4++]
}
return vch
}
function decode (string) {
var buffer = decodeUnsafe(string)
if (buffer) { return buffer }
throw new Error('Non-base' + BASE + ' character')
}
return {
encode: encode,
decodeUnsafe: decodeUnsafe,
decode: decode
}
}
module.exports = base
},{"safe-buffer":95}],3:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
exports.toByteArray = toByteArray
exports.fromByteArray = fromByteArray
var lookup = []
var revLookup = []
var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
for (var i = 0, len = code.length; i < len; ++i) {
lookup[i] = code[i]
revLookup[code.charCodeAt(i)] = i
}
// Support decoding URL-safe base64 strings, as Node.js does.
// See: https://en.wikipedia.org/wiki/Base64#URL_applications
revLookup['-'.charCodeAt(0)] = 62
revLookup['_'.charCodeAt(0)] = 63
function getLens (b64) {
var len = b64.length
if (len % 4 > 0) {
throw new Error('Invalid string. Length must be a multiple of 4')
}
// Trim off extra bytes after placeholder bytes are found
// See: https://github.com/beatgammit/base64-js/issues/42
var validLen = b64.indexOf('=')
if (validLen === -1) validLen = len
var placeHoldersLen = validLen === len
? 0
: 4 - (validLen % 4)
return [validLen, placeHoldersLen]
}
// base64 is 4/3 + up to two characters of the original data
function byteLength (b64) {
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function _byteLength (b64, validLen, placeHoldersLen) {
return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
}
function toByteArray (b64) {
var tmp
var lens = getLens(b64)
var validLen = lens[0]
var placeHoldersLen = lens[1]
var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
var curByte = 0
// if there are placeholders, only get up to the last complete 4 chars
var len = placeHoldersLen > 0
? validLen - 4
: validLen
var i
for (i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
(revLookup[b64.charCodeAt(i + 2)] << 6) |
revLookup[b64.charCodeAt(i + 3)]
arr[curByte++] = (tmp >> 16) & 0xFF
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 2) {
tmp =
(revLookup[b64.charCodeAt(i)] << 2) |
(revLookup[b64.charCodeAt(i + 1)] >> 4)
arr[curByte++] = tmp & 0xFF
}
if (placeHoldersLen === 1) {
tmp =
(revLookup[b64.charCodeAt(i)] << 10) |
(revLookup[b64.charCodeAt(i + 1)] << 4) |
(revLookup[b64.charCodeAt(i + 2)] >> 2)
arr[curByte++] = (tmp >> 8) & 0xFF
arr[curByte++] = tmp & 0xFF
}
return arr
}
function tripletToBase64 (num) {
return lookup[num >> 18 & 0x3F] +
lookup[num >> 12 & 0x3F] +
lookup[num >> 6 & 0x3F] +
lookup[num & 0x3F]
}
function encodeChunk (uint8, start, end) {
var tmp
var output = []
for (var i = start; i < end; i += 3) {
tmp =
((uint8[i] << 16) & 0xFF0000) +
((uint8[i + 1] << 8) & 0xFF00) +
(uint8[i + 2] & 0xFF)
output.push(tripletToBase64(tmp))
}
return output.join('')
}
function fromByteArray (uint8) {
var tmp
var len = uint8.length
var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
var parts = []
var maxChunkLength = 16383 // must be multiple of 3
// go through the array every three bytes, we'll deal with trailing stuff later
for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
}
// pad the end with zeros, but make sure to not forget the extra bytes
if (extraBytes === 1) {
tmp = uint8[len - 1]
parts.push(
lookup[tmp >> 2] +
lookup[(tmp << 4) & 0x3F] +
'=='
)
} else if (extraBytes === 2) {
tmp = (uint8[len - 2] << 8) + uint8[len - 1]
parts.push(
lookup[tmp >> 10] +
lookup[(tmp >> 4) & 0x3F] +
lookup[(tmp << 2) & 0x3F] +
'='
)
}
return parts.join('')
}
},{}],4:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", { value: true });
exports.bech32m = exports.bech32 = void 0;
const ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';
const ALPHABET_MAP = {};
for (let z = 0; z < ALPHABET.length; z++) {
const x = ALPHABET.charAt(z);
ALPHABET_MAP[x] = z;
}
function polymodStep(pre) {
const b = pre >> 25;
return (((pre & 0x1ffffff) << 5) ^
(-((b >> 0) & 1) & 0x3b6a57b2) ^
(-((b >> 1) & 1) & 0x26508e6d) ^
(-((b >> 2) & 1) & 0x1ea119fa) ^
(-((b >> 3) & 1) & 0x3d4233dd) ^
(-((b >> 4) & 1) & 0x2a1462b3));
}
function prefixChk(prefix) {
let chk = 1;
for (let i = 0; i < prefix.length; ++i) {
const c = prefix.charCodeAt(i);
if (c < 33 || c > 126)
return 'Invalid prefix (' + prefix + ')';
chk = polymodStep(chk) ^ (c >> 5);
}
chk = polymodStep(chk);
for (let i = 0; i < prefix.length; ++i) {
const v = prefix.charCodeAt(i);
chk = polymodStep(chk) ^ (v & 0x1f);
}
return chk;
}
function convert(data, inBits, outBits, pad) {
let value = 0;
let bits = 0;
const maxV = (1 << outBits) - 1;
const result = [];
for (let i = 0; i < data.length; ++i) {
value = (value << inBits) | data[i];
bits += inBits;
while (bits >= outBits) {
bits -= outBits;
result.push((value >> bits) & maxV);
}
}
if (pad) {
if (bits > 0) {
result.push((value << (outBits - bits)) & maxV);
}
}
else {
if (bits >= inBits)
return 'Excess padding';
if ((value << (outBits - bits)) & maxV)
return 'Non-zero padding';
}
return result;
}
function toWords(bytes) {
return convert(bytes, 8, 5, true);
}
function fromWordsUnsafe(words) {
const res = convert(words, 5, 8, false);
if (Array.isArray(res))
return res;
}
function fromWords(words) {
const res = convert(words, 5, 8, false);
if (Array.isArray(res))
return res;
throw new Error(res);
}
function getLibraryFromEncoding(encoding) {
let ENCODING_CONST;
if (encoding === 'bech32') {
ENCODING_CONST = 1;
}
else {
ENCODING_CONST = 0x2bc830a3;
}
function encode(prefix, words, LIMIT) {
LIMIT = LIMIT || 90;
if (prefix.length + 7 + words.length > LIMIT)
throw new TypeError('Exceeds length limit');
prefix = prefix.toLowerCase();
// determine chk mod
let chk = prefixChk(prefix);
if (typeof chk === 'string')
throw new Error(chk);
let result = prefix + '1';
for (let i = 0; i < words.length; ++i) {
const x = words[i];
if (x >> 5 !== 0)
throw new Error('Non 5-bit word');
chk = polymodStep(chk) ^ x;
result += ALPHABET.charAt(x);
}
for (let i = 0; i < 6; ++i) {
chk = polymodStep(chk);
}
chk ^= ENCODING_CONST;
for (let i = 0; i < 6; ++i) {
const v = (chk >> ((5 - i) * 5)) & 0x1f;
result += ALPHABET.charAt(v);
}
return result;
}
function __decode(str, LIMIT) {
LIMIT = LIMIT || 90;
if (str.length < 8)
return str + ' too short';
if (str.length > LIMIT)
return 'Exceeds length limit';
// don't allow mixed case
const lowered = str.toLowerCase();
const uppered = str.toUpperCase();
if (str !== lowered && str !== uppered)
return 'Mixed-case string ' + str;
str = lowered;
const split = str.lastIndexOf('1');
if (split === -1)
return 'No separator character for ' + str;
if (split === 0)
return 'Missing prefix for ' + str;
const prefix = str.slice(0, split);
const wordChars = str.slice(split + 1);
if (wordChars.length < 6)
return 'Data too short';
let chk = prefixChk(prefix);
if (typeof chk === 'string')
return chk;
const words = [];
for (let i = 0; i < wordChars.length; ++i) {
const c = wordChars.charAt(i);
const v = ALPHABET_MAP[c];
if (v === undefined)
return 'Unknown character ' + c;
chk = polymodStep(chk) ^ v;
// not in the checksum?
if (i + 6 >= wordChars.length)
continue;
words.push(v);
}
if (chk !== ENCODING_CONST)
return 'Invalid checksum for ' + str;
return { prefix, words };
}
function decodeUnsafe(str, LIMIT) {
const res = __decode(str, LIMIT);
if (typeof res === 'object')
return res;
}
function decode(str, LIMIT) {
const res = __decode(str, LIMIT);
if (typeof res === 'object')
return res;
throw new Error(res);
}
return {
decodeUnsafe,
decode,
encode,
toWords,
fromWordsUnsafe,
fromWords,
};
}
exports.bech32 = getLibraryFromEncoding('bech32');
exports.bech32m = getLibraryFromEncoding('bech32m');
},{}],5:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const parser_1 = require('../parser');
function combine(psbts) {
const self = psbts[0];
const selfKeyVals = parser_1.psbtToKeyVals(self);
const others = psbts.slice(1);
if (others.length === 0) throw new Error('Combine: Nothing to combine');
const selfTx = getTx(self);
if (selfTx === undefined) {
throw new Error('Combine: Self missing transaction');
}
const selfGlobalSet = getKeySet(selfKeyVals.globalKeyVals);
const selfInputSets = selfKeyVals.inputKeyVals.map(getKeySet);
const selfOutputSets = selfKeyVals.outputKeyVals.map(getKeySet);
for (const other of others) {
const otherTx = getTx(other);
if (
otherTx === undefined ||
!otherTx.toBuffer().equals(selfTx.toBuffer())
) {
throw new Error(
'Combine: One of the Psbts does not have the same transaction.',
);
}
const otherKeyVals = parser_1.psbtToKeyVals(other);
const otherGlobalSet = getKeySet(otherKeyVals.globalKeyVals);
otherGlobalSet.forEach(
keyPusher(
selfGlobalSet,
selfKeyVals.globalKeyVals,
otherKeyVals.globalKeyVals,
),
);
const otherInputSets = otherKeyVals.inputKeyVals.map(getKeySet);
otherInputSets.forEach((inputSet, idx) =>
inputSet.forEach(
keyPusher(
selfInputSets[idx],
selfKeyVals.inputKeyVals[idx],
otherKeyVals.inputKeyVals[idx],
),
),
);
const otherOutputSets = otherKeyVals.outputKeyVals.map(getKeySet);
otherOutputSets.forEach((outputSet, idx) =>
outputSet.forEach(
keyPusher(
selfOutputSets[idx],
selfKeyVals.outputKeyVals[idx],
otherKeyVals.outputKeyVals[idx],
),
),
);
}
return parser_1.psbtFromKeyVals(selfTx, {
globalMapKeyVals: selfKeyVals.globalKeyVals,
inputKeyVals: selfKeyVals.inputKeyVals,
outputKeyVals: selfKeyVals.outputKeyVals,
});
}
exports.combine = combine;
function keyPusher(selfSet, selfKeyVals, otherKeyVals) {
return key => {
if (selfSet.has(key)) return;
const newKv = otherKeyVals.filter(kv => kv.key.toString('hex') === key)[0];
selfKeyVals.push(newKv);
selfSet.add(key);
};
}
function getTx(psbt) {
return psbt.globalMap.unsignedTx;
}
function getKeySet(keyVals) {
const set = new Set();
keyVals.forEach(keyVal => {
const hex = keyVal.key.toString('hex');
if (set.has(hex))
throw new Error('Combine: KeyValue Map keys should be unique');
set.add(hex);
});
return set;
}
},{"../parser":30}],6:[function(require,module,exports){
(function (Buffer){(function (){
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const typeFields_1 = require('../../typeFields');
const range = n => [...Array(n).keys()];
function decode(keyVal) {
if (keyVal.key[0] !== typeFields_1.GlobalTypes.GLOBAL_XPUB) {
throw new Error(
'Decode Error: could not decode globalXpub with key 0x' +
keyVal.key.toString('hex'),
);
}
if (keyVal.key.length !== 79 || ![2, 3].includes(keyVal.key[46])) {
throw new Error(
'Decode Error: globalXpub has invalid extended pubkey in key 0x' +
keyVal.key.toString('hex'),
);
}
if ((keyVal.value.length / 4) % 1 !== 0) {
throw new Error(
'Decode Error: Global GLOBAL_XPUB value length should be multiple of 4',
);
}
const extendedPubkey = keyVal.key.slice(1);
const data = {
masterFingerprint: keyVal.value.slice(0, 4),
extendedPubkey,
path: 'm',
};
for (const i of range(keyVal.value.length / 4 - 1)) {
const val = keyVal.value.readUInt32LE(i * 4 + 4);
const isHard = !!(val & 0x80000000);
const idx = val & 0x7fffffff;
data.path += '/' + idx.toString(10) + (isHard ? "'" : '');
}
return data;
}
exports.decode = decode;
function encode(data) {
const head = Buffer.from([typeFields_1.GlobalTypes.GLOBAL_XPUB]);
const key = Buffer.concat([head, data.extendedPubkey]);
const splitPath = data.path.split('/');
const value = Buffer.allocUnsafe(splitPath.length * 4);
data.masterFingerprint.copy(value, 0);
let offset = 4;
splitPath.slice(1).forEach(level => {
const isHard = level.slice(-1) === "'";
let num = 0x7fffffff & parseInt(isHard ? level.slice(0, -1) : level, 10);
if (isHard) num += 0x80000000;
value.writeUInt32LE(num, offset);
offset += 4;
});
return {
key,
value,
};
}
exports.encode = encode;
exports.expected =
'{ masterFingerprint: Buffer; extendedPubkey: Buffer; path: string; }';
function check(data) {
const epk = data.extendedPubkey;
const mfp = data.masterFingerprint;
const p = data.path;
return (
Buffer.isBuffer(epk) &&
epk.length === 78 &&
[2, 3].indexOf(epk[45]) > -1 &&
Buffer.isBuffer(mfp) &&
mfp.length === 4 &&
typeof p === 'string' &&
!!p.match(/^m(\/\d+'?)*$/)
);
}
exports.check = check;
function canAddToArray(array, item, dupeSet) {
const dupeString = item.extendedPubkey.toString('hex');
if (dupeSet.has(dupeString)) return false;
dupeSet.add(dupeString);
return (
array.filter(v => v.extendedPubkey.equals(item.extendedPubkey)).length === 0
);
}
exports.canAddToArray = canAddToArray;
}).call(this)}).call(this,require("buffer").Buffer)
},{"../../typeFields":33,"buffer":69}],7:[function(require,module,exports){
(function (Buffer){(function (){
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const typeFields_1 = require('../../typeFields');
function encode(data) {
return {
key: Buffer.from([typeFields_1.GlobalTypes.UNSIGNED_TX]),
value: data.toBuffer(),
};
}
exports.encode = encode;
}).call(this)}).call(this,require("buffer").Buffer)
},{"../../typeFields":33,"buffer":69}],8:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const typeFields_1 = require('../typeFields');
const globalXpub = require('./global/globalXpub');
const unsignedTx = require('./global/unsignedTx');
const finalScriptSig = require('./input/finalScriptSig');
const finalScriptWitness = require('./input/finalScriptWitness');
const nonWitnessUtxo = require('./input/nonWitnessUtxo');
const partialSig = require('./input/partialSig');
const porCommitment = require('./input/porCommitment');
const sighashType = require('./input/sighashType');
const tapKeySig = require('./input/tapKeySig');
const tapLeafScript = require('./input/tapLeafScript');
const tapMerkleRoot = require('./input/tapMerkleRoot');
const tapScriptSig = require('./input/tapScriptSig');
const witnessUtxo = require('./input/witnessUtxo');
const tapTree = require('./output/tapTree');
const bip32Derivation = require('./shared/bip32Derivation');
const checkPubkey = require('./shared/checkPubkey');
const redeemScript = require('./shared/redeemScript');
const tapBip32Derivation = require('./shared/tapBip32Derivation');
const tapInternalKey = require('./shared/tapInternalKey');
const witnessScript = require('./shared/witnessScript');
const globals = {
unsignedTx,
globalXpub,
// pass an Array of key bytes that require pubkey beside the key
checkPubkey: checkPubkey.makeChecker([]),
};
exports.globals = globals;
const inputs = {
nonWitnessUtxo,
partialSig,
sighashType,
finalScriptSig,
finalScriptWitness,
porCommitment,
witnessUtxo,
bip32Derivation: bip32Derivation.makeConverter(
typeFields_1.InputTypes.BIP32_DERIVATION,
),
redeemScript: redeemScript.makeConverter(
typeFields_1.InputTypes.REDEEM_SCRIPT,
),
witnessScript: witnessScript.makeConverter(
typeFields_1.InputTypes.WITNESS_SCRIPT,
),
checkPubkey: checkPubkey.makeChecker([
typeFields_1.InputTypes.PARTIAL_SIG,
typeFields_1.InputTypes.BIP32_DERIVATION,
]),
tapKeySig,
tapScriptSig,
tapLeafScript,
tapBip32Derivation: tapBip32Derivation.makeConverter(
typeFields_1.InputTypes.TAP_BIP32_DERIVATION,
),
tapInternalKey: tapInternalKey.makeConverter(
typeFields_1.InputTypes.TAP_INTERNAL_KEY,
),
tapMerkleRoot,
};
exports.inputs = inputs;
const outputs = {
bip32Derivation: bip32Derivation.makeConverter(
typeFields_1.OutputTypes.BIP32_DERIVATION,
),
redeemScript: redeemScript.makeConverter(
typeFields_1.OutputTypes.REDEEM_SCRIPT,
),
witnessScript: witnessScript.makeConverter(
typeFields_1.OutputTypes.WITNESS_SCRIPT,
),
checkPubkey: checkPubkey.makeChecker([
typeFields_1.OutputTypes.BIP32_DERIVATION,
]),
tapBip32Derivation: tapBip32Derivation.makeConverter(
typeFields_1.OutputTypes.TAP_BIP32_DERIVATION,
),
tapTree,
tapInternalKey: tapInternalKey.makeConverter(
typeFields_1.OutputTypes.TAP_INTERNAL_KEY,
),
};
exports.outputs = outputs;
},{"../typeFields":33,"./global/globalXpub":6,"./global/unsignedTx":7,"./input/finalScriptSig":9,"./input/finalScriptWitness":10,"./input/nonWitnessUtxo":11,"./input/partialSig":12,"./input/porCommitment":13,"./input/sighashType":14,"./input/tapKeySig":15,"./input/tapLeafScript":16,"./input/tapMerkleRoot":17,"./input/tapScriptSig":18,"./input/witnessUtxo":19,"./output/tapTree":20,"./shared/bip32Derivation":21,"./shared/checkPubkey":22,"./shared/redeemScript":23,"./shared/tapBip32Derivation":24,"./shared/tapInternalKey":25,"./shared/witnessScript":26}],9:[function(require,module,exports){
(function (Buffer){(function (){
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const typeFields_1 = require('../../typeFields');
function decode(keyVal) {
if (keyVal.key[0] !== typeFields_1.InputTypes.FINAL_SCRIPTSIG) {
throw new Error(
'Decode Error: could not decode finalScriptSig with key 0x' +
keyVal.key.toString('hex'),
);
}
return keyVal.value;
}
exports.decode = decode;
function encode(data) {
const key = Buffer.from([typeFields_1.InputTypes.FINAL_SCRIPTSIG]);
return {
key,
value: data,
};
}
exports.encode = encode;
exports.expected = 'Buffer';
function check(data) {
return Buffer.isBuffer(data);
}
exports.check = check;
function canAdd(currentData, newData) {
return !!currentData && !!newData && currentData.finalScriptSig === undefined;
}
exports.canAdd = canAdd;
}).call(this)}).call(this,require("buffer").Buffer)
},{"../../typeFields":33,"buffer":69}],10:[function(require,module,exports){
(function (Buffer){(function (){
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const typeFields_1 = require('../../typeFields');
function decode(keyVal) {
if (keyVal.key[0] !== typeFields_1.InputTypes.FINAL_SCRIPTWITNESS) {
throw new Error(
'Decode Error: could not decode finalScriptWitness with key 0x' +
keyVal.key.toString('hex'),
);
}
return keyVal.value;
}
exports.decode = decode;
function encode(data) {
const key = Buffer.from([typeFields_1.InputTypes.FINAL_SCRIPTWITNESS]);
return {
key,
value: data,
};
}
exports.encode = encode;
exports.expected = 'Buffer';
function check(data) {
return Buffer.isBuffer(data);
}
exports.check = check;
function canAdd(currentData, newData) {
return (
!!currentData && !!newData && currentData.finalScriptWitness === undefined
);
}
exports.canAdd = canAdd;
}).call(this)}).call(this,require("buffer").Buffer)
},{"../../typeFields":33,"buffer":69}],11:[function(require,module,exports){
(function (Buffer){(function (){
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const typeFields_1 = require('../../typeFields');
function decode(keyVal) {
if (keyVal.key[0] !== typeFields_1.InputTypes.NON_WITNESS_UTXO) {
throw new Error(
'Decode Error: could not decode nonWitnessUtxo with key 0x' +
keyVal.key.toString('hex'),
);
}
return keyVal.value;
}
exports.decode = decode;
function encode(data) {
return {
key: Buffer.from([typeFields_1.InputTypes.NON_WITNESS_UTXO]),
value: data,
};
}
exports.encode = encode;
exports.expected = 'Buffer';
function check(data) {
return Buffer.isBuffer(data);
}
exports.check = check;
function canAdd(currentData, newData) {
return !!currentData && !!newData && currentData.nonWitnessUtxo === undefined;
}
exports.canAdd = canAdd;
}).call(this)}).call(this,require("buffer").Buffer)
},{"../../typeFields":33,"buffer":69}],12:[function(require,module,exports){
(function (Buffer){(function (){
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const typeFields_1 = require('../../typeFields');
function decode(keyVal) {
if (keyVal.key[0] !== typeFields_1.InputTypes.PARTIAL_SIG) {
throw new Error(
'Decode Error: could not decode partialSig with key 0x' +
keyVal.key.toString('hex'),
);
}
if (
!(keyVal.key.length === 34 || keyVal.key.length === 66) ||
![2, 3, 4].includes(keyVal.key[1])
) {
throw new Error(
'Decode Error: partialSig has invalid pubkey in key 0x' +
keyVal.key.toString('hex'),
);
}
const pubkey = keyVal.key.slice(1);
return {
pubkey,
signature: keyVal.value,
};
}
exports.decode = decode;
function encode(pSig) {
const head = Buffer.from([typeFields_1.InputTypes.PARTIAL_SIG]);
return {
key: Buffer.concat([head, pSig.pubkey]),
value: pSig.signature,
};
}
exports.encode = encode;
exports.expected = '{ pubkey: Buffer; signature: Buffer; }';
function check(data) {
return (
Buffer.isBuffer(data.pubkey) &&
Buffer.isBuffer(data.signature) &&
[33, 65].includes(data.pubkey.length) &&
[2, 3, 4].includes(data.pubkey[0]) &&
isDerSigWithSighash(data.signature)
);
}
exports.check = check;
function isDerSigWithSighash(buf) {
if (!Buffer.isBuffer(buf) || buf.length < 9) return false;
if (buf[0] !== 0x30) return false;
if (buf.length !== buf[1] + 3) return false;
if (buf[2] !== 0x02) return false;
const rLen = buf[3];
if (rLen > 33 || rLen < 1) return false;
if (buf[3 + rLen + 1] !== 0x02) return false;
const sLen = buf[3 + rLen + 2];
if (sLen > 33 || sLen < 1) return false;
if (buf.length !== 3 + rLen + 2 + sLen + 2) return false;
return true;
}
function canAddToArray(array, item, dupeSet) {
const dupeString = item.pubkey.toString('hex');
if (dupeSet.has(dupeString)) return false;
dupeSet.add(dupeString);
return array.filter(v => v.pubkey.equals(item.pubkey)).length === 0;
}
exports.canAddToArray = canAddToArray;
}).call(this)}).call(this,require("buffer").Buffer)
},{"../../typeFields":33,"buffer":69}],13:[function(require,module,exports){
(function (Buffer){(function (){
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const typeFields_1 = require('../../typeFields');
function decode(keyVal) {
if (keyVal.key[0] !== typeFields_1.InputTypes.POR_COMMITMENT) {
throw new Error(
'Decode Error: could not decode porCommitment with key 0x' +
keyVal.key.toString('hex'),
);
}
return keyVal.value.toString('utf8');
}
exports.decode = decode;
function encode(data) {
const key = Buffer.from([typeFields_1.InputTypes.POR_COMMITMENT]);
return {
key,
value: Buffer.from(data, 'utf8'),
};
}
exports.encode = encode;
exports.expected = 'string';
function check(data) {
return typeof data === 'string';
}
exports.check = check;
function canAdd(currentData, newData) {
return !!currentData && !!newData && currentData.porCommitment === undefined;
}
exports.canAdd = canAdd;
}).call(this)}).call(this,require("buffer").Buffer)
},{"../../typeFields":33,"buffer":69}],14:[function(require,module,exports){
(function (Buffer){(function (){
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const typeFields_1 = require('../../typeFields');
function decode(keyVal) {
if (keyVal.key[0] !== typeFields_1.InputTypes.SIGHASH_TYPE) {
throw new Error(
'Decode Error: could not decode sighashType with key 0x' +
keyVal.key.toString('hex'),
);
}
return keyVal.value.readUInt32LE(0);
}
exports.decode = decode;
function encode(data) {
const key = Buffer.from([typeFields_1.InputTypes.SIGHASH_TYPE]);
const value = Buffer.allocUnsafe(4);
value.writeUInt32LE(data, 0);
return {
key,
value,
};
}
exports.encode = encode;
exports.expected = 'number';
function check(data) {
return typeof data === 'number';
}
exports.check = check;
function canAdd(currentData, newData) {
return !!currentData && !!newData && currentData.sighashType === undefined;
}
exports.canAdd = canAdd;
}).call(this)}).call(this,require("buffer").Buffer)
},{"../../typeFields":33,"buffer":69}],15:[function(require,module,exports){
(function (Buffer){(function (){
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const typeFields_1 = require('../../typeFields');
function decode(keyVal) {
if (
keyVal.key[0] !== typeFields_1.InputTypes.TAP_KEY_SIG ||
keyVal.key.length !== 1
) {
throw new Error(
'Decode Error: could not decode tapKeySig with key 0x' +
keyVal.key.toString('hex'),
);
}
if (!check(keyVal.value)) {
throw new Error(
'Decode Error: tapKeySig not a valid 64-65-byte BIP340 signature',
);
}
return keyVal.value;
}
exports.decode = decode;
function encode(value) {
const key = Buffer.from([typeFields_1.InputTypes.TAP_KEY_SIG]);
return { key, value };
}
exports.encode = encode;
exports.expected = 'Buffer';
function check(data) {
return Buffer.isBuffer(data) && (data.length === 64 || data.length === 65);
}
exports.check = check;
function canAdd(currentData, newData) {
return !!currentData && !!newData && currentData.tapKeySig === undefined;
}
exports.canAdd = canAdd;