-
Notifications
You must be signed in to change notification settings - Fork 24
/
slip39_helper.js
2244 lines (2115 loc) · 34.8 KB
/
slip39_helper.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
/* eslint-disable no-array-constructor */
let crypto;
try {
crypto = require('crypto');
} catch (err) {
throw new Error('crypto support must be enabled');
}
// The length of the radix in bits.
const RADIX_BITS = 10;
// The length of the random identifier in bits.
const ID_BITS_LENGTH = 15;
// The length of the iteration exponent in bits.
const ITERATION_EXP_BITS_LENGTH = 5;
// The length of the random identifier and iteration exponent in words.
const ITERATION_EXP_WORDS_LENGTH =
parseInt((ID_BITS_LENGTH + ITERATION_EXP_BITS_LENGTH + RADIX_BITS - 1) / RADIX_BITS, 10);
// The maximum iteration exponent
const MAX_ITERATION_EXP = Math.pow(2, ITERATION_EXP_BITS_LENGTH);
// The maximum number of shares that can be created.
const MAX_SHARE_COUNT = 16;
// The length of the RS1024 checksum in words.
const CHECKSUM_WORDS_LENGTH = 3;
// The length of the digest of the shared secret in bytes.
const DIGEST_LENGTH = 4;
// The customization string used in the RS1024 checksum and in the PBKDF2 salt.
const SALT_STRING = 'shamir';
// The minimum allowed entropy of the master secret.
const MIN_ENTROPY_BITS = 128;
// The minimum allowed length of the mnemonic in words.
const METADATA_WORDS_LENGTH =
ITERATION_EXP_WORDS_LENGTH + 2 + CHECKSUM_WORDS_LENGTH;
// The length of the mnemonic in words without the share value.
const MNEMONICS_WORDS_LENGTH = parseInt(
METADATA_WORDS_LENGTH + (MIN_ENTROPY_BITS + RADIX_BITS - 1) / RADIX_BITS, 10);
// The minimum number of iterations to use in PBKDF2.
const ITERATION_COUNT = 10000;
// The number of rounds to use in the Feistel cipher.
const ROUND_COUNT = 4;
// The index of the share containing the digest of the shared secret.
const DIGEST_INDEX = 254;
// The index of the share containing the shared secret.
const SECRET_INDEX = 255;
//
// Helper functions for SLIP39 implementation.
//
String.prototype.encodeHex = function () {
let bytes = [];
for (let i = 0; i < this.length; ++i) {
bytes.push(this.charCodeAt(i));
}
return bytes;
};
Array.prototype.decodeHex = function () {
let str = [];
const hex = this.toString().split(',');
for (let i = 0; i < hex.length; i++) {
str.push(String.fromCharCode(hex[i]));
}
return str.toString().replace(/,/g, '');
};
Array.prototype.generate = function (n, v) {
let m = n || this.length;
for (let i = 0; i < m; i++) {
this[i] = typeof v === 'undefined' ? i : v(i);
}
return this;
};
Array.prototype.toHexString = function () {
return Array.prototype.map.call(this, function (byte) {
return ('0' + (byte & 0xFF).toString(16)).slice(-2);
}).join('');
};
Array.prototype.toByteArray = function (hexString) {
for (let i = 0; i < hexString.length; i = i + 2) {
this.push(parseInt(hexString.substr(i, 2), 16));
}
return this;
};
const BIGINT_WORD_BITS = BigInt(8);
function decodeBigInt(bytes) {
let result = BigInt(0);
for (let i = 0; i < bytes.length; i++) {
let b = BigInt(bytes[bytes.length - i - 1]);
result = result + (b << BIGINT_WORD_BITS * BigInt(i));
}
return result;
}
function encodeBigInt(number, paddedLength = 0) {
let num = number;
const BYTE_MASK = BigInt(0xff);
const BIGINT_ZERO = BigInt(0);
let result = new Array(0);
while (num > BIGINT_ZERO) {
let i = parseInt(num & BYTE_MASK, 10);
result.unshift(i);
num = num >> BIGINT_WORD_BITS;
}
// Zero padding to the length
for (let i = result.length; i < paddedLength; i++) {
result.unshift(0);
}
if (paddedLength !== 0 && result.length > paddedLength) {
throw new Error(`Error in encoding BigInt value, expected less than ${paddedLength} length value, got ${result.length}`);
}
return result;
}
function bitsToBytes(n) {
const res = (n + 7) / 8;
const b = parseInt(res, RADIX_BITS);
return b;
}
function bitsToWords(n) {
const res = (n + RADIX_BITS - 1) / RADIX_BITS;
const b = parseInt(res, RADIX_BITS);
return b;
}
//
// Returns a randomly generated integer in the range 0, ... , 2**ID_LENGTH_BITS - 1.
//
function randomBytes(length = 32) {
let randoms = crypto.randomBytes(length);
return Array.prototype.slice.call(randoms, 0);
}
//
// The round function used internally by the Feistel cipher.
//
function roundFunction(round, passphrase, exp, salt, secret) {
const saltedSecret = salt.concat(secret);
const roundedPhrase = [round].concat(passphrase);
const count = (ITERATION_COUNT << exp) / ROUND_COUNT;
const key = crypto.pbkdf2Sync(Buffer.from(roundedPhrase), Buffer.from(saltedSecret), count, secret.length, 'sha256');
return Array.prototype.slice.call(key, 0);
}
function crypt(masterSecret, passphrase, iterationExponent,
identifier,
encrypt = true) {
// Iteration exponent validated here.
if (iterationExponent < 0 || iterationExponent > MAX_ITERATION_EXP) {
throw Error(`Invalid iteration exponent (${iterationExponent}). Expected between 0 and ${MAX_ITERATION_EXP}`);
}
let IL = masterSecret.slice().slice(0, masterSecret.length / 2);
let IR = masterSecret.slice().slice(masterSecret.length / 2);
const pwd = passphrase.encodeHex();
const salt = getSalt(identifier);
let range = Array().generate(ROUND_COUNT);
range = encrypt ? range : range.reverse();
range.forEach((round) => {
const f = roundFunction(round, pwd, iterationExponent, salt, IR);
const t = xor(IL, f);
IL = IR;
IR = t;
});
return IR.concat(IL);
}
function createDigest(randomData, sharedSecret) {
const hmac = crypto.createHmac('sha256', Buffer.from(randomData));
hmac.update(Buffer.from(sharedSecret));
let result = hmac.digest();
result = result.slice(0, 4);
return Array.prototype.slice.call(result, 0);
}
function splitSecret(threshold, shareCount, sharedSecret) {
if (threshold <= 0) {
throw Error(`The requested threshold (${threshold}) must be a positive integer.`);
}
if (threshold > shareCount) {
throw Error(`The requested threshold (${threshold}) must not exceed the number of shares (${shareCount}).`);
}
if (shareCount > MAX_SHARE_COUNT) {
throw Error(`The requested number of shares (${shareCount}) must not exceed ${MAX_SHARE_COUNT}.`);
}
// If the threshold is 1, then the digest of the shared secret is not used.
if (threshold === 1) {
return Array().generate(shareCount, () => sharedSecret);
}
const randomShareCount = threshold - 2;
const randomPart = randomBytes(sharedSecret.length - DIGEST_LENGTH);
const digest = createDigest(randomPart, sharedSecret);
let baseShares = new Map();
let shares = [];
if (randomShareCount) {
shares = Array().generate(
randomShareCount, () => randomBytes(sharedSecret.length));
shares.forEach((item, idx) => {
baseShares.set(idx, item);
});
}
baseShares.set(DIGEST_INDEX, digest.concat(randomPart));
baseShares.set(SECRET_INDEX, sharedSecret);
for (let i = randomShareCount; i < shareCount; i++) {
const rr = interpolate(baseShares, i);
shares.push(rr);
}
return shares;
}
//
// Returns a randomly generated integer in the range 0, ... , 2**ID_BITS_LENGTH - 1.
//
function generateIdentifier() {
const byte = bitsToBytes(ID_BITS_LENGTH);
const bits = ID_BITS_LENGTH % 8;
const identifier = randomBytes(byte);
identifier[0] = identifier[0] & (1 << bits) - 1;
return identifier;
}
function xor(a, b) {
if (a.length !== b.length) {
throw new Error(`Invalid padding in mnemonic or insufficient length of mnemonics (${a.length} or ${b.length})`);
}
return Array().generate(a.length, (i) => a[i] ^ b[i]);
}
function getSalt(identifier) {
const salt = SALT_STRING.encodeHex();
return salt.concat(identifier);
}
function interpolate(shares, x) {
let xCoord = new Set(shares.keys());
let arr = Array.from(shares.values(), (v) => {
v.length;
});
let sharesValueLengths = new Set(arr);
if (sharesValueLengths.size !== 1) {
throw new Error('Invalid set of shares. All share values must have the same length.');
}
if (xCoord.has(x)) {
shares.forEach((k, v) => {
if (k === x) {
return v;
}
});
}
// Logarithm of the product of (x_i - x) for i = 1, ... , k.
let logProd = 0;
shares.forEach((v, k) => {
logProd = logProd + LOG_TABLE[k ^ x];
});
let results = Array().generate(sharesValueLengths.values().next().value, () => 0);
shares.forEach((v, k) => {
// The logarithm of the Lagrange basis polynomial evaluated at x.
let sum = 0;
shares.forEach((vv, kk) => {
sum = sum + LOG_TABLE[k ^ kk];
});
// FIXME: -18 % 255 = 237. IT shoulud be 237 and not -18 as it's
// implemented in javascript.
const basis = (logProd - LOG_TABLE[k ^ x] - sum) % 255;
const logBasisEval = basis < 0 ? 255 + basis : basis;
v.forEach((item, idx) => {
const shareVal = item;
const intermediateSum = results[idx];
const r = shareVal !== 0 ?
EXP_TABLE[(LOG_TABLE[shareVal] + logBasisEval) % 255] : 0;
const res = intermediateSum ^ r;
results[idx] = res;
});
});
return results;
}
function rs1024Polymod(data) {
const GEN = [
0xE0E040,
0x1C1C080,
0x3838100,
0x7070200,
0xE0E0009,
0x1C0C2412,
0x38086C24,
0x3090FC48,
0x21B1F890,
0x3F3F120
];
let chk = 1;
data.forEach((byte) => {
const b = chk >> 20;
chk = (chk & 0xFFFFF) << 10 ^ byte;
for (let i = 0; i < 10; i++) {
let gen = (b >> i & 1) !== 0 ? GEN[i] : 0;
chk = chk ^ gen;
}
});
return chk;
}
function rs1024CreateChecksum(data) {
const values = SALT_STRING.encodeHex()
.concat(data)
.concat(Array().generate(CHECKSUM_WORDS_LENGTH, () => 0));
const polymod = rs1024Polymod(values) ^ 1;
const result =
Array().generate(CHECKSUM_WORDS_LENGTH, (i) => polymod >> 10 * i & 1023).reverse();
return result;
}
function rs1024VerifyChecksum(data) {
return rs1024Polymod(SALT_STRING.encodeHex().concat(data)) === 1;
}
//
// Converts a list of base 1024 indices in big endian order to an integer value.
//
function intFromIndices(indices) {
let value = BigInt(0);
const radix = BigInt(Math.pow(2, RADIX_BITS));
indices.forEach((index) => {
value = value * radix + BigInt(index);
});
return value;
}
//
// Converts a Big integer value to indices in big endian order.
//
function intToIndices(value, length, bits) {
const mask = BigInt((1 << bits) - 1);
const result =
Array().generate(length, (i) => parseInt(value >> BigInt(i) * BigInt(bits) & mask, 10));
return result.reverse();
}
function mnemonicFromIndices(indices) {
const result = indices.map((index) => {
return WORD_LIST[index];
});
return result.toString().split(',').join(' ');
}
function mnemonicToIndices(mnemonic) {
if (typeof mnemonic !== 'string') {
throw new Error(`Mnemonic expected to be typeof string with white space separated words. Instead found typeof ${typeof mnemonic}.`);
}
const words = mnemonic.toLowerCase().split(' ');
const result = words.reduce((prev, item) => {
const index = WORD_LIST_MAP[item];
if (typeof index === 'undefined') {
throw new Error(`Invalid mnemonic word ${item}.`);
}
return prev.concat(index);
}, []);
return result;
}
function recoverSecret(threshold, shares) {
// If the threshold is 1, then the digest of the shared secret is not used.
if (threshold === 1) {
return shares.values().next().value;
}
const sharedSecret = interpolate(shares, SECRET_INDEX);
const digestShare = interpolate(shares, DIGEST_INDEX);
const digest = digestShare.slice(0, DIGEST_LENGTH);
const randomPart = digestShare.slice(DIGEST_LENGTH);
const recoveredDigest = createDigest(
randomPart, sharedSecret);
if (!listsAreEqual(digest, recoveredDigest)) {
throw new Error('Invalid digest of the shared secret.');
}
return sharedSecret;
}
//
// Combines mnemonic shares to obtain the master secret which was previously
// split using Shamir's secret sharing scheme.
//
function combineMnemonics(mnemonics, passphrase = '') {
if (mnemonics === null || mnemonics.length === 0) {
throw new Error('The list of mnemonics is empty.');
}
const decoded = decodeMnemonics(mnemonics);
const identifier = decoded.identifier;
const iterationExponent = decoded.iterationExponent;
const groupThreshold = decoded.groupThreshold;
const groupCount = decoded.groupCount;
const groups = decoded.groups;
if (groups.size < groupThreshold) {
throw new Error(`Insufficient number of mnemonic groups (${groups.length}). The required number of groups is ${groupThreshold}.`);
}
if (groups.size !== groupThreshold) {
throw new Error(`Wrong number of mnemonic groups. Expected $groupThreshold groups, but ${groups.length} were provided.`);
}
let allShares = new Map();
groups.forEach((members, groupIndex) => {
const threshold = members.keys().next().value;
const shares = members.values().next().value;
if (shares.size !== threshold) {
const prefix = groupPrefix(
identifier,
iterationExponent,
groupIndex,
groupThreshold,
groupCount
);
throw new Error(`Wrong number of mnemonics. Expected ${threshold} mnemonics starting with "${mnemonicFromIndices(prefix)}", \n but ${shares.size} were provided.`);
}
const recovered = recoverSecret(threshold, shares);
allShares.set(groupIndex, recovered);
});
const ems = recoverSecret(groupThreshold, allShares);
const id = intToIndices(BigInt(identifier), ITERATION_EXP_WORDS_LENGTH, 8);
const ms = crypt(ems, passphrase, iterationExponent, id, false);
return ms;
}
function decodeMnemonics(mnemonics) {
if (!(mnemonics instanceof Array)) {
throw new Error('Mnemonics should be an array of strings');
}
const identifiers = new Set();
const iterationExponents = new Set();
const groupThresholds = new Set();
const groupCounts = new Set();
const groups = new Map();
mnemonics.forEach((mnemonic) => {
const decoded = decodeMnemonic(mnemonic);
identifiers.add(decoded.identifier);
iterationExponents.add(decoded.iterationExponent);
const groupIndex = decoded.groupIndex;
groupThresholds.add(decoded.groupThreshold);
groupCounts.add(decoded.groupCount);
const memberIndex = decoded.memberIndex;
const memberThreshold = decoded.memberThreshold;
const share = decoded.share;
const group = !groups.has(groupIndex) ? new Map() : groups.get(groupIndex);
const member = !group.has(memberThreshold) ? new Map() : group.get(memberThreshold);
member.set(memberIndex, share);
group.set(memberThreshold, member);
if (group.size !== 1) {
throw new Error('Invalid set of mnemonics. All mnemonics in a group must have the same member threshold.');
}
groups.set(groupIndex, group);
});
if (identifiers.size !== 1 || iterationExponents.size !== 1) {
throw new Error(`Invalid set of mnemonics. All mnemonics must begin with the same ${ITERATION_EXP_WORDS_LENGTH} words.`);
}
if (groupThresholds.size !== 1) {
throw new Error('Invalid set of mnemonics. All mnemonics must have the same group threshold.');
}
if (groupCounts.size !== 1) {
throw new Error('Invalid set of mnemonics. All mnemonics must have the same group count.');
}
return {
identifier: identifiers.values().next().value,
iterationExponent: iterationExponents.values().next().value,
groupThreshold: groupThresholds.values().next().value,
groupCount: groupCounts.values().next().value,
groups: groups
};
}
//
// Converts a share mnemonic to share data.
//
function decodeMnemonic(mnemonic) {
const data = mnemonicToIndices(mnemonic);
if (data.length < MNEMONICS_WORDS_LENGTH) {
throw new Error(`Invalid mnemonic length. The length of each mnemonic must be at least ${MNEMONICS_WORDS_LENGTH} words.`);
}
const paddingLen = RADIX_BITS * (data.length - METADATA_WORDS_LENGTH) % 16;
if (paddingLen > 8) {
throw new Error('Invalid mnemonic length.');
}
if (!rs1024VerifyChecksum(data)) {
throw new Error('Invalid mnemonic checksum');
}
const idExpInt =
parseInt(intFromIndices(data.slice(0, ITERATION_EXP_WORDS_LENGTH)), 10);
const identifier = idExpInt >> ITERATION_EXP_BITS_LENGTH;
const iterationExponent = idExpInt & (1 << ITERATION_EXP_BITS_LENGTH) - 1;
const tmp = intFromIndices(
data.slice(ITERATION_EXP_WORDS_LENGTH, ITERATION_EXP_WORDS_LENGTH + 2));
const indices = intToIndices(tmp, 5, 4);
const groupIndex = indices[0];
const groupThreshold = indices[1];
const groupCount = indices[2];
const memberIndex = indices[3];
const memberThreshold = indices[4];
const valueData = data.slice(
ITERATION_EXP_WORDS_LENGTH + 2, data.length - CHECKSUM_WORDS_LENGTH);
if (groupCount < groupThreshold) {
throw new Error(`Invalid mnemonic: ${mnemonic}.\n Group threshold (${groupThreshold}) cannot be greater than group count (${groupCount}).`);
}
const valueInt = intFromIndices(valueData);
try {
const valueByteCount = bitsToBytes(RADIX_BITS * valueData.length - paddingLen);
const share = encodeBigInt(valueInt, valueByteCount);
return {
identifier: identifier,
iterationExponent: iterationExponent,
groupIndex: groupIndex,
groupThreshold: groupThreshold + 1,
groupCount: groupCount + 1,
memberIndex: memberIndex,
memberThreshold: memberThreshold + 1,
share: share
};
} catch (e) {
throw new Error(`Invalid mnemonic padding (${e})`);
}
}
function validateMnemonic(mnemonic) {
try {
decodeMnemonic(mnemonic);
return true;
} catch (error) {
return false;
}
}
function groupPrefix(
identifier, iterationExponent, groupIndex, groupThreshold, groupCount) {
const idExpInt = BigInt(
(identifier << ITERATION_EXP_BITS_LENGTH) + iterationExponent);
const indc = intToIndices(idExpInt, ITERATION_EXP_WORDS_LENGTH, RADIX_BITS);
const indc2 =
(groupIndex << 6) + (groupThreshold - 1 << 2) + (groupCount - 1 >> 2);
indc.push(indc2);
return indc;
}
function listsAreEqual(a, b) {
if (a === null || b === null || a.length !== b.length) {
return false;
}
let i = 0;
return a.every((item) => {
return b[i++] === item;
});
}
//
// Converts share data to a share mnemonic.
//
function encodeMnemonic(
identifier,
iterationExponent,
groupIndex,
groupThreshold,
groupCount,
memberIndex,
memberThreshold,
value
) {
// Convert the share value from bytes to wordlist indices.
const valueWordCount = bitsToWords(value.length * 8);
const valueInt = decodeBigInt(value);
let newIdentifier = parseInt(decodeBigInt(identifier), 10);
const gp = groupPrefix(
newIdentifier, iterationExponent, groupIndex, groupThreshold, groupCount);
const tp = intToIndices(valueInt, valueWordCount, RADIX_BITS);
const calc = ((groupCount - 1 & 3) << 8) +
(memberIndex << 4) +
(memberThreshold - 1);
gp.push(calc);
const shareData = gp.concat(tp);
const checksum = rs1024CreateChecksum(shareData);
return mnemonicFromIndices(shareData.concat(checksum));
}
// The precomputed exponent and log tables.
// ```
// const exp = List<int>.filled(255, 0)
// const log = List<int>.filled(256, 0)
// const poly = 1
//
// for (let i = 0; i < exp.length; i++) {
// exp[i] = poly
// log[poly] = i
// // Multiply poly by the polynomial x + 1.
// poly = (poly << 1) ^ poly
// // Reduce poly by x^8 + x^4 + x^3 + x + 1.
// if (poly & 0x100 === 0x100) poly ^= 0x11B
// }
// ```
const EXP_TABLE = [
1,
3,
5,
15,
17,
51,
85,
255,
26,
46,
114,
150,
161,
248,
19,
53,
95,
225,
56,
72,
216,
115,
149,
164,
247,
2,
6,
10,
30,
34,
102,
170,
229,
52,
92,
228,
55,
89,
235,
38,
106,
190,
217,
112,
144,
171,
230,
49,
83,
245,
4,
12,
20,
60,
68,
204,
79,
209,
104,
184,
211,
110,
178,
205,
76,
212,
103,
169,
224,
59,
77,
215,
98,
166,
241,
8,
24,
40,
120,
136,
131,
158,
185,
208,
107,
189,
220,
127,
129,
152,
179,
206,
73,
219,
118,
154,
181,
196,
87,
249,
16,
48,
80,
240,
11,
29,
39,
105,
187,
214,
97,
163,
254,
25,
43,
125,
135,
146,
173,
236,
47,
113,
147,
174,
233,
32,
96,
160,
251,
22,
58,
78,
210,
109,
183,
194,
93,
231,
50,
86,
250,
21,
63,
65,
195,
94,
226,
61,
71,
201,
64,
192,
91,
237,
44,
116,
156,
191,
218,
117,
159,
186,
213,
100,
172,
239,
42,
126,
130,
157,
188,
223,
122,
142,
137,
128,
155,
182,
193,
88,
232,
35,
101,
175,
234,
37,
111,
177,
200,
67,
197,
84,
252,
31,
33,
99,
165,
244,
7,
9,
27,
45,
119,
153,
176,
203,
70,
202,
69,
207,
74,
222,
121,
139,
134,
145,
168,
227,
62,
66,
198,
81,
243,
14,
18,
54,
90,
238,
41,
123,
141,
140,
143,
138,
133,
148,
167,
242,
13,
23,
57,
75,
221,
124,
132,
151,
162,
253,
28,
36,
108,
180,
199,
82,
246
];
const LOG_TABLE = [
0,
0,
25,
1,
50,
2,
26,
198,
75,
199,
27,
104,
51,
238,
223,
3,
100,
4,
224,
14,
52,
141,
129,
239,
76,
113,
8,
200,
248,
105,
28,
193,
125,
194,
29,
181,
249,
185,
39,
106,
77,
228,
166,
114,
154,
201,
9,
120,
101,
47,
138,
5,
33,
15,
225,
36,
18,
240,
130,