validMnemonic function
If the mnemonic or recovery phrase has all legal characters and the requiredNumberOfWords, then the normalized correct form is returned. If it's not legal, then an explanation is returned in the error message.
Implementation
Result<String, String> validMnemonic({
required String phrase,
int requiredNumberOfWords = 24,
}) {
if (phrase.isEmpty) {
return Err("mnemonic required");
}
final lowerCase = phrase.toLowerCase().trim(); //TODO normalize white space
int invalidCharIndex = _firstIllegalDataChar(lowerCase);
if (invalidCharIndex > -1) {
return Err(
"invalid character: ${lowerCase.substring(invalidCharIndex, invalidCharIndex + 1)}");
}
final words = lowerCase.split(' ');
try {
bip39.mnemonicToEntropy(lowerCase);
} on ArgumentError catch (e) {
//might be a bad word, see if we can find it
final validity = validMnemonicWords(words);
if (validity.isErr()) return Err(validity.unwrapErr());
//otherwise check length
if (words.length != requiredNumberOfWords) {
return Err("$requiredNumberOfWords words required");
}
return Err(e.message);
} on StateError catch (e) {
if (words.length != requiredNumberOfWords) {
return Err("$requiredNumberOfWords words required");
}
return Err(e.message);
} catch (e) {
return Err(e.toString());
}
if (words.length != requiredNumberOfWords) {
return Err("$requiredNumberOfWords words required");
}
return Ok(lowerCase);
}