decodeBech32 static method

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

Implementation

static (String, List<int>) decodeBech32(
  String bechStr,
  String sep,
  int checksumLen,
  bool Function(String hrp, List<int> data) verifyChecksum,
) {
  if (_isStringMixedCase(bechStr)) {
    throw const BuError(
      DefaultErrorType.badBech32,
      'Invalid bech32 format.',
      details: {'reason': 'mixed uppercase and lowercase characters'},
    );
  }

  bechStr = bechStr.toLowerCase();

  final sepPos = bechStr.lastIndexOf(sep);
  if (sepPos == -1) {
    throw BuError(
      DefaultErrorType.badBech32,
      'Invalid bech32 format.',
      details: {'reason': 'missing separator "$sep"'},
    );
  }

  final hrp = bechStr.substring(0, sepPos);
  if (hrp.isEmpty || StringUtils.encode(hrp).any((x) => x < 33 || x > 126)) {
    throw const BuError(
      DefaultErrorType.badBech32,
      'Invalid bech32 format.',
      details: {'reason': 'empty or invalid human-readable part'},
    );
  }

  final dataPart = bechStr.substring(sepPos + 1);
  // Exactly checksumLen characters (zero-length payload, pure checksum)
  // is the minimum valid length - e.g. the official BIP-173 minimal
  // test vector "A12UEL5L" has a 6-character data part with
  // checksumStrLen == 6. The original required checksumLen + 1 here,
  // which would incorrectly reject that vector.
  if (dataPart.length < checksumLen) {
    throw const BuError(
      DefaultErrorType.invalidChecksum,
      'Invalid bech32 format.',
      details: {'reason': 'data part shorter than the checksum length'},
    );
  }

  // Single pass: validates every character AND looks up its value at
  // the same time, instead of one .any()/.contains() scan (each
  // re-scanning the 32-char charset per input character, and each
  // allocating a fresh 1-char String to do so) followed by a second
  // .indexOf() pass to actually get the values.
  final intData = List<int>.filled(dataPart.length, 0);
  for (var i = 0; i < dataPart.length; i++) {
    final value = Bech32BaseConst.valueOf(dataPart.codeUnitAt(i));
    if (value == -1) {
      throw BuError(
        DefaultErrorType.badBech32,
        'Invalid bech32 format.',
        details: {'reason': 'invalid character at index $i'},
      );
    }
    intData[i] = value;
  }

  if (!verifyChecksum(hrp, intData)) {
    throw const BuError(
      DefaultErrorType.invalidChecksum,
      'Invalid checksum.',
      details: {'reason': 'checksum verification failed'},
    );
  }

  return (hrp, intData.sublist(0, intData.length - checksumLen));
}