decodeBech32 static method
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 (String, List<int>) decodeBech32(
String bechStr,
String sep,
int checksumLen,
bool Function(String hrp, List<int> data) verifyChecksum,
) {
if (_isStringMixed(bechStr)) {
throw ArgumentException.invalidOperationArguments(
"decodeBech32",
name: "data",
reason: 'Invalid bech32 format.',
);
}
bechStr = bechStr.toLowerCase();
final sepPos = bechStr.lastIndexOf(sep);
if (sepPos == -1) {
throw ArgumentException.invalidOperationArguments(
"decodeBech32",
name: "data",
reason: 'Invalid bech32 format.',
);
}
final hrp = bechStr.substring(0, sepPos);
if (hrp.isEmpty || hrp.codeUnits.any((x) => x < 33 || x > 126)) {
throw ArgumentException.invalidOperationArguments(
"decodeBech32",
name: "data",
reason: 'Invalid bech32 format.',
);
}
final dataPart = bechStr.substring(sepPos + 1);
if (dataPart.length < checksumLen + 1 ||
dataPart.codeUnits.any(
(x) => !Bech32BaseConst.charset.contains(String.fromCharCode(x)),
)) {
throw ArgumentException.invalidOperationArguments(
"decodeBech32",
name: "data",
reason: 'Invalid bech32 format.',
);
}
final intData =
dataPart.codeUnits
.map((x) => Bech32BaseConst.charset.indexOf(String.fromCharCode(x)))
.toList();
if (!verifyChecksum(hrp, intData)) {
throw const Bech32Error("Invalid checksum.");
}
return (hrp, intData.sublist(0, intData.length - checksumLen));
}