decodeBech32 static method

Tuple<String, List<int>> decodeBech32(
  1. String bechStr,
  2. String sep,
  3. int checksumLen,
  4. bool verifyChecksum(
    1. String hrp,
    2. List<int> data
    ),
)

Decodes a Bech32-encoded string into its components.

Parameters:

  • bechStr: The Bech32-encoded string to decode.
  • sep: The separator character used in the Bech32 string.
  • checksumLen: The length of the checksum in the Bech32 string.
  • verifyChecksum: A function that verifies the checksum of the Bech32 string.

Returns: A tuple containing the Human-Readable Part (HRP) and the data part of the Bech32-encoded string.

Throws:

  • ArgumentException: If the input string is mixed case, lacks a separator, HRP is invalid, or the checksum is invalid.

Implementation

static Tuple<String, List<int>> decodeBech32(
    String bechStr,
    String sep,
    int checksumLen,
    bool Function(String hrp, List<int> data) verifyChecksum) {
  if (_isStringMixed(bechStr)) {
    throw ArgumentException('Invalid bech32 format (string is mixed case)');
  }

  bechStr = bechStr.toLowerCase();

  final sepPos = bechStr.lastIndexOf(sep);
  if (sepPos == -1) {
    throw ArgumentException('Invalid bech32 format (no separator found)');
  }

  final hrp = bechStr.substring(0, sepPos);
  if (hrp.isEmpty || hrp.codeUnits.any((x) => x < 33 || x > 126)) {
    throw ArgumentException('Invalid bech32 format (HRP not valid: $hrp)');
  }

  final dataPart = bechStr.substring(sepPos + 1);

  if (dataPart.length < checksumLen + 1 ||
      dataPart.codeUnits.any(
          (x) => !Bech32BaseConst.charset.contains(String.fromCharCode(x)))) {
    throw ArgumentException('Invalid bech32 format (data part not valid)');
  }

  final intData = dataPart.codeUnits
      .map((x) => Bech32BaseConst.charset.indexOf(String.fromCharCode(x)))
      .toList();
  if (!verifyChecksum(hrp, intData)) {
    throw const Bech32ChecksumError('Invalid bech32 checksum');
  }

  return Tuple(
      hrp, List<int>.from(intData.sublist(0, intData.length - checksumLen)));
}