Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add function to calculate checksum and last word of a manually generated mnemonic #7

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
46 changes: 46 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,26 @@ impl Mnemonic {
let (arr, len) = self.to_entropy_array();
arr[0..len].to_vec()
}

/// Calculates the final word (based on the checksum) of a manually generated mnemonic.
/// There are multiple valid checksums, the first one (alphabetically) is picked.
#[cfg(feature = "std")]
pub fn finalize_mnemonic<'a, S: Into<Cow<'a, str>>>(s: S) -> Result<Mnemonic, Error> {
let mut words = s.into();
Mnemonic::normalize_utf8_cow(&mut words);
let language = Mnemonic::language_of(&words)?;

for word in language.word_list() {
let potential_mnemonic = format!("{} {}", words, word);
match Mnemonic::parse_in_normalized(language, &potential_mnemonic) {
Ok(mnemonic) => return Ok(mnemonic),
Err(Error::InvalidChecksum) => {}, // Keep searching.
Err(e) => return Err(e)
}
}
Err(Error::InvalidChecksum)
}

}

impl fmt::Display for Mnemonic {
Expand Down Expand Up @@ -1023,4 +1043,30 @@ mod tests {
assert_eq!(seed, &mnemonic.to_seed(passphrase)[..], "failed vector: {}", mnemonic_str);
}
}

#[test]
fn test_finalize_mnemonic() {
let vectors = [
(
"ozone drill grab fiber curtain grace pudding thank cruise elder eight",
"about"
),
(
"light rule cinnamon wrap drastic word pride squirrel upgrade then income fatal apart sustain crack supply proud",
"access"
),
(
"hamster diagram private dutch cause delay private meat slide toddler razor book happy fancy gospel tennis maple dilemma loan word shrug inflict delay",
"balance"
),
(
"あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん あいこくしん",
"あおぞら"
)
];

for vector in &vectors {
assert_eq!(Mnemonic::parse(format!("{} {}", vector.0, vector.1)), Mnemonic::finalize_mnemonic(vector.0));
}
}
}