@@ -529,6 +529,28 @@ impl Mnemonic {
529
529
let ( arr, len) = self . to_entropy_array ( ) ;
530
530
arr[ 0 ..len] . to_vec ( )
531
531
}
532
+
533
+ /// Calculates the final word (based on the checksum) of a manually generated mnemonic.
534
+ /// There are multiple valid checksums, the first one (alphabetically) is picked.
535
+ #[ cfg( feature = "std" ) ]
536
+ pub fn finalize_mnemonic < ' a , S : Into < Cow < ' a , str > > > ( s : S ) -> Result < Mnemonic , Error > {
537
+ let mut words = s. into ( ) ;
538
+ Mnemonic :: normalize_utf8_cow ( & mut words) ;
539
+ let language = Mnemonic :: language_of ( & words) ?;
540
+
541
+ for word in language. word_list ( ) {
542
+ let potential_mnemonic = format ! ( "{} {}" , words, word) ;
543
+ match Mnemonic :: parse_in_normalized ( language, & potential_mnemonic) {
544
+ Ok ( mnemonic) => return Ok ( mnemonic) ,
545
+ Err ( e) => match e {
546
+ Error :: InvalidChecksum => { } , // Keep searching.
547
+ _ => return Err ( e)
548
+ }
549
+ }
550
+ }
551
+ Err ( Error :: InvalidChecksum )
552
+ }
553
+
532
554
}
533
555
534
556
impl fmt:: Display for Mnemonic {
@@ -1023,4 +1045,30 @@ mod tests {
1023
1045
assert_eq ! ( seed, & mnemonic. to_seed( passphrase) [ ..] , "failed vector: {}" , mnemonic_str) ;
1024
1046
}
1025
1047
}
1048
+
1049
+ #[ test]
1050
+ fn test_finalize_mnemonic ( ) {
1051
+ let vectors = [
1052
+ (
1053
+ "ozone drill grab fiber curtain grace pudding thank cruise elder eight" ,
1054
+ "about"
1055
+ ) ,
1056
+ (
1057
+ "light rule cinnamon wrap drastic word pride squirrel upgrade then income fatal apart sustain crack supply proud" ,
1058
+ "access"
1059
+ ) ,
1060
+ (
1061
+ "hamster diagram private dutch cause delay private meat slide toddler razor book happy fancy gospel tennis maple dilemma loan word shrug inflict delay" ,
1062
+ "balance"
1063
+ ) ,
1064
+ (
1065
+ "あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん" ,
1066
+ "あおぞら"
1067
+ )
1068
+ ] ;
1069
+
1070
+ for vector in & vectors {
1071
+ assert_eq ! ( Mnemonic :: parse( format!( "{} {}" , vector. 0 , vector. 1 ) ) , Mnemonic :: finalize_mnemonic( vector. 0 ) ) ;
1072
+ }
1073
+ }
1026
1074
}
0 commit comments