decode static method

Tuple<int, List<int>> decode(
  1. String? hrp,
  2. String addr
)

Decodes a Bech32-encoded SegWit address.

This method decodes a Bech32-encoded SegWit address, verifying its format, Human-Readable Part (HRP), witness version, and witness program.

  • hrp: The expected Human-Readable Part (HRP) for the address.
  • addr: The Bech32-encoded SegWit address to decode.

Returns a tuple containing the SegWit version (witness version) and the decoded witness program as a List

Implementation

static Tuple<int, List<int>> decode(String? hrp, String addr) {
  final decoded = Bech32DecoderBase.decodeBech32(
      addr,
      SegwitBech32Const.separator,
      SegwitBech32Const.checksumStrLen,
      _verifyChecksum);
  final hrpGot = decoded.item1;
  final data = decoded.item2;

  // Check HRP
  if (hrp != null && hrp != hrpGot) {
    throw ArgumentException(
        'Invalid format (HRP not valid, expected $hrp, got $hrpGot)');
  }

  // Convert back from base32 (remove witness version)
  final convData = Bech32BaseUtils.convertFromBase32(data.sublist(1));

  // Check data length
  if (convData.length < SegwitBech32Const.witnessProgMinByteLen ||
      convData.length > SegwitBech32Const.witnessProgMaxByteLen) {
    throw ArgumentException(
        'Invalid format (witness program length not valid: ${convData.length})');
  }

  // Check witness version
  final witVer = data[0];
  if (witVer > SegwitBech32Const.witnessVerMaxVal) {
    throw ArgumentException(
        'Invalid format (witness version not valid: $witVer)');
  }

  if (witVer == 0 &&
      !SegwitBech32Const.witnessVerZeroDataByteLen
          .contains(convData.length)) {
    throw ArgumentException(
        'Invalid format (length not valid: ${convData.length})');
  }

  return Tuple(witVer, convData);
}