-
Notifications
You must be signed in to change notification settings - Fork 86
/
sss.rs
1273 lines (1202 loc) · 58.5 KB
/
sss.rs
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
//
// Copyright 2019 Tamas Blummer
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
//!
//! # Shamir's Secret Sharing as defined by SLIP-0039
//! see https://github.com/satoshilabs/slips/blob/master/slip-0039.md
//!
use std::{
collections::{HashMap, HashSet},
io::Cursor,
};
use bitcoin::util::bip158::{BitStreamReader, BitStreamWriter};
use crypto::{hmac::Hmac, mac::Mac, pbkdf2::pbkdf2, sha2::Sha256};
use rand::{thread_rng, RngCore};
use account::Seed;
use error::Error;
const RADIX_BITS: usize = 10; // The length of the radix in bits.
const RADIX: usize = 1 << RADIX_BITS; // The number of words in the word list.
const ID_LENGTH_BITS: usize = 15; // The length of the random identifier in bits.
const ITERATION_EXP_LENGTH_BITS: usize = 5; // The length of the iteration exponent in bits.
const fn bits_to_words(n: usize) -> usize {
(n + RADIX_BITS - 1) / RADIX_BITS
}
const ID_EXP_LENGTH_WORDS: usize = bits_to_words(ID_LENGTH_BITS + ITERATION_EXP_LENGTH_BITS); // The length of the random identifier and iteration exponent in words.
const MAX_SHARE_COUNT: u8 = 16; // The maximum number of shares that can be created.
const CHECKSUM_LENGTH_WORDS: usize = 3; // The length of the RS1024 checksum in words.
const DIGEST_LENGTH_BYTES: usize = 4; // The length of the digest of the shared secret in bytes.
const CUSTOMIZATION_STRING: &[u8; 6] = b"shamir"; // The customization string used in the RS1024 checksum and in the PBKDF2 salt.
const METADATA_LENGTH_WORDS: usize = ID_EXP_LENGTH_WORDS + 2 + CHECKSUM_LENGTH_WORDS; // The length of the mnemonic in words without the share value.
const MIN_STRENGTH_BITS: usize = 128; // The minimum allowed entropy of the master secret.
const MIN_MNEMONIC_LENGTH_WORDS: usize = METADATA_LENGTH_WORDS + bits_to_words(MIN_STRENGTH_BITS); // The minimum allowed length of the mnemonic in words.
const BASE_ITERATION_COUNT: usize = 10000; // The minimum number of iterations to use in PBKDF2.
const ROUND_COUNT: usize = 4; // The number of rounds to use in the Feistel cipher.
const SECRET_INDEX: usize = 255; // The index of the share containing the shared secret.
const DIGEST_INDEX: usize = 254; // The index of the share containing the digest of the shared secret.
pub struct ShamirSecretSharing {}
impl ShamirSecretSharing {
pub fn generate(
group_threshold: u8,
groups: &[(u8, u8)],
seed: &Seed,
pd_passphrase: Option<&str>,
iteration_exponent: u8,
) -> Result<Vec<Share>, Error> {
let secret = seed.0.as_slice();
if secret.len() * 8 < MIN_STRENGTH_BITS || secret.len() % 2 != 0 {
return Err(Error::Unsupported(
"master key entropy must be at least 128 bits and multiple of 16 bits",
));
}
if group_threshold > MAX_SHARE_COUNT {
return Err(Error::Unsupported("more than 16 groups are not supported"));
}
if group_threshold as usize > groups.len() {
return Err(Error::Unsupported(
"group threshold should not exceed number of groups",
));
}
if groups
.iter()
.any(|(threshold, count)| *threshold == 1 && *count > 1)
{
return Err(Error::Unsupported(
"can only generate one share for threshold = 1",
));
}
if groups.iter().any(|(threshold, count)| *threshold > *count) {
return Err(Error::Unsupported(
"number of shares must not be less than threshold",
));
}
let id = (thread_rng().next_u32() % (((1 << (ID_LENGTH_BITS + 1)) - 1) as u32)) as u16;
let mut shares = Vec::new();
for (group_index, group_share) in Self::split_secret(
group_threshold,
groups.len() as u8,
Self::encrypt(id, iteration_exponent, secret, pd_passphrase)?.as_slice(),
)? {
let (member_threshold, count) = groups[group_index as usize];
for (member_index, value) in
Self::split_secret(member_threshold, count, group_share.as_slice())?
{
shares.push(Share {
id,
value,
iteration_exponent,
group_count: groups.len() as u8,
group_index,
group_threshold,
member_index,
member_threshold,
});
}
}
Ok(shares)
}
pub fn combine(shares: &[Share], pd_passphrase: Option<&str>) -> Result<Seed, Error> {
let (id, iteration_exponent, group_threshold, groups) = Self::preprocess(shares)?;
if groups.len() < group_threshold as usize {
return Err(Error::Unsupported(
"need shares from more groups to reconstruct secret",
));
}
if groups.len() != group_threshold as usize {
return Err(Error::Unsupported("shares from too many groups"));
}
if groups
.iter()
.any(|(_, group)| group[0].0 as usize != group.len())
{
return Err(Error::Unsupported(
"for every group number of member shares should match member threshold",
));
}
if groups.iter().any(|(_, g)| {
g.iter()
.fold(HashSet::new(), |mut a, v| {
a.insert(v.0);
a
})
.len()
> 1
}) {
return Err(Error::Unsupported(
"member threshold must be the same within a group",
));
}
let mut group_secrets = Vec::new();
for (group_index, group) in groups {
group_secrets.push((
group_index,
Self::recover_secret(
group[0].0,
group
.iter()
.map(|(_, m, v)| (*m, v.clone()))
.collect::<Vec<_>>()
.as_slice(),
)?,
));
}
Ok(Seed(Self::decrypt(
id,
iteration_exponent,
Self::recover_secret(group_threshold, group_secrets.as_slice())?.as_slice(),
pd_passphrase,
)?))
}
fn preprocess(
shares: &[Share],
) -> Result<(u16, u8, u8, HashMap<u8, Vec<(u8, u8, Vec<u8>)>>), Error> {
if shares.len() < 1 {
return Err(Error::Unsupported(
"need at least one share to reconstruct secret",
));
}
let identifiers = shares.iter().map(|s| s.id).collect::<HashSet<_>>();
if identifiers.len() > 1 {
return Err(Error::Unsupported(
"shares do not belong to the same secret",
));
}
let iteration_exponents = shares
.iter()
.map(|s| s.iteration_exponent)
.collect::<HashSet<_>>();
if iteration_exponents.len() > 1 {
return Err(Error::Unsupported(
"shares do not have the same iteration exponent",
));
}
let group_thresholds = shares
.iter()
.map(|s| s.group_threshold)
.collect::<HashSet<_>>();
if group_thresholds.len() > 1 {
return Err(Error::Unsupported(
"shares do not have the same group threshold",
));
}
let group_counts = shares.iter().map(|s| s.group_count).collect::<HashSet<_>>();
if group_counts.len() > 1 {
return Err(Error::Unsupported(
"shares do not have the same group count",
));
}
if shares.iter().any(|s| s.group_threshold > s.group_count) {
return Err(Error::Unsupported(
"greater group threshold than group counts",
));
}
let mut groups = HashMap::new();
for share in shares {
groups.entry(share.group_index).or_insert(Vec::new()).push((
share.member_threshold,
share.member_index,
share.value.clone(),
));
}
return Ok((
identifiers.iter().next().unwrap().clone(),
iteration_exponents.iter().next().unwrap().clone(),
group_thresholds.iter().next().unwrap().clone(),
groups,
));
}
fn recover_secret(threshold: u8, shares: &[(u8, Vec<u8>)]) -> Result<Vec<u8>, Error> {
if threshold == 1 {
return Ok(shares[0].1.clone());
}
let shared_secret = Self::interpolate(shares, SECRET_INDEX as u8)?;
let digest_share = Self::interpolate(shares, DIGEST_INDEX as u8)?;
if &digest_share[..DIGEST_LENGTH_BYTES]
!= Self::share_digest(
&digest_share[DIGEST_LENGTH_BYTES..],
shared_secret.as_slice(),
)
.as_slice()
{
return Err(Error::Unsupported("share digest incorrect"));
}
Ok(shared_secret)
}
fn split_secret(
threshold: u8,
share_count: u8,
shared_secret: &[u8],
) -> Result<Vec<(u8, Vec<u8>)>, Error> {
if threshold < 1 {
return Err(Error::Unsupported("sharing threshold must be > 1"));
}
if share_count > MAX_SHARE_COUNT {
return Err(Error::Unsupported("too many shares"));
}
if threshold > share_count {
return Err(Error::Unsupported(
"number of shares should be at least equal threshold",
));
}
let mut shares = Vec::new();
if threshold == 1 {
for i in 0..share_count {
shares.push((i, shared_secret.to_vec()));
}
return Ok(shares);
}
let random_shares_count = std::cmp::max(threshold - 2, 0);
for i in 0..random_shares_count {
let mut share = vec![0u8; shared_secret.len()];
thread_rng().fill_bytes(share.as_mut_slice());
shares.push((i, share));
}
let mut base_shares = shares.clone();
let mut random_part = vec![0u8; shared_secret.len() - DIGEST_LENGTH_BYTES];
thread_rng().fill_bytes(random_part.as_mut_slice());
let mut digest = Self::share_digest(random_part.as_slice(), shared_secret);
digest.extend_from_slice(random_part.as_slice());
base_shares.push((DIGEST_INDEX as u8, digest));
base_shares.push((SECRET_INDEX as u8, shared_secret.to_vec()));
for i in random_shares_count..share_count {
shares.push((i, Self::interpolate(base_shares.as_slice(), i)?));
}
Ok(shares)
}
fn interpolate(shares: &[(u8, Vec<u8>)], x: u8) -> Result<Vec<u8>, Error> {
let x_coordinates = shares.iter().map(|(i, _)| *i).collect::<HashSet<_>>();
if x_coordinates.len() != shares.len() {
return Err(Error::Unsupported("need unique shares for interpolation"));
}
if shares.len() < 1 {
return Err(Error::Unsupported(
"need at least one share for interpolation",
));
}
let len = shares[0].1.len();
if shares.iter().any(|s| s.1.len() != len) {
return Err(Error::Unsupported("shares should have equal length"));
}
if x_coordinates.contains(&x) {
return Ok(shares
.iter()
.find_map(|(i, v)| if *i == x { Some(v.clone()) } else { None })
.unwrap());
}
#[inline]
fn mod_255(mut n: i16) -> i16 {
while n < 0 {
n += 255;
}
n % 255
}
let log_prod = shares
.iter()
.map(|(i, _)| Self::LOG[(*i ^ x) as usize])
.fold(0i16, |a, v| a + v as i16);
let mut result = vec![0u8; len];
for (i, share) in shares {
let log_basis = mod_255(
log_prod
- Self::LOG[(*i ^ x) as usize] as i16
- shares
.iter()
.map(|(j, _)| Self::LOG[(*j ^ *i) as usize])
.fold(0i16, |a, v| a + v as i16) as i16,
);
result.iter_mut().zip(share.iter()).for_each(|(r, s)| {
*r ^= if *s != 0 {
Self::EXP[mod_255(Self::LOG[*s as usize] as i16 + log_basis) as usize]
} else {
0
}
});
}
Ok(result)
}
fn share_digest(random: &[u8], shared_secret: &[u8]) -> Vec<u8> {
let mut mac = Hmac::new(Sha256::new(), random);
mac.input(shared_secret);
mac.result().code()[..4].to_vec()
}
// encrypt master with a passphrase
fn encrypt(
id: u16,
iteration_exponent: u8,
master: &[u8],
passphrase: Option<&str>,
) -> Result<Vec<u8>, Error> {
Self::checkpass(passphrase)?;
Ok(Self::crypt(
id,
iteration_exponent,
master,
(0..ROUND_COUNT)
.map(|n| n as u8)
.collect::<Vec<_>>()
.as_slice(),
passphrase.unwrap_or(""),
))
}
// decrypt master with a passphrase
fn decrypt(
id: u16,
iteration_exponent: u8,
master: &[u8],
passphrase: Option<&str>,
) -> Result<Vec<u8>, Error> {
Self::checkpass(passphrase)?;
Ok(Self::crypt(
id,
iteration_exponent,
master,
(0..ROUND_COUNT)
.rev()
.map(|n| n as u8)
.collect::<Vec<_>>()
.as_slice(),
passphrase.unwrap_or(""),
))
}
// check if password is only printable ascii
fn checkpass(passphrase: Option<&str>) -> Result<(), Error> {
if let Some(p) = passphrase {
if p.as_bytes().iter().any(|b| *b < 32 || *b > 126) {
return Err(Error::Unsupported(
"passphrase should only contain printable ASCII",
));
}
}
Ok(())
}
// encrypt of decrypt depending on range order
fn crypt(
id: u16,
iteration_exponent: u8,
master: &[u8],
range: &[u8],
passphrase: &str,
) -> Vec<u8> {
let len = master.len();
let mut left = vec![0u8; len / 2];
let mut right = vec![0u8; len / 2];
let mut output = vec![0u8; len / 2];
left.as_mut_slice().copy_from_slice(&master[..len / 2]);
right.as_mut_slice().copy_from_slice(&master[len / 2..]);
for i in range {
Self::feistel(
id,
iteration_exponent,
*i,
right.as_slice(),
passphrase,
&mut output,
);
output
.iter_mut()
.zip(left.iter())
.for_each(|(o, l)| *o ^= *l);
left.as_mut_slice().copy_from_slice(right.as_slice());
right.as_mut_slice().copy_from_slice(output.as_slice());
}
right.extend_from_slice(left.as_slice());
right
}
// a step of a Feistel network
fn feistel(
id: u16,
iteration_exponent: u8,
step: u8,
block: &[u8],
passphrase: &str,
output: &mut [u8],
) {
let mut key = [step].to_vec();
key.extend_from_slice(passphrase.as_bytes());
let mut mac = Hmac::new(Sha256::new(), key.as_slice());
let mut salt = "shamir".as_bytes().to_vec();
salt.extend_from_slice(&[(id >> 8) as u8, (id & 0xff) as u8]);
salt.extend_from_slice(block);
pbkdf2(
&mut mac,
salt.as_slice(),
((BASE_ITERATION_COUNT / 4) as u32) << (iteration_exponent as u32),
output,
);
}
const EXP: [u8; 255] = [
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: [u8; 256] = [
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, 69, 53,
147, 218, 142, 150, 143, 219, 189, 54, 208, 206, 148, 19, 92, 210, 241, 64, 70, 131, 56,
102, 221, 253, 48, 191, 6, 139, 98, 179, 37, 226, 152, 34, 136, 145, 16, 126, 110, 72, 195,
163, 182, 30, 66, 58, 107, 40, 84, 250, 133, 61, 186, 43, 121, 10, 21, 155, 159, 94, 202,
78, 212, 172, 229, 243, 115, 167, 87, 175, 88, 168, 80, 244, 234, 214, 116, 79, 174, 233,
213, 231, 230, 173, 232, 44, 215, 117, 122, 235, 22, 11, 245, 89, 203, 95, 176, 156, 169,
81, 160, 127, 12, 246, 111, 23, 196, 73, 236, 216, 67, 31, 45, 164, 118, 123, 183, 204,
187, 62, 90, 251, 96, 177, 134, 59, 82, 161, 108, 170, 85, 41, 157, 151, 178, 135, 144, 97,
190, 220, 252, 188, 149, 207, 205, 55, 63, 91, 209, 83, 57, 132, 60, 65, 162, 109, 71, 20,
42, 158, 93, 86, 242, 211, 171, 68, 17, 146, 217, 35, 32, 46, 137, 180, 124, 184, 38, 119,
153, 227, 165, 103, 74, 237, 222, 197, 49, 254, 24, 13, 99, 140, 128, 192, 247, 112, 7,
];
}
#[derive(Clone)]
pub struct Share {
pub id: u16,
pub iteration_exponent: u8,
pub group_index: u8,
pub group_threshold: u8,
pub group_count: u8,
pub member_index: u8,
pub member_threshold: u8,
pub value: Vec<u8>,
}
impl Share {
/// create from human readable representation
pub fn from_mnemonic(mnemonic: &str) -> Result<Share, Error> {
let words = Self::mnemonic_to_words(mnemonic)?;
if words.len() < MIN_MNEMONIC_LENGTH_WORDS {
return Err(Error::Mnemonic(
"key share mnemonic must be at least 20 words",
));
}
if Self::checksum(words.as_slice()) != 1 {
return Err(Error::Mnemonic("checksum failed"));
}
let padded_value = Self::words_to_bytes(
&words[ID_EXP_LENGTH_WORDS + 2..words.len() - CHECKSUM_LENGTH_WORDS],
);
let padding = (RADIX_BITS * (words.len() - METADATA_LENGTH_WORDS)) % 16;
if padding > 8 {
return Err(Error::Mnemonic("incorrect mnmemonic length"));
}
let mut cursor = Cursor::new(padded_value.as_slice());
let mut reader = BitStreamReader::new(&mut cursor);
if reader.read(padding as u8).unwrap() != 0 {
return Err(Error::Mnemonic("invalid padding"));
}
let mut value = Vec::new();
while let Ok(b) = reader.read(8) {
value.push(b as u8);
}
let prefix = Self::words_to_bytes(&words[..ID_EXP_LENGTH_WORDS + 2]);
let mut cursor = Cursor::new(&prefix);
let mut reader = BitStreamReader::new(&mut cursor);
Ok(Share {
id: reader.read(ID_LENGTH_BITS as u8).unwrap() as u16,
iteration_exponent: reader.read(ITERATION_EXP_LENGTH_BITS as u8).unwrap() as u8,
group_index: reader.read(4).unwrap() as u8,
group_threshold: (reader.read(4).unwrap() + 1) as u8,
group_count: (reader.read(4).unwrap() + 1) as u8,
member_index: reader.read(4).unwrap() as u8,
member_threshold: (reader.read(4).unwrap() + 1) as u8,
value,
})
}
/// convert to human readable representation
pub fn to_mnemonic(&self) -> String {
let mut bytes = Vec::new();
let mut writer = BitStreamWriter::new(&mut bytes);
writer.write(self.id as u64, 15).unwrap();
writer.write(self.iteration_exponent as u64, 5).unwrap();
writer.write(self.group_index as u64, 4).unwrap();
writer.write((self.group_threshold - 1) as u64, 4).unwrap();
writer.write((self.group_count - 1) as u64, 4).unwrap();
writer.write(self.member_index as u64, 4).unwrap();
writer.write((self.member_threshold - 1) as u64, 4).unwrap();
writer.flush().unwrap();
let value_word_count = (self.value.len() * 8 + RADIX_BITS - 1) / RADIX_BITS;
let padding = value_word_count * 10 - self.value.len() * 8;
let mut padded_value = Vec::new();
let mut writer = BitStreamWriter::new(&mut padded_value);
writer.write(0, padding as u8).unwrap();
for v in &self.value {
writer.write(*v as u64, 8).unwrap();
}
writer.flush().unwrap();
bytes.extend_from_slice(padded_value.as_slice());
let mut words = Self::bytes_to_words(&bytes[..]);
words.push(0);
words.push(0);
words.push(0);
let chk = Self::checksum(words.as_slice()) ^ 1;
let len = words.len();
for i in 0..3 {
words[len - 3 + i] = ((chk >> (RADIX_BITS as u32 * (2 - i as u32))) & 1023) as u16;
}
Self::words_to_mnemonic(&words[..])
}
// convert from byte vector to a vector of 10 bit words
fn bytes_to_words(bytes: &[u8]) -> Vec<u16> {
let mut words = Vec::new();
let mut cursor = Cursor::new(bytes);
let mut reader = BitStreamReader::new(&mut cursor);
while let Ok(w) = reader.read(RADIX_BITS as u8) {
words.push(w as u16);
}
words
}
// convert from vector of 10 bit words to byte vector
fn words_to_bytes(words: &[u16]) -> Vec<u8> {
let mut bytes = Vec::new();
let mut writer = BitStreamWriter::new(&mut bytes);
for w in words {
writer.write(*w as u64, 10).unwrap();
}
writer.flush().unwrap();
bytes
}
// convert from human readable to a vector of 10 bit words
fn mnemonic_to_words(mnemonic: &str) -> Result<Vec<u16>, Error> {
let mut words = Vec::new();
for w in mnemonic.split(' ') {
if let Ok(w) = WORDS.binary_search_by(|probe| probe[..4].cmp(&w[..4])) {
words.push(w as u16);
} else {
return Err(Error::Mnemonic("invalid word in the key share"));
}
}
Ok(words)
}
// convert to human readable words
fn words_to_mnemonic(words: &[u16]) -> String {
let mut result = String::new();
for w in words {
if !result.is_empty() {
result.push(' ');
}
result.push_str(WORDS[*w as usize]);
}
result
}
// rs1024 checksum calculator
fn checksum(values: &[u16]) -> u32 {
const GEN: [u32; 10] = [
0xE0E040, 0x1C1C080, 0x3838100, 0x7070200, 0xE0E0009, 0x1C0C2412, 0x38086C24,
0x3090FC48, 0x21B1F890, 0x3F3F120,
];
let mut chk = 1u32;
for v in CUSTOMIZATION_STRING
.iter()
.map(|c| *c as u16)
.chain(values.iter().cloned())
{
let b = chk >> 20;
chk = ((chk & 0xFFFFF) << 10) ^ (v as u32);
for i in 0..10 {
if (b >> i) & 1 != 0 {
chk ^= GEN[i as usize];
}
}
}
chk
}
}
#[cfg(test)]
mod test {
use std::collections::HashSet;
use std::str::FromStr;
use bitcoin::hashes::hex::ToHex;
use bitcoin::network::constants::Network;
use bitcoin::Address;
use rand::{thread_rng, Rng};
use serde_json::Value;
use account::{Account, AccountAddressType, MasterAccount, MasterKeyEntropy, Seed, Unlocker};
use super::{ShamirSecretSharing, Share, WORDS};
const PASSPHRASE: &str = "correct horse battery staple";
#[test]
pub fn reconstruct() {
let master =
MasterAccount::new(MasterKeyEntropy::Sufficient, Network::Bitcoin, PASSPHRASE).unwrap();
let seed = master.seed(Network::Bitcoin, PASSPHRASE).unwrap();
let shares = ShamirSecretSharing::generate(1, &[(3, 5)], &seed, None, 1).unwrap();
let reconstructed_seed = ShamirSecretSharing::combine(&shares[..3], None).unwrap();
let reconstructed_master =
MasterAccount::from_seed(&reconstructed_seed, 0, Network::Bitcoin, PASSPHRASE).unwrap();
assert_eq!(master.master_public(), reconstructed_master.master_public());
assert_eq!(master.encrypted(), reconstructed_master.encrypted());
}
#[test]
pub fn reconstruct_account() {
let shares = [
"column upstairs academic acid blue task loyalty dwarf trash election squeeze pipeline pharmacy fiber soldier already gross length acne guest",
"column upstairs academic always away perfect dynamic wrote bumpy olympic privacy satisfy fraction educate task twin animal physics bolt cage"
].iter().map(|s| Share::from_mnemonic(s).unwrap()).collect::<Vec<_>>();
let seed = ShamirSecretSharing::combine(&shares[..], None).unwrap();
let mut master = MasterAccount::from_seed(&seed, 0, Network::Bitcoin, PASSPHRASE).unwrap();
let mut unlocker = Unlocker::new_for_master(&master, PASSPHRASE).unwrap();
master.add_account(
Account::new(&mut unlocker, AccountAddressType::P2SHWPKH, 0, 0, 10).unwrap(),
);
assert_eq!(
master.get_mut((0, 0)).unwrap().next_key().unwrap().address,
Address::from_str("3JKyFZdkKYYgxFT37cPgJDxqNzQQKbbbtj").unwrap()
);
}
#[test]
pub fn round_trips() {
let mut secret = [0u8; 32];
thread_rng().fill(&mut secret);
let seed = Seed(secret.to_vec());
for n in 1..16 {
let shares = ShamirSecretSharing::generate(1, &[(n, n)], &seed, None, 0).unwrap();
assert_eq!(seed, ShamirSecretSharing::combine(&shares, None).unwrap());
}
for n in 2..5 {
let shares = ShamirSecretSharing::generate(
n,
vec![(1, 1); n as usize].as_slice(),
&seed,
None,
0,
)
.unwrap();
assert_eq!(seed, ShamirSecretSharing::combine(&shares, None).unwrap());
}
for n in 3..6 {
for m in 2..4 {
let shares =
ShamirSecretSharing::generate(1, vec![(m, n)].as_slice(), &seed, None, 0)
.unwrap();
assert_eq!(
seed,
ShamirSecretSharing::combine(&shares[..(m as usize)], None).unwrap()
);
}
}
}
#[test]
pub fn precompute() {
let mut exp = Vec::new();
let mut log = vec![0u8; 256];
let mut poly = 1u16;
for i in 0u8..255u8 {
exp.push(poly as u8);
log[poly as usize] = i;
poly = (poly << 1) ^ poly;
if poly & 0x100 != 0 {
poly ^= 0x11b;
}
}
for (i, e) in exp.iter().enumerate() {
assert_eq!(ShamirSecretSharing::EXP[i], *e);
}
for (i, l) in log.iter().enumerate() {
assert_eq!(ShamirSecretSharing::LOG[i], *l);
}
}
#[test]
pub fn wordlist_checks() {
let mut words = WORDS.clone();
words.sort();
assert_eq!(&words[..], &WORDS[..]);
assert!(!WORDS.iter().any(|w| w.len() < 4 || w.len() > 8));
let mut first4 = HashSet::new();
assert!(!WORDS
.iter()
.any(|w| first4.insert(w[..4].to_string()) == false));
}
#[test]
pub fn trezor_tests() {
let json: Value = serde_json::from_str(TEST_CASES).unwrap();
let tests = json.as_array().unwrap();
for t in 0..tests.len() {
let values = tests[t].as_array().unwrap();
let title = values[0].as_str().unwrap();
println!("{}", title);
let result = values[2].as_str().unwrap();
if result.is_empty() {
let shares = values[1]
.as_array()
.unwrap()
.iter()
.filter_map(|v| {
if let Ok(s) = Share::from_mnemonic(v.as_str().unwrap()) {
Some(s)
} else {
None
}
})
.collect::<Vec<_>>();
if !shares.is_empty() {
assert!(ShamirSecretSharing::combine(&shares, Some("TREZOR")).is_err());
}
} else {
let shares = values[1]
.as_array()
.unwrap()
.iter()
.map(|v| Share::from_mnemonic(v.as_str().unwrap()).unwrap())
.collect::<Vec<_>>();
assert_eq!(result,
ShamirSecretSharing::combine(&shares, Some("TREZOR")).unwrap().0.to_hex(),
);
}
}
}
const TEST_CASES: &str = r#"
[
[
"1. Valid mnemonic without sharing (128 bits)",
[
"duckling enlarge academic academic agency result length solution fridge kidney coal piece deal husband erode duke ajar critical decision keyboard"
],
"bb54aac4b89dc868ba37d9cc21b2cece"
],
[
"2. Mnemonic with invalid checksum (128 bits)",
[
"duckling enlarge academic academic agency result length solution fridge kidney coal piece deal husband erode duke ajar critical decision kidney"
],
""
],
[
"3. Mnemonic with invalid padding (128 bits)",
[
"duckling enlarge academic academic email result length solution fridge kidney coal piece deal husband erode duke ajar music cargo fitness"
],
""
],
[
"4. Basic sharing 2-of-3 (128 bits)",
[
"shadow pistol academic always adequate wildlife fancy gross oasis cylinder mustang wrist rescue view short owner flip making coding armed",
"shadow pistol academic acid actress prayer class unknown daughter sweater depict flip twice unkind craft early superior advocate guest smoking"
],
"b43ceb7e57a0ea8766221624d01b0864"
],
[
"5. Basic sharing 2-of-3 (128 bits)",
[
"shadow pistol academic always adequate wildlife fancy gross oasis cylinder mustang wrist rescue view short owner flip making coding armed"
],
""
],
[
"6. Mnemonics with different identifiers (128 bits)",
[
"adequate smoking academic acid debut wine petition glen cluster slow rhyme slow simple epidemic rumor junk tracks treat olympic tolerate",
"adequate stay academic agency agency formal party ting frequent learn upstairs remember smear leaf damage anatomy ladle market hush corner"
],
""
],
[
"7. Mnemonics with different iteration exponents (128 bits)",
[
"peasant leaves academic acid desert exact olympic math alive axle trial tackle drug deny decent smear dominant desert bucket remind",
"peasant leader academic agency cultural blessing percent network envelope medal junk primary human pumps jacket fragment payroll ticket evoke voice"
],
""
],
[
"8. Mnemonics with mismatching group thresholds (128 bits)",
[
"liberty category beard echo animal fawn temple briefing math username various wolf aviation fancy visual holy thunder yelp helpful payment",
"liberty category beard email beyond should fancy romp founder easel pink holy hairy romp loyalty material victim owner toxic custody",
"liberty category academic easy being hazard crush diminish oral lizard reaction cluster force dilemma deploy force club veteran expect photo"
],
""
],
[
"9. Mnemonics with mismatching group counts (128 bits)",
[
"average senior academic leaf broken teacher expect surface hour capture obesity desire negative dynamic dominant pistol mineral mailman iris aide",
"average senior academic agency curious pants blimp spew clothes slice script dress wrap firm shaft regular slavery negative theater roster"
],
""
],
[
"10. Mnemonics with greater group threshold than group counts (128 bits)",
[
"music husband acrobat acid artist finance center either graduate swimming object bike medical clothes station aspect spider maiden bulb welcome",
"music husband acrobat agency advance hunting bike corner density careful material civil evil tactics remind hawk discuss hobo voice rainbow",
"music husband beard academic black tricycle clock mayor estimate level photo episode exclude ecology papa source amazing salt verify divorce"
],
""
],
[
"11. Mnemonics with duplicate member indices (128 bits)",
[
"device stay academic always dive coal antenna adult black exceed stadium herald advance soldier busy dryer daughter evaluate minister laser",
"device stay academic always dwarf afraid robin gravity crunch adjust soul branch walnut coastal dream costume scholar mortgage mountain pumps"
],
""
],
[
"12. Mnemonics with mismatching member thresholds (128 bits)",
[
"hour painting academic academic device formal evoke guitar random modern justice filter withdraw trouble identify mailman insect general cover oven",
"hour painting academic agency artist again daisy capital beaver fiber much enjoy suitable symbolic identify photo editor romp float echo"
],
""
],
[
"13. Mnemonics giving an invalid digest (128 bits)",
[
"guilt walnut academic acid deliver remove equip listen vampire tactics nylon rhythm failure husband fatigue alive blind enemy teaspoon rebound",
"guilt walnut academic agency brave hamster hobo declare herd taste alpha slim criminal mild arcade formal romp branch pink ambition"
],
""
],
[
"14. Insufficient number of groups (128 bits, case 1)",
[
"eraser senior beard romp adorn nuclear spill corner cradle style ancient family general leader ambition exchange unusual garlic promise voice"
],
""
],
[
"15. Insufficient number of groups (128 bits, case 2)",
[
"eraser senior decision scared cargo theory device idea deliver modify curly include pancake both news skin realize vitamins away join",
"eraser senior decision roster beard treat identify grumpy salt index fake aviation theater cubic bike cause research dragon emphasis counter"
],
""
],
[
"16. Threshold number of groups, but insufficient number of members in one group (128 bits)",
[
"eraser senior decision shadow artist work morning estate greatest pipeline plan ting petition forget hormone flexible general goat admit surface",
"eraser senior beard romp adorn nuclear spill corner cradle style ancient family general leader ambition exchange unusual garlic promise voice"
],
""
],
[
"17. Threshold number of groups and members in each group (128 bits, case 1)",
[
"eraser senior decision roster beard treat identify grumpy salt index fake aviation theater cubic bike cause research dragon emphasis counter",
"eraser senior ceramic snake clay various huge numb argue hesitate auction category timber browser greatest hanger petition script leaf pickup",
"eraser senior ceramic shaft dynamic become junior wrist silver peasant force math alto coal amazing segment yelp velvet image paces",
"eraser senior ceramic round column hawk trust auction smug shame alive greatest sheriff living perfect corner chest sled fumes adequate",
"eraser senior decision smug corner ruin rescue cubic angel tackle skin skunk program roster trash rumor slush angel flea amazing"
],
"7c3397a292a5941682d7a4ae2d898d11"
],
[
"18. Threshold number of groups and members in each group (128 bits, case 2)",
[
"eraser senior decision smug corner ruin rescue cubic angel tackle skin skunk program roster trash rumor slush angel flea amazing",
"eraser senior beard romp adorn nuclear spill corner cradle style ancient family general leader ambition exchange unusual garlic promise voice",
"eraser senior decision scared cargo theory device idea deliver modify curly include pancake both news skin realize vitamins away join"
],
"7c3397a292a5941682d7a4ae2d898d11"
],
[
"19. Threshold number of groups and members in each group (128 bits, case 3)",
[
"eraser senior beard romp adorn nuclear spill corner cradle style ancient family general leader ambition exchange unusual garlic promise voice",
"eraser senior acrobat romp bishop medical gesture pumps secret alive ultimate quarter priest subject class dictate spew material endless market"
],
"7c3397a292a5941682d7a4ae2d898d11"
],
[
"20. Valid mnemonic without sharing (256 bits)",
[
"theory painting academic academic armed sweater year military elder discuss acne wildlife boring employer fused large satoshi bundle carbon diagnose anatomy hamster leaves tracks paces beyond phantom capital marvel lips brave detect luck"
],
"989baf9dcaad5b10ca33dfd8cc75e42477025dce88ae83e75a230086a0e00e92"
],
[
"21. Mnemonic with invalid checksum (256 bits)",
[
"theory painting academic academic armed sweater year military elder discuss acne wildlife boring employer fused large satoshi bundle carbon diagnose anatomy hamster leaves tracks paces beyond phantom capital marvel lips brave detect lunar"
],
""