validatePhrase function

Uint8List validatePhrase(
  1. String phrase, {
  2. required CryptoImplementation crypto,
})

Implementation

Uint8List validatePhrase(
  String phrase, {
  required CryptoImplementation crypto,
}) {
  phrase = sanitizePhrase(phrase);
  final phraseWords = phrase.split(' ');

  if (phraseWords.length != PHRASE_LENGTH) {
    throw 'Phrase must be 15 words long, was ${phraseWords.length}';
  }

  // Build the seed from words.
  final seedWords = Uint16List(SEED_WORDS_LENGTH);

  var i = 0;
  for (final word in phraseWords) {
    // Check word length.
    if (word.length < 3) {
      throw 'Word ${i + 1} is not at least 3 letters long';
    }

    // Check word prefix.
    final prefix = word.substring(0, 3);
    var bound = wordlist.length;
    if (i == 0) {
      bound = 256;
    }
    var found = -1;
    for (var j = 0; j < bound; j++) {
      final curPrefix = wordlist[j].substring(0, 3);
      if (curPrefix == prefix) {
        found = j;
        break;
      }
    }
    if (found < 0) {
      if (i == 0) {
        throw 'Prefix for word ${i + 1} must be found in the first 256 words of the wordlist';
      } else {
        throw 'Unrecognized prefix "$prefix" at word ${i + 1}, not found in wordlist';
      }
    }

    seedWords[i] = found;

    i++;
    if (i >= SEED_WORDS_LENGTH) break;
  }

  // Validate checksum.
  final checksumWords = generateChecksumWordsFromSeedWords(
    seedWords,
    crypto: crypto,
  );
  for (var i = 0; i < CHECKSUM_WORDS_LENGTH; i++) {
    final prefix = wordlist[checksumWords[i]].substring(0, 3);
    if (phraseWords[i + SEED_WORDS_LENGTH].substring(0, 3) != prefix) {
      throw 'Word "${phraseWords[i + SEED_WORDS_LENGTH + 1]}" is not a valid checksum for the seed';
    }
  }

  return seedWordsToSeed(seedWords);
}