Bech32.decode constructor

Bech32.decode(
  1. String encoded
)

Decodes a bech32 string into the hrp, 5-bit words and type. May throw an InvalidBech32. It will throw InvalidBech32Checksum if the bech32 is valid but doesn't have a valid checksum for either bech32 or bech32m.

Implementation

factory Bech32.decode(String encoded) {

  if (encoded.length > maxLength) {
    throw InvalidBech32("Bech32 too long");
  }

  final lower = encoded.toLowerCase();

  if (lower != encoded && encoded.toUpperCase() != encoded) {
    throw InvalidBech32("Bech32 cannot be mixed case");
  }

  final split = lower.lastIndexOf('1');
  if (split < 1) throw InvalidBech32("Missing HRP");
  if (lower.length - split - 1 < checksumLength) {
    throw InvalidBech32("Checksum too short");
  }

  final hrp = lower.substring(0, split);
  _throwOnInvalidHrp(hrp);

  final words = _charsToWords(lower.substring(split + 1));
  final dataWords = words.sublist(0, words.length - 6);

  if (words.any((w) => w == -1)) throw InvalidBech32("Invalid character");

  // Verify type
  final pm = _polymod(hrp, words);
  late Bech32Type type;
  if (pm == bech32CheckConst) {
    type = Bech32Type.bech32;
  } else if (pm == bech32mCheckConst) {
    type = Bech32Type.bech32m;
  } else {
    throw InvalidBech32Checksum();
  }

  final bech32 = Bech32._skipValidation(hrp: hrp, words: dataWords, type: type);
  bech32._encodedCache = encoded;
  return bech32;

}