Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/version_and_tests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ on:

jobs:
app-version-check:
runs-on: ubuntu-20.04
runs-on: ubuntu-24.04
steps:
# https://github.com/marketplace/actions/checkout
- uses: actions/checkout@main
Expand Down Expand Up @@ -52,7 +52,7 @@ jobs:
exit 1
run-unit-tests:
needs: app-version-check
runs-on: ubuntu-20.04
runs-on: ubuntu-24.04
steps:
# https://github.com/marketplace/actions/checkout
- uses: actions/checkout@main
Expand Down
16 changes: 11 additions & 5 deletions lib/codec_utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,18 @@ export 'src/codecs/base/base58_codec.dart';

/// Classes designed for encoding data using the Bech32 encoding scheme.
/// Usage:
/// ```
/// String encodedBech32 = Bech32Codec.encode(Bech32Pair(hrp: 'crypto', data: base64Decode('KxmiVli7oFEs8N5rjnzLtw7eym0=')));
/// Bech32Pair decodedBech32 = Bech32Codec.decode("crypto19vv6y4jchws9zt8sme4culxtku8dajndgyhdm2");
/// ``
/// List<int> convertedUint5List = BytesUtils.convertBits(Bech32.uint8List, 8, 5, padBool: true);
///
/// Bech32 bech32 = Bech32.fromUint5List('bc', convertedUint5List)
/// String encodedBech32 = Bech32Encoder().encode(bech32);
///
/// Bech32 decodedBech32 = Bech32Codec().decode("crypto19vv6y4jchws9zt8sme4culxtku8dajndgyhdm2");
///
/// SegWit segWit = SegWit(hrp, witnessVersion, witnessProgramUint8List);
/// String encodedSegWit SegWitEncoder().encode(segWit);
///
/// String encodedSegwit = SegwitBech32Codec.encode('bc', 0, base64Decode('KxmiVli7oFEs8N5rjnzLtw7eym0='));
/// Uint8List decodedSegwit = SegwitBech32Codec.decode("bc1q9vv6y4jchws9zt8sme4culxtku8dajnd5jq660");
/// SegWit decodedSegWit = SegWitDecoder().decode("bc1q9vv6y4jchws9zt8sme4culxtku8dajnd5jq660");
/// ```
export 'src/codecs/bech32/export.dart';

Expand Down
31 changes: 31 additions & 0 deletions lib/src/codecs/bech32/bech32.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import 'dart:typed_data';

import 'package:codec_utils/src/utils/bytes_utils.dart';
import 'package:equatable/equatable.dart';

/// Class representing a Bech32 encoded pair
///
/// A Bech32 string consists of two main parts:
/// - The human-readable part (HRP), which indicates the network or context.
/// - The data payload encoded using a 5-bit scheme.
class Bech32 extends Equatable {
/// The human-readable part (hrp) of the Bech32 encoded pair.
final String hrp;

/// The data part of the Bech32 encoded pair.
final Uint8List uint8List;

const Bech32(this.hrp, this.uint8List);

factory Bech32.fromUint5List(String hrp, List<int> uint5List) {
Uint8List uint8List = BytesUtils.convertBits(uint5List, 5, 8);
return Bech32(hrp, uint8List);
}

List<int> get uint5List {
return BytesUtils.convertBits(uint8List, 8, 5, allowPaddingBool: false);
}

@override
List<Object?> get props => <Object?>[hrp, uint8List];
}
60 changes: 0 additions & 60 deletions lib/src/codecs/bech32/bech32_codec.dart

This file was deleted.

17 changes: 17 additions & 0 deletions lib/src/codecs/bech32/bech32_constants.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
class Bech32Constants {
static const int maxInputLength = 90;
static const int checksumLength = 6;
static const String separator = '1';
static const List<String> charList = <String>[
'q', 'p', 'z', 'r', 'y', '9', 'x', //
'8', 'g', 'f', '2', 't', 'v', 'd',
'w', '0', 's', '3', 'j', 'n', '5',
'4', 'k', 'h', 'c', 'e', '6', 'm',
'u', 'a', '7', 'l',
];

static const List<int> generatorList = <int>[
0x3b6a57b2, 0x26508e6d, 0x1ea119fa, //
0x3d4233dd, 0x2a1462b3,
];
}
83 changes: 83 additions & 0 deletions lib/src/codecs/bech32/bech32_decoder.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
// This class was primarily influenced by:
// Copyright 2020 Harm Aarts
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,
// sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import 'package:codec_utils/codec_utils.dart';
import 'package:codec_utils/src/codecs/bech32/bech32_constants.dart';
import 'package:codec_utils/src/codecs/bech32/bech32_utils.dart';
import 'package:codec_utils/src/codecs/bech32/exceptions/invalid_bech32_exception.dart';
import 'package:codec_utils/src/codecs/bech32/exceptions/invalid_checksum_exception.dart';
import 'package:codec_utils/src/codecs/bech32/exceptions/invalid_hrp_exception.dart';

/// A utility class for decoding Bech32-encoded strings into [Bech32] objects.
///
/// This decoder validates and parses a Bech32 string into its human-readable part (HRP)
/// and data payload, following the specifications described in BIP 173 and BIP 350.
class Bech32Decoder {
Bech32 decode(String bechAddress, [int maxInputLength = Bech32Constants.maxInputLength]) {
if (bechAddress.length > maxInputLength) {
throw InvalidBech32Exception('Bech32 is too long: ${bechAddress.length} > 90');
}
if (bechAddress.toLowerCase() != bechAddress && bechAddress.toUpperCase() != bechAddress) {
throw InvalidBech32Exception('Bech32 input must be either all lowercase or all uppercase: $bechAddress');
}
if (bechAddress.lastIndexOf(Bech32Constants.separator) == -1) {
throw InvalidBech32Exception('Bech32 string is missing the required separator between HRP and data');
}

int separatorPosition = bechAddress.lastIndexOf(Bech32Constants.separator);

if (bechAddress.length - separatorPosition - 1 - Bech32Constants.checksumLength < 0) {
throw InvalidChecksumException('Checksum is too short: ${bechAddress.length} < 6');
}

if (separatorPosition == 0) {
throw InvalidHrpException('HRP is too short: $separatorPosition');
}

String normalizedInput = bechAddress.toLowerCase();

String hrp = normalizedInput.substring(0, separatorPosition);
String data = normalizedInput.substring(separatorPosition + 1, bechAddress.length - Bech32Constants.checksumLength);
String checksum = normalizedInput.substring(bechAddress.length - Bech32Constants.checksumLength);

if (hrp.codeUnits.any((int element) => element < 33 || element > 126)) {
throw InvalidHrpException('HRP contains invalid characters: $hrp');
}

List<int> uint5List = data.split('').map((String element) {
return Bech32Constants.charList.indexOf(element);
}).toList();

if (uint5List.any((int element) => element == -1)) {
throw InvalidBech32Exception('Bech32 has undefined character: ${data[uint5List.indexOf(-1)]}');
}

List<int> checksumUint5List = checksum.split('').map((String element) {
return Bech32Constants.charList.indexOf(element);
}).toList();

if (checksumUint5List.any((int element) => element == -1)) {
int invalidIndex = checksumUint5List.indexOf(-1);
throw InvalidChecksumException('Checksum contains undefined character at position: ${checksumUint5List[invalidIndex]}');
}

List<int> expandedHrpUint5List = Bech32Utils.expandHrp(hrp);

if (Bech32Utils.calculatePolymodChecksum(expandedHrpUint5List + (uint5List + checksumUint5List)) != 1) {
throw InvalidChecksumException('Checksum verification failed for input: $bechAddress');
}

return Bech32.fromUint5List(hrp, uint5List);
}
}
62 changes: 62 additions & 0 deletions lib/src/codecs/bech32/bech32_encoder.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// This class was primarily influenced by:
// Copyright 2020 Harm Aarts
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import 'dart:typed_data';

import 'package:codec_utils/codec_utils.dart';
import 'package:codec_utils/src/codecs/bech32/bech32_constants.dart';
import 'package:codec_utils/src/codecs/bech32/bech32_utils.dart';
import 'package:codec_utils/src/codecs/bech32/exceptions/invalid_bech32_exception.dart';
import 'package:codec_utils/src/codecs/bech32/exceptions/invalid_hrp_exception.dart';

/// A utility class for encoding [Bech32] objects into valid Bech32 strings.
///
/// This encoder converts a [Bech32] instance (which contains a human-readable part (HRP)
/// and a data payload) into a properly formatted Bech32 string, as specified in
/// BIP 173 and BIP 350.
class Bech32Encoder {
/// Encodes a [Bech32] object [bech32] into a valid Bech32 string.
String encode(Bech32 bech32, [int maxLength = Bech32Constants.maxInputLength]) {
String hrp = bech32.hrp.toLowerCase();
List<int> uint5List = bech32.uint5List;
int length = hrp.length + uint5List.length + Bech32Constants.separator.length + Bech32Constants.checksumLength;

if (length > maxLength) {
throw InvalidBech32Exception('Bech32 is too long: ${hrp.length + uint5List.length + 1 + Bech32Constants.checksumLength}');
}

if (hrp.isEmpty) {
throw InvalidHrpException('HRP is empty');
}

List<int> checkSummedListUint5List = uint5List + _createChecksum(hrp, uint5List);

return hrp + Bech32Constants.separator + checkSummedListUint5List.map((int element) => Bech32Constants.charList[element]).join();
}

/// Computes a 6-byte checksum for the given [hrp] and [uint5List],
/// following Bech32 checksum rules (BIP 173).
///
/// Returns a [Uint8List] representing the 6 checksum bytes.
List<int> _createChecksum(String hrp, List<int> uint5List) {
List<int> payloadUint5List = Bech32Utils.expandHrp(hrp) + uint5List + <int>[0, 0, 0, 0, 0, 0];
int polymodValue = Bech32Utils.calculatePolymodChecksum(payloadUint5List) ^ 1;

List<int> checksumUint5List = <int>[0, 0, 0, 0, 0, 0];

for (int i = 0; i < checksumUint5List.length; i++) {
checksumUint5List[i] = (polymodValue >> (5 * (5 - i))) & 31;
}
return checksumUint5List;
}
}
21 changes: 0 additions & 21 deletions lib/src/codecs/bech32/bech32_pair.dart

This file was deleted.

31 changes: 31 additions & 0 deletions lib/src/codecs/bech32/bech32_utils.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import 'package:codec_utils/src/codecs/bech32/bech32_constants.dart';

class Bech32Utils {
/// Calculates the polymod checksum value for a list of integers [payloadUint5List].
static int calculatePolymodChecksum(List<int> payloadUint5List) {
int checksum = 1;
for (int element in payloadUint5List) {
int highBit = checksum >> 25;
checksum = (checksum & 0x1ffffff) << 5 ^ element;
for (int i = 0; i < Bech32Constants.generatorList.length; i++) {
if ((highBit >> i) & 1 == 1) {
checksum ^= Bech32Constants.generatorList[i];
}
}
}
return checksum;
}

/// Expands the human-readable part (HRP) string [hrp] into a list of integers.
///
/// This transformation is required for checksum calculation as defined
/// in BIP 173. The HRP is split into higher and lower 5-bit groups, separated by a zero delimiter.
///
/// Returns a [resultUint5List] representing the expanded HRP.
static List<int> expandHrp(String hrp) {
List<int> resultUint5List = hrp.codeUnits.map((int element) => element >> 5).toList();
resultUint5List = resultUint5List + <int>[0];
resultUint5List = resultUint5List + hrp.codeUnits.map((int element) => element & 31).toList();
return resultUint5List;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class InvalidBech32Exception implements Exception {
final String? message;

InvalidBech32Exception(this.message);

@override
String toString() => message ?? runtimeType.toString();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class InvalidChecksumException implements Exception {
final String? message;

InvalidChecksumException(this.message);

@override
String toString() => message ?? runtimeType.toString();
}
8 changes: 8 additions & 0 deletions lib/src/codecs/bech32/exceptions/invalid_hrp_exception.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class InvalidHrpException implements Exception {
final String? message;

InvalidHrpException(this.message);

@override
String toString() => message ?? runtimeType.toString();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class InvalidWitnessProgramException implements Exception {
final String? message;

InvalidWitnessProgramException(this.message);

@override
String toString() => message ?? runtimeType.toString();
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
class InvalidWitnessVersionException implements Exception {
final String? message;

InvalidWitnessVersionException(this.message);

@override
String toString() => message ?? runtimeType.toString();
}
Loading