-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathslip39.go
1680 lines (1497 loc) · 49.9 KB
/
slip39.go
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
// Package slip39 is a Go implementation of the SLIP-0039 spec, implementing
// Shamir's Secret Sharing Scheme.
//
// The official SLIP-0039 spec can be found at
// https://github.com/satoshilabs/slips/blob/master/slip-0039.md
package slip39
import (
"bytes"
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/binary"
"errors"
"fmt"
"math/big"
"regexp"
"sort"
"strings"
mapset "github.com/deckarep/golang-set/v2"
"golang.org/x/crypto/pbkdf2"
"golang.org/x/exp/maps"
"gonum.org/v1/gonum/stat/combin"
)
const (
minMnemonicLengthWords = 20
customizationStringOriginal = "shamir"
customizationStringExtendable = "shamir_extendable"
radixBits = 10
idLengthBits = 15
extendableFlagLengthBits = 1
iterationExpLengthBits = 4
idExpLengthWords = 2
groupPrefixLengthWords = idExpLengthWords + 1
maxShareCount = 16
checksumLengthWords = 3
digestLengthBytes = 4
metadataLengthWords = idExpLengthWords + 2 + checksumLengthWords
minStrengthBits = 128
shift5Bits = 1 << 5
shift10Bits = 1 << 10
last10Bits = 1<<10 - 1
shift30Bits = 1 << 30
last30Bits = 1<<30 - 1
// cipher constants
baseIterationCount = 10000 // The minimum number of iterations for PBKDF2
roundCount = 4 // The number of rounds to use in the Feistel cipher
secretIndex = 255 // The index of the shared secret share
digestIndex = 254 // The index of the shared secret digest share
// Limit the combinatorial explosion possible with ValidateMnemonics
maxCombinations = 100
)
var (
bigOne = big.NewInt(1)
shift5BitsMask = big.NewInt(shift5Bits)
shift10BitsMask = big.NewInt(shift10Bits)
last10BitsMask = big.NewInt(last10Bits)
shift30BitsMask = big.NewInt(shift30Bits)
last30BitsMask = big.NewInt(last30Bits)
expTable = []int{}
logTable = []int{}
reLabel = regexp.MustCompile(`^\d{3,6}$`)
)
// ErrTooFewShares is returned when the number of groups or shares supplied
// is fewer than the required threshold
type ErrTooFewShares struct{} // public error, for testing with errors.Is()
// ErrTooManyShares is returned when the number of groups or shares supplied
// is greater than the required threshold
type ErrTooManyShares struct{} // public error, for testing with errors.Is()
type errBadQuantityShares struct { // private wrapping error, to hold details
errorType error
isGroup bool
count int
threshold int
prefix string
}
// ErrToo{Few,Many}Shares
func (e ErrTooFewShares) Error() string {
// Required to satisfy error interface, but not actually used
return "number of shares is fewer than the required threshold"
}
func (e ErrTooManyShares) Error() string {
// Required to satisfy error interface, but not actually used
return "number of shares exceeds the required threshold"
}
func (e errBadQuantityShares) Error() string {
items := "shares"
thresholdType := "member"
fewerMore := "fewer"
if e.count > e.threshold {
fewerMore = "more"
}
if e.isGroup {
items = "share groups"
thresholdType = "group"
}
prefixString := ""
if e.prefix != "" {
prefixString = fmt.Sprintf(", for group starting with %q", e.prefix)
}
return fmt.Sprintf("number of %s is %s than %s threshold (%d supplied, %d required%s)",
items, fewerMore, thresholdType, e.count, e.threshold, prefixString)
}
func (e errBadQuantityShares) Unwrap() error {
return e.errorType
}
// ErrInvalidPadding is returned when the padding on a mnemonic is invalid
type ErrInvalidPadding struct{}
type errInvalidPadding struct {
errorType ErrInvalidPadding
prefix string
}
func (e ErrInvalidPadding) Error() string {
// Required to satisfy error interface, but not actually used
return "invalid mnemonic padding"
}
func (e errInvalidPadding) Error() string {
return fmt.Sprintf(`invalid mnemonic padding for "%s..."`, e.prefix)
}
func (e errInvalidPadding) Unwrap() error {
return e.errorType
}
// ErrBadGroupThreshold is returned when the group threshold exceeds the group count
type ErrBadGroupThreshold struct{}
type errBadGroupThreshold struct {
errorType ErrBadGroupThreshold
prefix string
}
func (e ErrBadGroupThreshold) Error() string {
// Required to satisfy error interface, but not actually used
return "group threshold cannot exceed group count"
}
func (e errBadGroupThreshold) Error() string {
return fmt.Sprintf(`invalid mnemonic "%s..." - group threshold cannot exceed group count`, e.prefix)
}
func (e errBadGroupThreshold) Unwrap() error {
return e.errorType
}
// ErrInvalidMnemonicWord is returned when a mnemonic word is not found in the
// reference wordlist
type ErrInvalidMnemonicWord struct{}
type errInvalidMnemonicWord struct {
errorType ErrInvalidMnemonicWord
word string
}
func (e ErrInvalidMnemonicWord) Error() string {
// Required to satisfy error interface, but not actually used
return "invalid mnemonic - bad word"
}
func (e errInvalidMnemonicWord) Error() string {
return fmt.Sprintf("invalid mnemonic: word %q not found in wordmap", e.word)
}
func (e errInvalidMnemonicWord) Unwrap() error {
return e.errorType
}
var (
// ErrInvalidChecksum is returned when the checksum on a mnemonic is invalid
ErrInvalidChecksum = errors.New("invalid checksum")
// ErrInvalidMnemonic is returned when a mnemonic is invalid
ErrInvalidMnemonic = errors.New("invalid mnemonic")
// ErrInvalidCommonParameters is returned when the mnemonics in a group differ
// in their identifiers, group thresholds, or group counts
ErrInvalidCommonParameters = errors.New("all mnemonics must begin with the same 2 words, must have the same group threshold and the same group count")
// ErrEmptyShareGroup is returned when a share group is empty
ErrEmptyShareGroup = errors.New("the share group is empty")
// ErrMaxShareCountExceeded is returned when too many shares are provided
ErrMaxShareCountExceeded = fmt.Errorf("the number of shares cannot exceed %d", maxShareCount)
// ErrInvalidGroupThreshold is returned when the group threshold is invalid
ErrInvalidGroupThreshold = errors.New("group threshold must be a positive integers and must not exceed the number of groups")
// ErrInvalidThreshold is returned when the threshold is invalid
ErrInvalidThreshold = errors.New("the requested threshold must be a positive integers and must not exceed the number of shares")
// ErrInvalidSingleMemberThreshold is returned when the group threshold is invalid
ErrInvalidSingleMemberThreshold = errors.New("cannot create multiple member shares with member threshold 1 - use 1-of-1 member sharing instead")
// ErrInvalidMnemonicIndices is returned when a set of shares contains
// non-unique share indices
ErrInvalidMnemonicIndices = errors.New("invalid set of shares - share indices must be unique")
// ErrInvalidMnemonicShareLengths is returned with a set of shares include
// shares with different lengths
ErrInvalidMnemonicShareLengths = errors.New("invalid set of shares - all share values must have the same length")
// ErrInvalidMnemonicSharedSecretDigest is returned when a mnemonic has an
// invalid shared secret digest
ErrInvalidMnemonicSharedSecretDigest = errors.New("invalid shared secret digest")
// ErrInvalidMasterSecretLength is returned when trying to use a (decrypted)
// master secret with an invalid length
ErrInvalidMasterSecretLength = errors.New("master secret length must be >= 16B and be a multiple of 2")
// ErrInvalidEncryptedMasterSecretLength is returned when an encrypted master
// secret has an invalid length
ErrInvalidEncryptedMasterSecretLength = errors.New("the length of the encrypted master secret must be an even number")
// ErrInvalidPassphrase is returned when a passphrase contains invalid
// characters
ErrInvalidPassphrase = errors.New("the passphrase must contain only printable ASCII characters (code points 32-126)")
// ErrTooManyCombinations is returned when the number of share combinations
// is too many for ValidateMnemonics to test exhaustively
ErrTooManyCombinations = fmt.Errorf("too many combinations (more than %d)", maxCombinations)
)
// MemberGroupParameters define the (MemberThreshold, MemberCount) pairs required
// for the share groups created by GenerateMnemonics. MemberCount is the number
// of shares to generate for the group, and MemberThreshold is the number of
// members required to reconstruct the group secret.
type MemberGroupParameters struct {
MemberThreshold int `json:"member_threshold"`
MemberCount int `json:"member_count"`
}
// ShareCommonParameters represents the common parameters for a set of shares
// in a Shamir secret scheme
type ShareCommonParameters struct {
Identifier int `json:"identifier"`
Extendable int `json:"extendable"`
IterationExponent int `json:"iteration_exponent"`
GroupThreshold int `json:"group_threshold"`
GroupCount int `json:"group_count"`
}
// ShareGroupParameters represents the common parameters for a single group
// in a Shamir secret scheme
type ShareGroupParameters struct {
ShareCommonParameters `json:",inline"`
GroupIndex int `json:"group_index"`
MemberThreshold int `json:"member_threshold"`
}
// Share represents a single share of a Shamir secret scheme
type Share struct {
ShareGroupParameters `json:",inline"`
MemberIndex int `json:"member_index"`
ShareValues []byte `json:"share_values"`
}
type shareGroup struct {
shares []Share
}
type shareGroupMap map[int]shareGroup
type rawShare struct {
x int
data []byte
}
// ShareGroups is a slice of string slices, each comprising a group of slip39
// shares
type ShareGroups [][]string
func selectIndices(indices [][]int, group []string) [][]string {
combinations := make([][]string, len(indices))
for i, idx := range indices {
combination := make([]string, len(idx))
for j, k := range idx {
combination[j] = group[k]
}
combinations[i] = combination
}
return combinations
}
// combinations returns all combinations of shares in sg that meet the group
// and member threshold requirements. It returns a slice of combinations, each
// of which is a minimal slice of mnemonics sufficient to reproduce the
// underlying master secret. Returns an error if the share groups are invalid
// or if the number of combinations found exceeds maxCombinations.
func (sg ShareGroups) combinations() ([][]string, error) {
// Generate groupCombinations satisfying memberThresholds
groupCombinations := make([][][]string, len(sg))
groupThreshold := 0
for i, group := range sg {
if len(group) == 0 {
return nil, ErrEmptyShareGroup
}
// Parse the first share in the group to get the member threshold
memberThreshold := 0
share, err := ParseShare(group[0])
if err != nil {
return nil, fmt.Errorf("parsing share %q: %w", group[0], err)
}
if groupThreshold == 0 {
groupThreshold = share.GroupThreshold
} else if share.GroupThreshold != groupThreshold {
return nil,
errors.New("all share groups do not have the same group threshold")
}
memberThreshold = share.MemberThreshold
if memberThreshold > len(group) {
return nil,
fmt.Errorf("member threshold %d exceeds group size %d",
memberThreshold, len(group))
}
// Generate memberThreshold share combinations for the group
indices := combin.Combinations(len(group), memberThreshold)
if len(indices) > maxCombinations {
return nil, ErrTooManyCombinations
}
groupCombinations[i] = selectIndices(indices, group)
}
// Generate groupThreshold combinations of the groups
groupIndicesCombinations := combin.Combinations(
len(groupCombinations), groupThreshold,
)
//fmt.Fprintf(os.Stderr, "groupIndicesCombinations: %v\n", groupIndicesCombinations)
// For each set of groupIndices, produce the cartesian product of
// groupCombinations elements
shareCombinations := [][]string{}
for _, groupIndices := range groupIndicesCombinations {
//fmt.Fprintf(os.Stderr, "groupIndices [%d]: %v\n", i, groupIndices)
productDimensions := make([]int, len(groupIndices))
for j, groupIndex := range groupIndices {
productDimensions[j] = len(groupCombinations[groupIndex])
}
//fmt.Fprintf(os.Stderr, "productDimensions [%d]: %v\n", i, productDimensions)
productIndices := combin.Cartesian(productDimensions)
//fmt.Fprintf(os.Stderr, "productIndices [%d] (len %d): %v\n", i, len(productIndices), productIndices)
// Map productIndices back to groupCombinations shares
shares := make([]string, 0)
for _, productIndex := range productIndices {
for i, groupIndex := range groupIndices {
selected := productIndex[i]
shares = append(shares, groupCombinations[groupIndex][selected]...)
}
//fmt.Fprintf(os.Stderr, "shares [%d] (%d): %v\n", i, len(shares), shares)
shareCombinations = append(shareCombinations, shares)
if len(shareCombinations) > maxCombinations {
return nil, ErrTooManyCombinations
}
shares = make([]string, 0)
}
}
return shareCombinations, nil
}
// String converts sg to a string with one share per line, output in share group
// order
func (sg ShareGroups) String() string {
var sb strings.Builder
for _, shares := range sg {
for _, share := range shares {
sb.WriteString(share + "\n")
}
}
return sb.String()
}
// StringLabelled converts sg to a string with each share word on a separate line
// and prefixed with a numeric label formatted as follows:
//
// - If there is only a single share group then the label is a
// 3- or 4-digit number of the form:
//
// share_number * 100 + word number e.g. 101, 102, ... 201, 202... etc.
//
// - If there are multiple share groups then then label is a 4- to 6-digit
// number of the form:
//
// group_number * 1000 + share number * 100 + word_number, OR:
// group_number * 10000 + share number * 100 + word_number
//
// e.g. 1101, 1102... 1201, 1202..., 2101, 2102... etc. OR
// e.g. 10101, 10102... 10201, 10202..., 20101, 20102... etc.
func (sg ShareGroups) StringLabelled() (string, error) {
maxShares := 0
for _, shares := range sg {
if len(shares) > maxShares {
maxShares = len(shares)
}
}
// Build format string
var sb strings.Builder
groupCount := len(sg)
if groupCount > 1 {
if groupCount <= 9 {
sb.WriteString("%d")
} else {
sb.WriteString("%02d")
}
}
if maxShares <= 9 {
sb.WriteString("%d")
} else {
sb.WriteString("%02d")
}
sb.WriteString("%02d %s\n")
lfmt := sb.String()
// Build output string
sb.Reset()
for g, shares := range sg {
for s, share := range shares {
words, err := SplitMnemonicWords(share)
if err != nil {
return "", fmt.Errorf("splitting share %q words: %w", share, err)
}
for w, word := range words {
if groupCount == 1 {
fmt.Fprintf(&sb, lfmt, s+1, w+1, word)
} else {
fmt.Fprintf(&sb, lfmt, g+1, s+1, w+1, word)
}
}
}
}
return sb.String(), nil
}
func checkLastWord(
numWords *int,
lastWord, incNum int,
incType, label string,
) error {
if *numWords == 0 && lastWord != 0 {
if lastWord != 33 && lastWord != 20 {
return fmt.Errorf("bad label %q - %s %d has incremented, so lastWord should be 20 or 33, not %d",
label, incType, incNum, lastWord)
}
*numWords = lastWord
} else if lastWord != *numWords {
return fmt.Errorf("bad label %q - %s %d has incremented, so lastWord should be %d, not %d",
label, incType, incNum, *numWords, lastWord)
}
return nil
}
// checkBadLabel checks the sequencing between consecutive labels, and returns
// an error if there is a problem.
func checkBadLabel(
numWords *int,
groupNum, shareNum, wordNum, lastGroup, lastShare, lastWord int,
label, lastLabel, word string,
) error {
if shareNum == 0 {
return fmt.Errorf("invalid label %q for %q - shareNum cannot be 0",
label, word)
}
if wordNum == 0 {
return fmt.Errorf("invalid label %q for %q - wordNum cannot be 0",
label, word)
}
if groupNum > lastGroup+1 || groupNum < lastGroup {
if lastGroup == 0 {
return fmt.Errorf("invalid label %q - first groupNum should be 1, not %d",
label, groupNum)
}
return fmt.Errorf("invalid label %q after %q - groupNums %d and %d are not consecutive",
label, lastLabel, lastGroup, groupNum)
} else if groupNum == lastGroup && (shareNum > lastShare+1 || shareNum < lastShare) {
if lastShare == 0 {
return fmt.Errorf("invalid label %q - first shareNum must be 1, not %d",
label, shareNum)
}
return fmt.Errorf("invalid label %q after %q - shareNums %d and %d are not consecutive",
label, lastLabel, lastShare, shareNum)
}
// Exactly one of groupNum, shareNum, wordNum should increment by 1
if groupNum == lastGroup+1 {
if shareNum != 1 || wordNum != 1 {
return fmt.Errorf("bad label %q - groupNum %d has incremented, so both shareNum and wordNum should be 1",
label, groupNum)
}
// Check lastword == numWords
err := checkLastWord(numWords, lastWord, groupNum, "groupNum", label)
if err != nil {
return err
}
} else if shareNum == lastShare+1 {
if wordNum != 1 {
return fmt.Errorf("bad label %q - shareNum %d has incremented, so wordNum should be 1",
label, shareNum)
}
// Check lastword == numWords
err := checkLastWord(numWords, lastWord, shareNum, "shareNum", label)
if err != nil {
return err
}
} else if wordNum != lastWord+1 {
if lastWord == 0 {
return fmt.Errorf("bad label %q - first wordNum must be 1, not %d",
label, wordNum)
}
return fmt.Errorf("bad label %q after %q - wordNums %d and %d are not consecutive",
label, lastLabel, lastWord, wordNum)
}
return nil
}
// CombineLabelledShares converts a string containing a set of labelled shares,
// one per line, in "<label> <word>" format, into a ShareGroups slice.
// It checks that the labels are in a consistent format, and are consecutive
// by group, share, and word order, or returns an error.
func CombineLabelledShares(labelledShares string) (ShareGroups, error) {
groups := make(ShareGroups, 0)
group := make([]string, 0)
share := make([]string, 0, 33)
lines := strings.Split(strings.TrimSpace(labelledShares), "\n")
lastGroup := 0
lastShare := 0
lastWord := 0
lastLabel := ""
label := ""
numWords := 0
for lineno, line := range lines {
fields := strings.Fields(strings.TrimSpace(line))
if len(fields) != 2 {
return nil,
fmt.Errorf("invalid line %d %q - expected <label> <word>",
lineno+1, line)
}
label = fields[0]
word := fields[1]
if !reLabel.MatchString(label) {
return nil,
fmt.Errorf("invalid label %q on line %d - expected 3-6 digits",
label, lineno+1)
}
// Parse label
var groupNum, shareNum, wordNum int
var err error
if len(label) == 3 {
_, err = fmt.Sscanf(line, "%1d%2d", &shareNum, &wordNum)
} else if len(label) == 4 {
if label[0] == '0' {
_, err = fmt.Sscanf(line, "%2d%2d", &shareNum, &wordNum)
} else {
_, err = fmt.Sscanf(line, "%1d%1d%2d",
&groupNum, &shareNum, &wordNum)
}
} else if len(label) == 5 {
if label[0] == '0' {
_, err = fmt.Sscanf(line, "%2d%1d%2d",
&groupNum, &shareNum, &wordNum)
} else {
_, err = fmt.Sscanf(line, "%1d%2d%2d",
&groupNum, &shareNum, &wordNum)
}
} else {
_, err = fmt.Sscanf(line, "%2d%2d%2d",
&groupNum, &shareNum, &wordNum)
}
if err != nil {
return nil, fmt.Errorf("parsing label %q in line %d: %w",
label, lineno+1, err)
}
/*
fmt.Fprintf(os.Stderr, "label %q: group %d, share %d, word %02d == %s\n",
label, groupNum, shareNum, wordNum, word)
*/
// Check groupNum/shareNum/wordNum error conditions
err = checkBadLabel(&numWords, groupNum, shareNum, wordNum,
lastGroup, lastShare, lastWord, label, lastLabel, word)
if err != nil {
return nil, err
}
// Add to groups
// Exactly one of groupNum, shareNum, wordNum should increment by 1
if groupNum == lastGroup+1 {
// New group - save last and reset
if len(share) > 0 {
sharestr := strings.Join(share, " ")
group = append(group, sharestr)
groups = append(groups, group)
group = make([]string, 0)
share = make([]string, 0, 33)
}
lastGroup = groupNum
lastShare = shareNum
} else if shareNum == lastShare+1 {
// New share - save last and reset
if len(share) > 0 {
sharestr := strings.Join(share, " ")
group = append(group, sharestr)
share = make([]string, 0, 33)
}
lastShare = shareNum
}
share = append(share, word)
lastWord = wordNum
lastLabel = label
}
if len(share) > 0 {
sharestr := strings.Join(share, " ")
group = append(group, sharestr)
groups = append(groups, group)
}
// lastWord should always finish at 20 or 33
if lastWord != 20 && lastWord != 33 {
return nil, fmt.Errorf("bad label %q - lastWord should be 20 or 33, not %d",
label, lastWord)
}
return groups, nil
}
type encryptedMasterSecret struct {
identifier int
extendable bool
iterationExponent int
ciphertext []byte
}
func newEncryptedMasterSecret(
masterSecret, passphrase []byte,
identifier int,
extendable bool,
iterationExponent int,
) (encryptedMasterSecret, error) {
ciphertext, err := cipherEncrypt(
masterSecret, passphrase, iterationExponent, identifier, extendable,
)
if err != nil {
return encryptedMasterSecret{}, err
}
return encryptedMasterSecret{
identifier: identifier,
extendable: extendable,
iterationExponent: iterationExponent,
ciphertext: ciphertext,
}, nil
}
func (ems encryptedMasterSecret) decrypt(passphrase []byte) ([]byte, error) {
return cipherDecrypt(ems.ciphertext, passphrase,
ems.iterationExponent, ems.identifier, ems.extendable)
}
func zipBytes(a, b []byte) [][2]byte {
length := len(a)
if len(b) < length {
length = len(b)
}
zip := make([][2]byte, length)
for i := range length {
x := byte(0)
y := byte(0)
if len(a) > i {
x = a[i]
}
if len(b) > i {
y = b[i]
}
zip[i] = [2]byte{x, y}
}
return zip
}
func xor(a, b []byte) []byte {
c := zipBytes(a, b)
xor := make([]byte, len(c))
for i := range len(c) {
xor[i] = c[i][0] ^ c[i][1]
}
return xor
}
func roundFunction(i int, passphrase []byte, e int, salt, r []byte) []byte {
b := append([]byte{byte(i)}, passphrase...)
s := append(salt, r...)
iterations := (baseIterationCount << e) / roundCount
return pbkdf2.Key(b, s, iterations, len(r), sha256.New)
}
func getSalt(identifier int, extendable bool) []byte {
if extendable {
return []byte{}
}
idBytes := [2]byte{}
binary.BigEndian.PutUint16(idBytes[:], uint16(identifier))
return append([]byte(customizationStringOriginal), idBytes[0], idBytes[1])
}
func cipherEncrypt(
masterSecret, passphrase []byte,
iterationExponent, identifier int,
extendable bool,
) ([]byte, error) {
if len(masterSecret)%2 != 0 {
return nil, ErrInvalidMasterSecretLength
}
l := masterSecret[:len(masterSecret)/2]
r := masterSecret[len(masterSecret)/2:]
salt := getSalt(identifier, extendable)
for i := range roundCount {
f := roundFunction(i, passphrase, iterationExponent, salt, r)
l, r = r, xor(l, f)
}
return append(r, l...), nil
}
func cipherDecrypt(
ems, passphrase []byte,
iterationExponent, identifier int,
extendable bool,
) ([]byte, error) {
if len(ems)%2 != 0 {
return nil, ErrInvalidEncryptedMasterSecretLength
}
l := ems[:len(ems)/2]
r := ems[len(ems)/2:]
salt := getSalt(identifier, extendable)
for i := roundCount - 1; i >= 0; i-- {
f := roundFunction(i, passphrase, iterationExponent, salt, r)
l, r = r, xor(l, f)
}
return append(r, l...), nil
}
// SplitMnemonicWords splits mnemonic into a slice of words. If mnemonic
// returns too few words for a slip39 mnemonic, it returns an error.
func SplitMnemonicWords(mnemonic string) ([]string, error) {
words := strings.Fields(mnemonic)
if len(words) < minMnemonicLengthWords {
return nil, ErrInvalidMnemonic
}
return words, nil
}
// roundBits returns the number of `radixBits`-sized digits required to store a
// `n`-bit value
func roundBits(bits, radixBits int) int {
return (bits + radixBits - 1) / radixBits
}
// padByteSlice returns a byte slice of the given size with contents of the
// given slice left padded and any empty spaces filled with zeros
func padByteSlice(slice []byte, length int) []byte {
offset := length - len(slice)
if offset <= 0 {
return slice
}
newSlice := make([]byte, length)
copy(newSlice[offset:], slice)
return newSlice
}
func intToIndices(value, length, bits int) []int {
mask := (1 << bits) - 1
indices := make([]int, 0, length)
for i := length - 1; i >= 0; i-- {
indices = append(indices, (value>>(i*bits))&mask)
}
return indices
}
// bitesToBytes rounds up bit count to bytes
func bitsToBytes(bits int) int {
return roundBits(bits, 8)
}
// bitsToWords rounds up bit count to a multiple of radixBits word size
func bitsToWords(bits int) int {
return roundBits(bits, radixBits)
}
func stringToInts(s string) []int {
ints := make([]int, len(s))
for i := 0; i < len(s); i++ {
ints[i] = int(s[i])
}
return ints
}
func intFromWordIndices(indices []int) int {
if len(indices) > 4 {
panic("intFromWordIndices: indices length must be <= 4")
}
value := 0
for _, index := range indices {
value = (value << radixBits) + index
}
return value
}
func bigintFromWordIndices(indices []int) *big.Int {
var wordBytes [2]byte
var b = big.NewInt(0)
for _, index := range indices {
binary.BigEndian.PutUint16(wordBytes[:], uint16(index))
b.Mul(b, shift10BitsMask)
b.Or(b, big.NewInt(0).SetBytes(wordBytes[:]))
}
return b
}
func intToWordIndices(value int, length int) []int {
return intToIndices(value, length, radixBits)
}
func bigintToWordIndices(b *big.Int, length int) []int {
indices := make([]int, length)
// Throwaway big.Int for AND masking
word := big.NewInt(0)
for i := length - 1; i >= 0; i-- {
// Get 10 rightmost bits and bitshift 10 to the right
word.And(b, last10BitsMask)
b.Div(b, shift10BitsMask)
// Get the bytes representing the 10 bits as a 2-byte slice
wordBytes := padByteSlice(word.Bytes(), 2)
// Converts wordBytes to an index and add to indices
indices[i] = int(binary.BigEndian.Uint16(wordBytes))
}
return indices
}
func rs1024Polymod(values []int) int {
gen := []int{
0xe0e040, 0x1c1c080, 0x3838100, 0x7070200, 0xe0e0009,
0x1c0c2412, 0x38086c24, 0x3090fc48, 0x21b1f890, 0x3f3f120,
}
chk := 1
for _, v := range values {
b := chk >> 20
chk = ((chk & 0xfffff) << 10) ^ v
for i := range 10 {
if (b>>i)&1 != 0 {
chk ^= gen[i]
} else {
chk ^= 0
}
}
}
return chk
}
func rs1024VerifyChecksum(cs string, data []int) bool {
values := append(stringToInts(cs), data...)
return rs1024Polymod(values) == 1
}
func rs1024CreateChecksum(data []int, cs string) []int {
values := append(stringToInts(cs), data...)
values = append(values, []int{0, 0, 0}...)
polymod := rs1024Polymod(values) ^ 1
checksum := make([]int, checksumLengthWords)
for i := range checksumLengthWords {
checksum[i] = (polymod >> (10 * (2 - i))) & 1023
}
return checksum
}
func (s Share) encodeIDExp() []int {
idExpInt := s.Identifier << (iterationExpLengthBits + extendableFlagLengthBits)
idExpInt += s.Extendable << iterationExpLengthBits
idExpInt += s.IterationExponent
return intToWordIndices(idExpInt, idExpLengthWords)
}
func (s Share) encodeShareParams() []int {
// Each value is 4 bits, for 20 bits total
val := s.GroupIndex
val <<= 4
val += s.GroupThreshold - 1
val <<= 4
val += s.GroupCount - 1
val <<= 4
val += s.MemberIndex
val <<= 4
val += s.MemberThreshold - 1
// Group parameters are 2 words
return intToWordIndices(val, 2)
}
func (s Share) encode(valueData []int) []int {
shareData := []int{}
shareData = append(shareData, s.encodeIDExp()...)
shareData = append(shareData, s.encodeShareParams()...)
shareData = append(shareData, valueData...)
return shareData
}
func (s Share) customizationString() string {
if s.Extendable != 0 {
return customizationStringExtendable
}
return customizationStringOriginal
}
// Words returns the mnemonic words for s as a string slice, or an error
func (s Share) Words() ([]string, error) {
valueWordCount := bitsToWords(len(s.ShareValues) * 8)
valueInt := big.NewInt(0).SetBytes(s.ShareValues)
valueData := bigintToWordIndices(valueInt, valueWordCount)
shareData := s.encode(valueData)
checksum := rs1024CreateChecksum(shareData, s.customizationString())
//fmt.Fprintf(os.Stderr, "shareData: %v, customizationString: %s, checksum: %v\n",
//shareData, s.customizationString(), checksum)
shareData = append(shareData, checksum...)
words := make([]string, 0, len(shareData))
for _, wordIndex := range shareData {
word := wordlist[wordIndex]
if word == "" {
return nil, fmt.Errorf("invalid share wordIndex %d", wordIndex)
}
words = append(words, word)
}
return words, nil
}
// Mnemonic returns the mnemonic string for s, or an error
func (s Share) Mnemonic() (string, error) {
words, err := s.Words()
if err != nil {
return "", err
}
return strings.Join(words, " "), nil
}
// ParseShare parses a slip39 mnemonic string and returns a Share struct,
// or an error if the mnemonic is invalid.
func ParseShare(mnemonic string) (Share, error) {
var share Share
mnemonicData, err := SplitMnemonicWords(strings.ToLower(mnemonic))
if err != nil {
return share, err
}
paddingLen := (radixBits * (len(mnemonicData) - metadataLengthWords)) % 16
//fmt.Fprintf(os.Stderr, "paddingLen: %d\n", paddingLen)
if paddingLen > 8 {
return share, ErrInvalidPadding{}
}
var data = make([]int, len(mnemonicData))
for i, v := range mnemonicData {
index, found := wordmap[v]
if !found {
return share, errInvalidMnemonicWord{
word: v,
}
}
data[i] = index
}
//fmt.Fprintf(os.Stderr, "data: %v\n", data)
idExpData := data[:idExpLengthWords]
idExpInt := intFromWordIndices(idExpData)
//fmt.Fprintf(os.Stderr, "idExpInt: %d\n", idExpInt)
share.Identifier = idExpInt >>
(extendableFlagLengthBits + iterationExpLengthBits)
share.Extendable = idExpInt >> iterationExpLengthBits & 1
share.IterationExponent = idExpInt & ((1 << iterationExpLengthBits) - 1)