diff --git a/CHANGELOG.md b/CHANGELOG.md index e27a4b4..79f71a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,12 @@ +## 3.1.0 + +- Ton Address Support: Implemented functionality to support Ton addresses. +- Ton Mnemonic Support: + - Added mnemonic and seed generation capabilities for Ton. + - Introduced a mnemonic validator for Ton. +- BIP-44 Support for TonCoin: Added TonCoin to the list of supported coins under the BIP-44 standard. +- The SecretWallet class name has been updated to Web3SecretStorageDefinitionV3. + ## 3.0.0 - Improved hex performance. diff --git a/README.md b/README.md index 4ce3e29..d4a0ca6 100644 --- a/README.md +++ b/README.md @@ -60,6 +60,7 @@ This comprehensive package has been shaped by the influence of several key sourc - Algorand - Ada Shelley - Ada Byron +- Ton **Binary Data:** @@ -90,6 +91,7 @@ This comprehensive package has been shaped by the influence of several key sourc - SHA256 - SHA384 - SHA512 + - XXhash These algorithms provide a wide range of cryptographic functions, including encryption, decryption, message authentication, hashing, and more, to enhance security and data integrity in applications. @@ -129,6 +131,8 @@ This comprehensive package has been shaped by the influence of several key sourc 24. **Electrum Mnemonic V1 and V2 with Key and Address Management:** Support for both Electrum Mnemonic V1 and V2, including SegWit and Standard transactions. +26. **TonMnemonic:** Support for Ton mnemonics has been added, enabling creation, validation, and seed generation. + These features make your package a comprehensive solution for encoding, cryptography, blockchain management, BIP39 mnemonic support, and diverse blockchain address encoding and decoding needs. 25. **Sign and Verification:** Implements classes for signing and verifying transaction digests. diff --git a/analysis_options.yaml b/analysis_options.yaml index 12e713a..a55c443 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -1,4 +1,28 @@ -include: package:lints/recommended.yaml +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at https://dart.dev/tools/linter-rules. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule # Additional information about this file can be found at -# https://dart.dev/guides/language/analysis-options +# https://dart.dev/tools/analysis \ No newline at end of file diff --git a/example/lib/test/address/ada_byron/byron.dart b/example/lib/test/address/ada_byron/byron.dart index aadbab7..17bf863 100644 --- a/example/lib/test/address/ada_byron/byron.dart +++ b/example/lib/test/address/ada_byron/byron.dart @@ -1,6 +1,5 @@ import 'package:blockchain_utils/bip/address/ada/ada_byron_addr.dart'; -import 'package:blockchain_utils/compare/compare.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'byron_test_vector.dart' as byron; import 'lagacy_test_vector.dart' as lagacy; @@ -13,7 +12,8 @@ void adaByronAddrTest() { .encodeKey(BytesUtils.fromHexString(i["public"]), params); assert(l == i["address"]); final decode = AdaByronAddrDecoder().decodeAddr(l); - assert(bytesEqual(decode, BytesUtils.fromHexString(i["decode"]))); + assert( + BytesUtils.bytesEqual(decode, BytesUtils.fromHexString(i["decode"]))); } for (final i in byron.testVector) { @@ -23,6 +23,7 @@ void adaByronAddrTest() { .encodeKey(BytesUtils.fromHexString(i["public"]), params); assert(l == i["address"]); final decode = AdaByronAddrDecoder().decodeAddr(l); - assert(bytesEqual(decode, BytesUtils.fromHexString(i["decode"]))); + assert( + BytesUtils.bytesEqual(decode, BytesUtils.fromHexString(i["decode"]))); } } diff --git a/example/lib/test/address/ada_shelly/ada_shelly.dart b/example/lib/test/address/ada_shelly/ada_shelly.dart index b0ed019..53c642e 100644 --- a/example/lib/test/address/ada_shelly/ada_shelly.dart +++ b/example/lib/test/address/ada_shelly/ada_shelly.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/bip/address/decoders.dart'; import 'package:blockchain_utils/bip/address/encoders.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; import 'stacking_test_vector.dart' as t; diff --git a/example/lib/test/address/algo/algo.dart b/example/lib/test/address/algo/algo.dart index 026a512..ebb52a4 100644 --- a/example/lib/test/address/algo/algo.dart +++ b/example/lib/test/address/algo/algo.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/algo_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; void algoAddressTest() { diff --git a/example/lib/test/address/aptos/aptos.dart b/example/lib/test/address/aptos/aptos.dart index 421a492..f1a9202 100644 --- a/example/lib/test/address/aptos/aptos.dart +++ b/example/lib/test/address/aptos/aptos.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/aptos_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; void aptosAddressTest() { diff --git a/example/lib/test/address/atom/atom.dart b/example/lib/test/address/atom/atom.dart index b542eb7..e2f174d 100644 --- a/example/lib/test/address/atom/atom.dart +++ b/example/lib/test/address/atom/atom.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/atom_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; void atomAddressTest() { diff --git a/example/lib/test/address/avax/avax.dart b/example/lib/test/address/avax/avax.dart index b2d1abc..980b80e 100644 --- a/example/lib/test/address/avax/avax.dart +++ b/example/lib/test/address/avax/avax.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/avax_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_p_vector.dart' as p; import 'test_x_vector.dart' as x; diff --git a/example/lib/test/address/bch_p2pkh/bch_p2pkh.dart b/example/lib/test/address/bch_p2pkh/bch_p2pkh.dart index f257ba6..815da63 100644 --- a/example/lib/test/address/bch_p2pkh/bch_p2pkh.dart +++ b/example/lib/test/address/bch_p2pkh/bch_p2pkh.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/bch_p2sh/bch_p2sh.dart b/example/lib/test/address/bch_p2sh/bch_p2sh.dart index 2e61b34..0ec51f5 100644 --- a/example/lib/test/address/bch_p2sh/bch_p2sh.dart +++ b/example/lib/test/address/bch_p2sh/bch_p2sh.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/p2sh_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/egld/egld.dart b/example/lib/test/address/egld/egld.dart index 73b15f4..8996f41 100644 --- a/example/lib/test/address/egld/egld.dart +++ b/example/lib/test/address/egld/egld.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/egld_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/eos/eos.dart b/example/lib/test/address/eos/eos.dart index 385bfb3..fcd0283 100644 --- a/example/lib/test/address/eos/eos.dart +++ b/example/lib/test/address/eos/eos.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/eos_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/ergo/ergo.dart b/example/lib/test/address/ergo/ergo.dart index cddfa9a..6785f6c 100644 --- a/example/lib/test/address/ergo/ergo.dart +++ b/example/lib/test/address/ergo/ergo.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/ergo.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/eth/eth.dart b/example/lib/test/address/eth/eth.dart index 3175af9..a4e4ab0 100644 --- a/example/lib/test/address/eth/eth.dart +++ b/example/lib/test/address/eth/eth.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/eth_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/fil/fil.dart b/example/lib/test/address/fil/fil.dart index c2ef425..b692690 100644 --- a/example/lib/test/address/fil/fil.dart +++ b/example/lib/test/address/fil/fil.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/fil_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/icx/icx.dart b/example/lib/test/address/icx/icx.dart index 297510e..3f9f2f3 100644 --- a/example/lib/test/address/icx/icx.dart +++ b/example/lib/test/address/icx/icx.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/icx_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVecotr; diff --git a/example/lib/test/address/inj/inj.dart b/example/lib/test/address/inj/inj.dart index c7e8fb7..bcf8235 100644 --- a/example/lib/test/address/inj/inj.dart +++ b/example/lib/test/address/inj/inj.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/inj_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/nano/nano.dart b/example/lib/test/address/nano/nano.dart index a4088ee..e1175aa 100644 --- a/example/lib/test/address/nano/nano.dart +++ b/example/lib/test/address/nano/nano.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/nano_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/near/near.dart b/example/lib/test/address/near/near.dart index 342b0af..9657772 100644 --- a/example/lib/test/address/near/near.dart +++ b/example/lib/test/address/near/near.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/near_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/neo/neo.dart b/example/lib/test/address/neo/neo.dart index f0bbc8c..75fa551 100644 --- a/example/lib/test/address/neo/neo.dart +++ b/example/lib/test/address/neo/neo.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/neo_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVecotr; diff --git a/example/lib/test/address/okex/okex.dart b/example/lib/test/address/okex/okex.dart index 1c4c17a..6ca8a39 100644 --- a/example/lib/test/address/okex/okex.dart +++ b/example/lib/test/address/okex/okex.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/okex_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/one/one.dart b/example/lib/test/address/one/one.dart index 1321c34..1a2d415 100644 --- a/example/lib/test/address/one/one.dart +++ b/example/lib/test/address/one/one.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/one_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/p2pkh/p2pkh.dart b/example/lib/test/address/p2pkh/p2pkh.dart index d3f01b0..a3d20ca 100644 --- a/example/lib/test/address/p2pkh/p2pkh.dart +++ b/example/lib/test/address/p2pkh/p2pkh.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'comperesed_test_vector.dart' show compresedTestVector; import 'uncompresed_test_vector.dart' show uncompressedTestVector; diff --git a/example/lib/test/address/p2sh/p2sh.dart b/example/lib/test/address/p2sh/p2sh.dart index e8cbb2d..5c43922 100644 --- a/example/lib/test/address/p2sh/p2sh.dart +++ b/example/lib/test/address/p2sh/p2sh.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/p2sh_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/p2tr/p2tr.dart b/example/lib/test/address/p2tr/p2tr.dart index 7299943..a180bdb 100644 --- a/example/lib/test/address/p2tr/p2tr.dart +++ b/example/lib/test/address/p2tr/p2tr.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/p2tr_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/p2wpkh/p2wpkh.dart b/example/lib/test/address/p2wpkh/p2wpkh.dart index be65797..fa93f81 100644 --- a/example/lib/test/address/p2wpkh/p2wpkh.dart +++ b/example/lib/test/address/p2wpkh/p2wpkh.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/p2wpkh_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/sol/sol.dart b/example/lib/test/address/sol/sol.dart index 4154d5f..aeed0ba 100644 --- a/example/lib/test/address/sol/sol.dart +++ b/example/lib/test/address/sol/sol.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/sol_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/substrate/substrate.dart b/example/lib/test/address/substrate/substrate.dart index bcb8350..dddb035 100644 --- a/example/lib/test/address/substrate/substrate.dart +++ b/example/lib/test/address/substrate/substrate.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/substrate_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/trx/trx.dart b/example/lib/test/address/trx/trx.dart index 0dbc759..763ffae 100644 --- a/example/lib/test/address/trx/trx.dart +++ b/example/lib/test/address/trx/trx.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/trx_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test.dart' show testVecotr; diff --git a/example/lib/test/address/xlm/xml.dart b/example/lib/test/address/xlm/xml.dart index ac10107..30b4302 100644 --- a/example/lib/test/address/xlm/xml.dart +++ b/example/lib/test/address/xlm/xml.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/xlm_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/xmr/xmr.dart b/example/lib/test/address/xmr/xmr.dart index 43b0298..88884b9 100644 --- a/example/lib/test/address/xmr/xmr.dart +++ b/example/lib/test/address/xmr/xmr.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/xmr_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; import 'test_vector_integrate.dart' show integrateTestVecotr; diff --git a/example/lib/test/address/xrp/xrp.dart b/example/lib/test/address/xrp/xrp.dart index 0112226..eb600e2 100644 --- a/example/lib/test/address/xrp/xrp.dart +++ b/example/lib/test/address/xrp/xrp.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/xrp_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/xtz/xtz.dart b/example/lib/test/address/xtz/xtz.dart index 395062b..b41c086 100644 --- a/example/lib/test/address/xtz/xtz.dart +++ b/example/lib/test/address/xtz/xtz.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/xtz_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/address/zil/zil.dart b/example/lib/test/address/zil/zil.dart index 6154cea..8350222 100644 --- a/example/lib/test/address/zil/zil.dart +++ b/example/lib/test/address/zil/zil.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/zil_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; diff --git a/example/lib/test/algorand/mnemonic.dart b/example/lib/test/algorand/mnemonic.dart index 9cf8ca5..f820c0e 100644 --- a/example/lib/test/algorand/mnemonic.dart +++ b/example/lib/test/algorand/mnemonic.dart @@ -5,7 +5,7 @@ import 'package:blockchain_utils/bip/algorand/mnemonic/algorand_seed_generator.d import 'package:blockchain_utils/bip/bip/bip44/bip44.dart'; import 'package:blockchain_utils/bip/bip/conf/bip44/bip44_coins.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; void algorandMnemonicAndAddressTest() { diff --git a/example/lib/test/base58/base58.dart b/example/lib/test/base58/base58.dart index 921cb92..867d9b4 100644 --- a/example/lib/test/base58/base58.dart +++ b/example/lib/test/base58/base58.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/base58/base58.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; final List> testVectBtc = [ {"raw": "", "encode": "", "check_encode": "3QJmnh"}, diff --git a/example/lib/test/base58/base58_xmr.dart b/example/lib/test/base58/base58_xmr.dart index 5c3b9e9..db9a1de 100644 --- a/example/lib/test/base58/base58_xmr.dart +++ b/example/lib/test/base58/base58_xmr.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/base58/base58_xmr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; var _testVect = [ { diff --git a/example/lib/test/bech32/bch_bech32.dart b/example/lib/test/bech32/bch_bech32.dart index a6abe9c..73595f2 100644 --- a/example/lib/test/bech32/bch_bech32.dart +++ b/example/lib/test/bech32/bch_bech32.dart @@ -1,8 +1,7 @@ import 'package:blockchain_utils/bech32/bch_bech32.dart'; import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; -import 'package:blockchain_utils/compare/compare.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; final List> _testVect = [ { @@ -36,7 +35,7 @@ void bchBech32Test() { final hrp = i["encode"]!.substring(0, i["encode"]!.indexOf(":")); final decode = BchBech32Decoder.decode(hrp, i["encode"]!); assert(decode.item2.toHex() == i["raw"]); - assert(bytesEqual( + assert(BytesUtils.bytesEqual( decode.item1, CoinsConf.bitcoinCashMainNet.params.p2pkhStdNetVer)); } for (final i in _testVect) { diff --git a/example/lib/test/bech32/bech32.dart b/example/lib/test/bech32/bech32.dart index 8c368fa..9f3db8d 100644 --- a/example/lib/test/bech32/bech32.dart +++ b/example/lib/test/bech32/bech32.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bech32/bech32.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; // import 'package:test/test.dart'; final List> _testVect = [ diff --git a/example/lib/test/bech32/segwit_bech32.dart b/example/lib/test/bech32/segwit_bech32.dart index 09e85cd..14febde 100644 --- a/example/lib/test/bech32/segwit_bech32.dart +++ b/example/lib/test/bech32/segwit_bech32.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bech32/segwit_bech32.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; final List> _testVectors = [ { diff --git a/example/lib/test/bip/bip32/ed25519/ed25519.dart b/example/lib/test/bip/bip32/ed25519/ed25519.dart index dc5768c..eed23e6 100644 --- a/example/lib/test/bip/bip32/ed25519/ed25519.dart +++ b/example/lib/test/bip/bip32/ed25519/ed25519.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip32/slip10/bip32_slip10_ed25519.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/bip/bip32/ed25519_blake2b/ed25519_blake2b.dart b/example/lib/test/bip/bip32/ed25519_blake2b/ed25519_blake2b.dart index 04fb5df..23be35f 100644 --- a/example/lib/test/bip/bip32/ed25519_blake2b/ed25519_blake2b.dart +++ b/example/lib/test/bip/bip32/ed25519_blake2b/ed25519_blake2b.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip32/slip10/bip32_slip10_ed25519_blake2b.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/bip/bip32/ed25519_khalow/ed25519_khalow.dart b/example/lib/test/bip/bip32/ed25519_khalow/ed25519_khalow.dart index 2987105..3468c93 100644 --- a/example/lib/test/bip/bip32/ed25519_khalow/ed25519_khalow.dart +++ b/example/lib/test/bip/bip32/ed25519_khalow/ed25519_khalow.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip32/khalow/bip32_kholaw_ed25519.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/bip/bip32/nist256p1/nist256p1.dart b/example/lib/test/bip/bip32/nist256p1/nist256p1.dart index 2c6da60..a12e455 100644 --- a/example/lib/test/bip/bip32/nist256p1/nist256p1.dart +++ b/example/lib/test/bip/bip32/nist256p1/nist256p1.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip32/slip10/bip32_slip10_nist256p1.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/bip/bip32/secp256k1/secp256k1.dart b/example/lib/test/bip/bip32/secp256k1/secp256k1.dart index b0c78d9..c51ed44 100644 --- a/example/lib/test/bip/bip32/secp256k1/secp256k1.dart +++ b/example/lib/test/bip/bip32/secp256k1/secp256k1.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip32/slip10/bip32_slip10_secp256k1.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/bip/bip38/bip38_addr.dart b/example/lib/test/bip/bip38/bip38_addr.dart index 3e1fab8..c5af96c 100644 --- a/example/lib/test/bip/bip38/bip38_addr.dart +++ b/example/lib/test/bip/bip38/bip38_addr.dart @@ -3,7 +3,7 @@ import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:blockchain_utils/bip/bip/bip38/bip38_addr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; List> _testVector = [ { diff --git a/example/lib/test/bip/bip38/bip38_no_ec.dart b/example/lib/test/bip/bip38/bip38_no_ec.dart index c56dbe9..dabc2fa 100644 --- a/example/lib/test/bip/bip38/bip38_no_ec.dart +++ b/example/lib/test/bip/bip38/bip38_no_ec.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:blockchain_utils/bip/bip/bip38/bip38.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:flutter/foundation.dart'; List> _testVector = [ diff --git a/example/lib/test/bip/bip39/bip39.dart b/example/lib/test/bip/bip39/bip39.dart index 438ebc5..d7c6948 100644 --- a/example/lib/test/bip/bip39/bip39.dart +++ b/example/lib/test/bip/bip39/bip39.dart @@ -3,7 +3,7 @@ import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic_decoder.dart'; import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic_generator.dart'; import 'package:blockchain_utils/bip/bip/bip39/bip39_seed_generator.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart' show testVector; const String _passphrase = "MRT"; diff --git a/example/lib/test/bip/bip44/bip44.dart b/example/lib/test/bip/bip44/bip44.dart index a2d609d..4df7ccd 100644 --- a/example/lib/test/bip/bip44/bip44.dart +++ b/example/lib/test/bip/bip44/bip44.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/bip/bip44/bip44.dart'; import 'package:blockchain_utils/bip/bip/conf/bip44/bip44_coins.dart'; import 'package:blockchain_utils/bip/monero/monero_base.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/bip/bip49/bip49.dart b/example/lib/test/bip/bip49/bip49.dart index 809736e..129f9a0 100644 --- a/example/lib/test/bip/bip49/bip49.dart +++ b/example/lib/test/bip/bip49/bip49.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/bip/bip/bip49/bip49.dart'; import 'package:blockchain_utils/bip/bip/conf/bip49/bip49_coins.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; void bip49Test() { diff --git a/example/lib/test/bip/bip84/bip84.dart b/example/lib/test/bip/bip84/bip84.dart index 896a259..ef43887 100644 --- a/example/lib/test/bip/bip84/bip84.dart +++ b/example/lib/test/bip/bip84/bip84.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/bip/bip/bip84/bip84.dart'; import 'package:blockchain_utils/bip/bip/conf/bip84/bip84_coins.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; void bip84Test() { diff --git a/example/lib/test/bip/bip86/bip86.dart b/example/lib/test/bip/bip86/bip86.dart index e565fb9..999f4af 100644 --- a/example/lib/test/bip/bip86/bip86.dart +++ b/example/lib/test/bip/bip86/bip86.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/bip/bip/bip86/bip86.dart'; import 'package:blockchain_utils/bip/bip/conf/bip86/bip86_coins.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; void bip86Test() { diff --git a/example/lib/test/cardano/bip32/icarus.dart b/example/lib/test/cardano/bip32/icarus.dart index 956bbec..00e3c87 100644 --- a/example/lib/test/cardano/bip32/icarus.dart +++ b/example/lib/test/cardano/bip32/icarus.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/cardano/bip32/cardano_icarus_bip32.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'icarus_test_vector.dart'; diff --git a/example/lib/test/cardano/bip32/legacy.dart b/example/lib/test/cardano/bip32/legacy.dart index 0ad212a..bd0e880 100644 --- a/example/lib/test/cardano/bip32/legacy.dart +++ b/example/lib/test/cardano/bip32/legacy.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/cardano/bip32/cardano_byron_legacy_bip32.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/cardano/byron/byron_lagacy.dart b/example/lib/test/cardano/byron/byron_lagacy.dart index 0c9cd05..844be2b 100644 --- a/example/lib/test/cardano/byron/byron_lagacy.dart +++ b/example/lib/test/cardano/byron/byron_lagacy.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/cardano/byron/cardano_byron_legacy.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:flutter/foundation.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/cardano/cip1852/cip1852.dart b/example/lib/test/cardano/cip1852/cip1852.dart index f8e8c6e..7c8e971 100644 --- a/example/lib/test/cardano/cip1852/cip1852.dart +++ b/example/lib/test/cardano/cip1852/cip1852.dart @@ -3,7 +3,7 @@ import 'package:blockchain_utils/bip/cardano/cip1852/cip1852.dart'; import 'package:blockchain_utils/bip/cardano/cip1852/conf/cip1852_coins.dart'; import 'package:blockchain_utils/bip/cardano/shelley/cardano_shelley.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; void cip1852Test() { diff --git a/example/lib/test/cbor.dart b/example/lib/test/cbor.dart index df2c4f8..4b9069c 100644 --- a/example/lib/test/cbor.dart +++ b/example/lib/test/cbor.dart @@ -1,3 +1,4 @@ +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/core/cbor.dart'; import 'package:blockchain_utils/cbor/types/bigint.dart'; import 'package:blockchain_utils/cbor/types/bytes.dart'; @@ -9,9 +10,7 @@ import 'package:blockchain_utils/cbor/types/int64.dart'; import 'package:blockchain_utils/cbor/types/list.dart'; import 'package:blockchain_utils/cbor/types/map.dart'; import 'package:blockchain_utils/cbor/types/string.dart'; -import 'package:blockchain_utils/compare/compare.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; List _testList1 = [ 0, @@ -46,7 +45,7 @@ void _decodeStringIndefinite() { final dec = CborObject.fromCbor(cb.encode()); assert(dec.runtimeType == CborIndefiniteStringValue); dec as CborIndefiniteStringValue; - assert(iterableIsEqual(dec.value, cb.value)); + assert(CompareUtils.iterableIsEqual(dec.value, cb.value)); } void _decodeMap() { @@ -58,10 +57,10 @@ void _decodeMap() { dec as CborMapValue; final keys = cb.value.keys.map((e) => e).toList(); final keysDec = dec.value.keys.map((e) => e.value).toList(); - assert(iterableIsEqual(keys, keysDec)); + assert(CompareUtils.iterableIsEqual(keys, keysDec)); final values = cb.value.values.map((e) => e).toList(); final valuesDec = dec.value.values.map((e) => e.value).toList(); - assert(iterableIsEqual(values, valuesDec)); + assert(CompareUtils.iterableIsEqual(values, valuesDec)); } void _decodeMapDynamic() { @@ -76,10 +75,10 @@ void _decodeMapDynamic() { dec as CborMapValue; final keys = cb.value.keys.map((e) => e).toList(); final keysDec = dec.value.keys.map((e) => e.value).toList(); - assert(iterableIsEqual(keys, keysDec)); + assert(CompareUtils.iterableIsEqual(keys, keysDec)); final values = cb.value.values.map((e) => e).toList(); final valuesDec = dec.value.values.map((e) => e.value).toList(); - assert(iterableIsEqual(values, valuesDec)); + assert(CompareUtils.iterableIsEqual(values, valuesDec)); } void _decodeList() { @@ -96,7 +95,7 @@ void _decodeList() { dec as CborListValue; final valuesDec = dec.value.map((e) => e.value).toList(); - assert(iterableIsEqual(cb.value, valuesDec)); + assert(CompareUtils.iterableIsEqual(cb.value, valuesDec)); } void _decodeDateTime() { diff --git a/example/lib/test/crypto/aes/aes_ctr.dart b/example/lib/test/crypto/aes/aes_ctr.dart index b4d69e9..66a2ea5 100644 --- a/example/lib/test/crypto/aes/aes_ctr.dart +++ b/example/lib/test/crypto/aes/aes_ctr.dart @@ -3,7 +3,7 @@ import 'dart:typed_data'; import 'package:blockchain_utils/crypto/crypto/aes/aes.dart'; import 'package:blockchain_utils/crypto/crypto/ctr/ctr.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/crypto/blake2b/blake2b.dart b/example/lib/test/crypto/blake2b/blake2b.dart index f1e52cc..1e6f664 100644 --- a/example/lib/test/crypto/blake2b/blake2b.dart +++ b/example/lib/test/crypto/blake2b/blake2b.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/crypto/chacha20_poly1305/chacha20_poly1305.dart b/example/lib/test/crypto/chacha20_poly1305/chacha20_poly1305.dart index ea66dec..80cd350 100644 --- a/example/lib/test/crypto/chacha20_poly1305/chacha20_poly1305.dart +++ b/example/lib/test/crypto/chacha20_poly1305/chacha20_poly1305.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/chacha20poly1305/chacha20poly1305.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/crypto/crc32/crc32.dart b/example/lib/test/crypto/crc32/crc32.dart index 85b5ab6..669ee6e 100644 --- a/example/lib/test/crypto/crc32/crc32.dart +++ b/example/lib/test/crypto/crc32/crc32.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/crc32/crc32.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/crypto/hmac/hmac.dart b/example/lib/test/crypto/hmac/hmac.dart index bef1023..9959eba 100644 --- a/example/lib/test/crypto/hmac/hmac.dart +++ b/example/lib/test/crypto/hmac/hmac.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:blockchain_utils/crypto/crypto/hmac/hmac.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/crypto/keccack/keccack.dart b/example/lib/test/crypto/keccack/keccack.dart index 48baab4..1a31d3b 100644 --- a/example/lib/test/crypto/keccack/keccack.dart +++ b/example/lib/test/crypto/keccack/keccack.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/crypto/md4/md4.dart b/example/lib/test/crypto/md4/md4.dart index a1d43c6..77365e6 100644 --- a/example/lib/test/crypto/md4/md4.dart +++ b/example/lib/test/crypto/md4/md4.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/crypto/md5/md5.dart b/example/lib/test/crypto/md5/md5.dart index e19e147..dcc1044 100644 --- a/example/lib/test/crypto/md5/md5.dart +++ b/example/lib/test/crypto/md5/md5.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/crypto/pbkdf2/pbkdf2.dart b/example/lib/test/crypto/pbkdf2/pbkdf2.dart index 0590bdd..21d81af 100644 --- a/example/lib/test/crypto/pbkdf2/pbkdf2.dart +++ b/example/lib/test/crypto/pbkdf2/pbkdf2.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:blockchain_utils/crypto/crypto/hmac/hmac.dart'; import 'package:blockchain_utils/crypto/crypto/pbkdf2/pbkdf2.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/crypto/ripemd/ripemd.dart b/example/lib/test/crypto/ripemd/ripemd.dart index 440729c..57508a5 100644 --- a/example/lib/test/crypto/ripemd/ripemd.dart +++ b/example/lib/test/crypto/ripemd/ripemd.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/crypto/scrypt/scrypt.dart b/example/lib/test/crypto/scrypt/scrypt.dart index b5daabe..4e9ed7f 100644 --- a/example/lib/test/crypto/scrypt/scrypt.dart +++ b/example/lib/test/crypto/scrypt/scrypt.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/scrypt/scrypt.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/crypto/sha1/sha1.dart b/example/lib/test/crypto/sha1/sha1.dart index 7da9e10..2de63cc 100644 --- a/example/lib/test/crypto/sha1/sha1.dart +++ b/example/lib/test/crypto/sha1/sha1.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/crypto/sha256/sha256.dart b/example/lib/test/crypto/sha256/sha256.dart index b40d35e..7527fc1 100644 --- a/example/lib/test/crypto/sha256/sha256.dart +++ b/example/lib/test/crypto/sha256/sha256.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/crypto/sha3/sha3.dart b/example/lib/test/crypto/sha3/sha3.dart index 14a4244..bc69819 100644 --- a/example/lib/test/crypto/sha3/sha3.dart +++ b/example/lib/test/crypto/sha3/sha3.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:example/test/quick_hex.dart'; diff --git a/example/lib/test/crypto/sha512/sha512.dart b/example/lib/test/crypto/sha512/sha512.dart index 2f10c9a..1ffdb55 100644 --- a/example/lib/test/crypto/sha512/sha512.dart +++ b/example/lib/test/crypto/sha512/sha512.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/crypto/sha512_256/sha512_256.dart b/example/lib/test/crypto/sha512_256/sha512_256.dart index aeabb2a..cdfe8b3 100644 --- a/example/lib/test/crypto/sha512_256/sha512_256.dart +++ b/example/lib/test/crypto/sha512_256/sha512_256.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/crypto/shake/shake.dart b/example/lib/test/crypto/shake/shake.dart index b69c167..2dea04b 100644 --- a/example/lib/test/crypto/shake/shake.dart +++ b/example/lib/test/crypto/shake/shake.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector_256.dart'; import 'test_vector_128.dart'; diff --git a/example/lib/test/crypto/x_modem_crc/x_modem_crc.dart b/example/lib/test/crypto/x_modem_crc/x_modem_crc.dart index 672e744..6b584d9 100644 --- a/example/lib/test/crypto/x_modem_crc/x_modem_crc.dart +++ b/example/lib/test/crypto/x_modem_crc/x_modem_crc.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/x_modem_crc/x_modem_crc.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/ecdsa/ed.dart b/example/lib/test/ecdsa/ed.dart index 9e60ca6..1b39cae 100644 --- a/example/lib/test/ecdsa/ed.dart +++ b/example/lib/test/ecdsa/ed.dart @@ -5,7 +5,7 @@ import 'package:blockchain_utils/crypto/crypto/cdsa/eddsa/privatekey.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/edwards.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; void _testDouble() { final a = Curves.generatorED25519; diff --git a/example/lib/test/ecdsa/projective.dart b/example/lib/test/ecdsa/projective.dart index 246a332..43a5aba 100644 --- a/example/lib/test/ecdsa/projective.dart +++ b/example/lib/test/ecdsa/projective.dart @@ -4,8 +4,7 @@ import 'package:blockchain_utils/crypto/crypto/cdsa/ecdsa/private_key.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/ec_projective_point.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/rfc6979/rfc6979.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; void _testEqualWithAffinePoint() { final point1 = ProjectiveECCPoint.fromAffine(Curves.generatorSecp256k1); diff --git a/example/lib/test/elctrum/mnemonic/mnemonic.dart b/example/lib/test/elctrum/mnemonic/mnemonic.dart index 0d29966..ed85fa0 100644 --- a/example/lib/test/elctrum/mnemonic/mnemonic.dart +++ b/example/lib/test/elctrum/mnemonic/mnemonic.dart @@ -7,9 +7,8 @@ import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic.d import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_decoder.dart'; import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_generator.dart'; import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_seed_generator.dart'; -import 'package:blockchain_utils/compare/compare.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector_v1.dart'; import 'test_vector_v2.dart'; @@ -28,9 +27,9 @@ void electrumMnemonicTest() { final decode = ElectrumV2MnemonicDecoder(mnemonicType: type, language: lang) .decode(mn.toStr()); - assert(bytesEqual(decode, entropy)); + assert(BytesUtils.bytesEqual(decode, entropy)); final seed = ElectrumV2SeedGenerator(mn, lang).generate("MRT"); - assert(bytesEqual(seed, BytesUtils.fromHexString(i["seed"]))); + assert(BytesUtils.bytesEqual(seed, BytesUtils.fromHexString(i["seed"]))); if (i["address"] != null) { String addr; if (type.name.startsWith("segwit")) { @@ -48,7 +47,7 @@ void electrumMnemonicTest() { final seed = ElectrumV1SeedGenerator(toMnemonic.toStr()).generate(); assert(seed.toHex() == i["seed"]); final en = ElectrumV1MnemonicDecoder().decode(toMnemonic.toStr()); - assert(bytesEqual(en, entropy)); + assert(BytesUtils.bytesEqual(en, entropy)); final addr = ElectrumV1.fromSeed(seed).getAddress(0, 0); assert(addr == i["address"]); } diff --git a/example/lib/test/elctrum/v1/v1.dart b/example/lib/test/elctrum/v1/v1.dart index 3013e42..94df1a9 100644 --- a/example/lib/test/elctrum/v1/v1.dart +++ b/example/lib/test/elctrum/v1/v1.dart @@ -3,7 +3,7 @@ import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; import 'package:blockchain_utils/bip/electrum/electrum_v1.dart'; import 'package:blockchain_utils/bip/wif/wif.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vectors.dart'; diff --git a/example/lib/test/elctrum/v2/v2.dart b/example/lib/test/elctrum/v2/v2.dart index fe14700..1d374a7 100644 --- a/example/lib/test/elctrum/v2/v2.dart +++ b/example/lib/test/elctrum/v2/v2.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; import 'package:blockchain_utils/bip/electrum/electrum_v2.dart'; import 'package:blockchain_utils/bip/wif/wif.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; import 'segwit_test_vector.dart'; diff --git a/example/lib/test/monero/mnemonic/monero_mnemonic.dart b/example/lib/test/monero/mnemonic/monero_mnemonic.dart index 4108ecd..e2439d1 100644 --- a/example/lib/test/monero/mnemonic/monero_mnemonic.dart +++ b/example/lib/test/monero/mnemonic/monero_mnemonic.dart @@ -2,9 +2,7 @@ import 'package:blockchain_utils/bip/monero/mnemonic/monero_mnemonic.dart'; import 'package:blockchain_utils/bip/monero/mnemonic/monero_mnemonic_decoder.dart'; import 'package:blockchain_utils/bip/monero/mnemonic/monero_mnemonic_generator.dart'; import 'package:blockchain_utils/bip/monero/mnemonic/monero_seed_generator.dart'; -import 'package:blockchain_utils/compare/compare.dart'; - -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import "test_vector.dart"; void moneroMnemonucTest() { @@ -18,8 +16,8 @@ void moneroMnemonucTest() { final mnNc = MoneroMnemonicGenerator(lang).fromEntropyNoChecksum(entropy); assert(mnNc.toStr() == i["no_checksum"]); final entropyResult = MoneroMnemonicDecoder(lang).decode(mn.toStr()); - assert(bytesEqual(entropyResult, entropy)); + assert(BytesUtils.bytesEqual(entropyResult, entropy)); final seed = MoneroSeedGenerator(mn).generate(); - assert(bytesEqual(seed, entropy)); + assert(BytesUtils.bytesEqual(seed, entropy)); } } diff --git a/example/lib/test/monero/monero.dart b/example/lib/test/monero/monero.dart index 8146e75..0e5adcf 100644 --- a/example/lib/test/monero/monero.dart +++ b/example/lib/test/monero/monero.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/bip/monero/conf/monero_coins.dart'; import 'package:blockchain_utils/bip/monero/monero_base.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:example/test/quick_hex.dart'; import 'test_vector.dart'; diff --git a/example/lib/test/quick_hex.dart b/example/lib/test/quick_hex.dart index affa46f..c6cd963 100644 --- a/example/lib/test/quick_hex.dart +++ b/example/lib/test/quick_hex.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; extension HEX on List { String toHex() => BytesUtils.toHexString(this); diff --git a/example/lib/test/schnorrkel/derive.dart b/example/lib/test/schnorrkel/derive.dart index 2a5fc04..c37c71c 100644 --- a/example/lib/test/schnorrkel/derive.dart +++ b/example/lib/test/schnorrkel/derive.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/schnorrkel/keys/keys.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'derive_test_vector.dart'; import 'derive_public_vector.dart'; diff --git a/example/lib/test/schnorrkel/schnorrkel_key.dart b/example/lib/test/schnorrkel/schnorrkel_key.dart index 5cc9780..446f6e8 100644 --- a/example/lib/test/schnorrkel/schnorrkel_key.dart +++ b/example/lib/test/schnorrkel/schnorrkel_key.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/crypto/crypto/schnorrkel/keys/keys.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'key_test_vector.dart'; diff --git a/example/lib/test/schnorrkel/sign.dart b/example/lib/test/schnorrkel/sign.dart index 283b654..7a2fdd0 100644 --- a/example/lib/test/schnorrkel/sign.dart +++ b/example/lib/test/schnorrkel/sign.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/crypto/crypto/schnorrkel/keys/keys.dart'; import 'package:blockchain_utils/crypto/crypto/schnorrkel/merlin/transcript.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'sign_test_vector.dart'; diff --git a/example/lib/test/schnorrkel/vrf.dart b/example/lib/test/schnorrkel/vrf.dart index 35503b6..c9b6261 100644 --- a/example/lib/test/schnorrkel/vrf.dart +++ b/example/lib/test/schnorrkel/vrf.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/crypto/crypto/schnorrkel/keys/keys.dart'; import 'package:blockchain_utils/crypto/crypto/schnorrkel/merlin/transcript.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'vrf_test_vector.dart' as vrf_test; void vrfSignTest() { diff --git a/example/lib/test/secure_storage.dart b/example/lib/test/secure_storage.dart index 81786b2..1e5b266 100644 --- a/example/lib/test/secure_storage.dart +++ b/example/lib/test/secure_storage.dart @@ -9,17 +9,18 @@ void testSecureStorage() { final message = QuickCrypto.generateRandom(64); // Encode the mnemonic with the password and additional parameters - final secureStorage = - SecretWallet.encode(message, password, p: 1, scryptN: 8192); + final secureStorage = Web3SecretStorageDefinationV3.encode( + message, password, + p: 1, scryptN: 8192); // Decode the encoded secure storage using the password - final decodeWallet = SecretWallet.decode( + final decodeWallet = Web3SecretStorageDefinationV3.decode( secureStorage.encrypt(encoding: SecretWalletEncoding.base64), password, encoding: SecretWalletEncoding.base64); // Verify that the credentials in the secure storage match the decoded credentials - assert(bytesEqual(secureStorage.data, decodeWallet.data), true); - assert(bytesEqual(decodeWallet.data, message), true); + assert(BytesUtils.bytesEqual(secureStorage.data, decodeWallet.data), true); + assert(BytesUtils.bytesEqual(decodeWallet.data, message), true); } // Repeat the following test 100 times for (int i = 0; i < 5; i++) { @@ -28,16 +29,17 @@ void testSecureStorage() { final message = QuickCrypto.generateRandom(64); // Encode the mnemonic with the password and additional parameters - final secureStorage = - SecretWallet.encode(message, password, p: 1, scryptN: 8192); + final secureStorage = Web3SecretStorageDefinationV3.encode( + message, password, + p: 1, scryptN: 8192); // Decode the encoded secure storage using the password - final decodeWallet = SecretWallet.decode( + final decodeWallet = Web3SecretStorageDefinationV3.decode( secureStorage.encrypt(encoding: SecretWalletEncoding.json), password, encoding: SecretWalletEncoding.json); // Verify that the credentials in the secure storage match the decoded credentials - assert(bytesEqual(secureStorage.data, decodeWallet.data), true); - assert(bytesEqual(decodeWallet.data, message), true); + assert(BytesUtils.bytesEqual(secureStorage.data, decodeWallet.data), true); + assert(BytesUtils.bytesEqual(decodeWallet.data, message), true); } } diff --git a/example/lib/test/ss58/ss58.dart b/example/lib/test/ss58/ss58.dart index 589a05a..1901afc 100644 --- a/example/lib/test/ss58/ss58.dart +++ b/example/lib/test/ss58/ss58.dart @@ -1,7 +1,7 @@ // ignore_for_file: depend_on_referenced_packages import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/ss58/ss58.dart'; final List> _testVector = [ diff --git a/example/lib/test/substrate/substrate.dart b/example/lib/test/substrate/substrate.dart index 62fb876..93617ae 100644 --- a/example/lib/test/substrate/substrate.dart +++ b/example/lib/test/substrate/substrate.dart @@ -1,8 +1,7 @@ import 'package:blockchain_utils/bip/ecc/bip_ecc.dart'; import 'package:blockchain_utils/bip/substrate/substrate.dart'; -import 'package:blockchain_utils/compare/compare.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; @@ -32,7 +31,7 @@ void substrateDeriveTest() { final secret = (w.priveKey.privKey as Sr25519PrivateKey).secretKey; final testPrive = BytesUtils.fromHexString(childInfo["private_key"]).sublist(0, 32); - assert(bytesEqual(testPrive, secret.key())); + assert(BytesUtils.bytesEqual(testPrive, secret.key())); } } } @@ -62,7 +61,7 @@ void substrateDeriveTest() { final secret = (w.priveKey.privKey as Sr25519PrivateKey).secretKey; final testPrive = BytesUtils.fromHexString(childInfo["private_key"]).sublist(0, 32); - assert(bytesEqual(testPrive, secret.key())); + assert(BytesUtils.bytesEqual(testPrive, secret.key())); } } } diff --git a/example/lib/test/wif/wif.dart b/example/lib/test/wif/wif.dart index 29a0718..79c1952 100644 --- a/example/lib/test/wif/wif.dart +++ b/example/lib/test/wif/wif.dart @@ -4,7 +4,7 @@ import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; import 'package:blockchain_utils/bip/wif/wif.dart'; import 'package:example/test/quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; final List> _testVector = [ { diff --git a/example/pubspec.lock b/example/pubspec.lock index e1b644e..a09f357 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -39,7 +39,7 @@ packages: path: ".." relative: true source: path - version: "2.1.2" + version: "3.0.0" boolean_selector: dependency: transitive description: @@ -201,10 +201,10 @@ packages: dependency: transitive description: name: meta - sha256: d584fa6707a52763a52446f02cc621b077888fb63b93bbcb1143a7be5a0c0c04 + sha256: "7687075e408b093f36e6bbf6c91878cc0d4cd10f409506f7bc996f68220b9136" url: "https://pub.dev" source: hosted - version: "1.11.0" + version: "1.12.0" mime: dependency: transitive description: diff --git a/lib/base32/base32.dart b/lib/base32/base32.dart index 19434d2..508e505 100644 --- a/lib/base32/base32.dart +++ b/lib/base32/base32.dart @@ -52,7 +52,7 @@ OF THE POSSIBILITY OF SUCH DAMAGE. */ -import 'package:blockchain_utils/string/string.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; /// Constants and data structures used for Base32 encoding and decoding. @@ -201,7 +201,7 @@ class Base32Decoder { return List.from(decodedBytes); } catch (ex) { /// Handle exceptions by throwing an error for invalid Base32 strings. - throw ArgumentException('Invalid Base32 string'); + throw const ArgumentException('Invalid Base32 string'); } } } diff --git a/lib/base58/base58_base.dart b/lib/base58/base58_base.dart index f68181c..83e3e2b 100644 --- a/lib/base58/base58_base.dart +++ b/lib/base58/base58_base.dart @@ -1,5 +1,7 @@ import 'package:blockchain_utils/base58/base58_ex.dart'; -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/crypto/quick_crypto.dart'; +import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/utils/utils.dart'; enum Base58Alphabets { bitcoin, @@ -159,7 +161,7 @@ class Base58Decoder { decodedBytes.sublist(decodedBytes.length - Base58Const.checksumByteLen); final computedChecksum = Base58Utils.computeChecksum(dataBytes); - if (!bytesEqual(checksumBytes, computedChecksum)) { + if (!BytesUtils.bytesEqual(checksumBytes, computedChecksum)) { throw Base58ChecksumError( "Invalid checksum (expected ${BytesUtils.toHexString(computedChecksum)}, got ${BytesUtils.toHexString(checksumBytes)})", ); diff --git a/lib/base58/base58_ex.dart b/lib/base58/base58_ex.dart index ac0cfa5..dfe6603 100644 --- a/lib/base58/base58_ex.dart +++ b/lib/base58/base58_ex.dart @@ -5,8 +5,11 @@ class Base58ChecksumError implements BlockchainUtilsException { @override final String message; + @override + final Map? details; + /// Constructor for creating a Base58ChecksumError with an optional error message. - const Base58ChecksumError(this.message); + const Base58ChecksumError(this.message, {this.details}); @override String toString() { diff --git a/lib/bech32/bch_bech32.dart b/lib/bech32/bch_bech32.dart index f5295b8..dc1213a 100644 --- a/lib/bech32/bch_bech32.dart +++ b/lib/bech32/bch_bech32.dart @@ -54,8 +54,7 @@ import 'dart:typed_data'; -import 'package:blockchain_utils/numbers/int_utils.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'bech32_utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; diff --git a/lib/bech32/bech32_base.dart b/lib/bech32/bech32_base.dart index aaede91..4eec23a 100644 --- a/lib/bech32/bech32_base.dart +++ b/lib/bech32/bech32_base.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'bech32_utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; diff --git a/lib/bech32/bech32_ex.dart b/lib/bech32/bech32_ex.dart index 6c2b33f..71fd1d7 100644 --- a/lib/bech32/bech32_ex.dart +++ b/lib/bech32/bech32_ex.dart @@ -5,12 +5,14 @@ class Bech32ChecksumError implements BlockchainUtilsException { /// The error message associated with this checksum error. @override final String message; + @override + final Map? details; /// Creates a new instance of [Bech32ChecksumError]. /// /// Parameters: /// - message: An optional error message describing the checksum error. - const Bech32ChecksumError(this.message); + const Bech32ChecksumError(this.message, {this.details}); @override String toString() { diff --git a/lib/bech32/bech32_utils.dart b/lib/bech32/bech32_utils.dart index e22e05f..a7df342 100644 --- a/lib/bech32/bech32_utils.dart +++ b/lib/bech32/bech32_utils.dart @@ -54,7 +54,7 @@ import 'package:blockchain_utils/bech32/bech32_ex.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// A utility class containing constants for Bech32 encoding and decoding. class Bech32BaseConst { @@ -77,7 +77,7 @@ class Bech32BaseUtils { static List convertToBase32(List data) { List? convData = _convertBits(data, 8, 5); if (convData == null) { - throw ArgumentException( + throw const ArgumentException( 'Invalid data, cannot perform conversion to base32'); } @@ -97,7 +97,7 @@ class Bech32BaseUtils { static List convertFromBase32(List data) { List? convData = _convertBits(data, 5, 8, pad: false); if (convData == null) { - throw ArgumentException( + throw const ArgumentException( 'Invalid data, cannot perform conversion from base32'); } @@ -193,14 +193,16 @@ abstract class Bech32DecoderBase { int checksumLen, bool Function(String hrp, List data) verifyChecksum) { if (_isStringMixed(bechStr)) { - throw ArgumentException('Invalid bech32 format (string is mixed case)'); + throw const 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)'); + throw const ArgumentException( + 'Invalid bech32 format (no separator found)'); } final hrp = bechStr.substring(0, sepPos); @@ -213,7 +215,8 @@ abstract class Bech32DecoderBase { if (dataPart.length < checksumLen + 1 || dataPart.codeUnits.any( (x) => !Bech32BaseConst.charset.contains(String.fromCharCode(x)))) { - throw ArgumentException('Invalid bech32 format (data part not valid)'); + throw const ArgumentException( + 'Invalid bech32 format (data part not valid)'); } final intData = dataPart.codeUnits diff --git a/lib/bech32/segwit_bech32.dart b/lib/bech32/segwit_bech32.dart index 2fb604c..1b65136 100644 --- a/lib/bech32/segwit_bech32.dart +++ b/lib/bech32/segwit_bech32.dart @@ -1,4 +1,8 @@ -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; +import 'package:blockchain_utils/utils/utils.dart'; + +import 'bech32_base.dart'; +import 'bech32_utils.dart'; /// A utility class containing constants used for segwit Bech32 encoding and decoding. class SegwitBech32Const { diff --git a/lib/binary/binary.dart b/lib/binary/binary.dart deleted file mode 100644 index da750bf..0000000 --- a/lib/binary/binary.dart +++ /dev/null @@ -1,4 +0,0 @@ -export 'binary_operation.dart'; -export 'bit_utils.dart'; -export 'utils.dart'; -export 'tracker.dart'; diff --git a/lib/bip/address/ada/ada_addres_type.dart b/lib/bip/address/ada/ada_addres_type.dart index c24d8fe..5a3be70 100644 --- a/lib/bip/address/ada/ada_addres_type.dart +++ b/lib/bip/address/ada/ada_addres_type.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/bip/address/exception/exception.dart'; class ADAAddressType { final int header; @@ -30,7 +30,7 @@ class ADAAddressType { case 0x8: return ADAAddressType.byron; } - throw MessageException("Invalid address header bytes.", + throw AddressConverterException("Invalid address header bytes.", details: {"value": header}); } @@ -44,7 +44,8 @@ class ADAAddressType { static ADAAddressType fromHeader(int? header) { return values.firstWhere( (element) => element.header == header, - orElse: () => throw MessageException("Invalid header value encountered."), + orElse: () => throw const AddressConverterException( + "Invalid header value encountered."), ); } diff --git a/lib/bip/address/ada/ada_byron_addr.dart b/lib/bip/address/ada/ada_byron_addr.dart index b1942ea..222b2b1 100644 --- a/lib/bip/address/ada/ada_byron_addr.dart +++ b/lib/bip/address/ada/ada_byron_addr.dart @@ -59,6 +59,7 @@ import 'package:blockchain_utils/bip/address/addr_dec_utils.dart'; import 'package:blockchain_utils/bip/address/addr_key_validator.dart'; import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; +import 'package:blockchain_utils/bip/address/exception/exception.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_path.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; @@ -69,8 +70,7 @@ import 'package:blockchain_utils/cbor/types/int.dart'; import 'package:blockchain_utils/cbor/types/list.dart'; import 'package:blockchain_utils/cbor/types/map.dart'; import 'package:blockchain_utils/crypto/crypto/crc32/crc32.dart'; -import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'network.dart'; @@ -157,7 +157,7 @@ class _AdaByronAddrHdPath { ); final decode = CborObject.fromCbor(plainTextBytes); if (decode is! CborListValue) { - throw ArgumentException("invalid bip32 path"); + throw const AddressConverterException("invalid bip32 path"); } final paths = decode.value .map((e) => Bip32KeyIndex(e is String ? int.parse(e) : e as int)) @@ -189,7 +189,7 @@ class ADAByronAddrAttrs { (cborValue.value.isNotEmpty && !cborValue.value.containsKey(cborOne) && !cborValue.value.containsKey(cborTwo))) { - throw ArgumentException('Invalid address attributes'); + throw const AddressConverterException('Invalid address attributes'); } final hdPath = cborValue.value.containsKey(cborOne) ? CborObject.fromCbor( @@ -257,12 +257,12 @@ class ADAByronAddrPayload { factory ADAByronAddrPayload.deserialize(List serPayloadBytes) { final addrPayload = CborObject.fromCbor(serPayloadBytes); if (addrPayload is! CborListValue || addrPayload.value.length != 3) { - throw const MessageException("Invalid address payload"); + throw const AddressConverterException("Invalid address payload"); } if (addrPayload.value[0] is! CborBytesValue || addrPayload.value[1] is! CborMapValue || addrPayload.value[2] is! CborIntValue) { - throw const MessageException("Invalid address payload"); + throw const AddressConverterException("Invalid address payload"); } final cborBytes = addrPayload.value[0] as CborBytesValue; // Check key hash length @@ -307,24 +307,25 @@ class ADAByronAddr { factory ADAByronAddr.deserialize(List serAddrBytes) { final addrBytes = CborObject.fromCbor(serAddrBytes); if (addrBytes is! CborListValue || addrBytes.value.length != 2) { - throw const MessageException("Invalid address encoding"); + throw const AddressConverterException("Invalid address encoding"); } if (addrBytes.value[0] is! CborTagValue || addrBytes.value[1] is! CborIntValue) { - throw const MessageException("Invalid address encoding"); + throw const AddressConverterException("Invalid address encoding"); } final decodeCbor = addrBytes.value[0] as CborTagValue; if (decodeCbor.tags.isEmpty || decodeCbor.tags.first != ADAByronAddrConst.payloadTag || decodeCbor.value is! CborBytesValue) { - throw const MessageException("Invalid CBOR tag"); + throw const AddressConverterException("Invalid CBOR tag"); } final crcTag = (addrBytes.value[1] as CborIntValue).value; final List payloadBytes = decodeCbor.value.value; final crc32Got = Crc32.quickIntDigest(payloadBytes); if (crc32Got != crcTag) { - throw MessageException("Invalid CRC (expected: $crcTag, got: $crc32Got)"); + throw AddressConverterException( + "Invalid CRC (expected: $crcTag, got: $crc32Got)"); } return ADAByronAddr(payload: ADAByronAddrPayload.deserialize(payloadBytes)); @@ -394,7 +395,7 @@ class AdaByronAddrDecoder implements BlockchainAddressDecoder { [Map kwargs = const {}]) { final addrType = kwargs["addr_type"]; if (addrType != null && addrType is! ADAByronAddrTypes) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ADAByronAddrTypes'); } @@ -403,13 +404,13 @@ class AdaByronAddrDecoder implements BlockchainAddressDecoder { /// Check if the provided network tag is a valid enum value. if (netTag != null && netTag is! ADANetwork) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ADANetwork'); } final decAddr = ADAByronAddr.decode(addr); if (addrType != null && decAddr.payload.type != addrType) { - throw ArgumentException('Invalid address type'); + throw const AddressConverterException('Invalid address type'); } if (netTag != null) { netTag as ADANetwork; @@ -418,7 +419,7 @@ class AdaByronAddrDecoder implements BlockchainAddressDecoder { netTag == ADANetwork.mainnet) { return decAddr.payload; } - throw MessageException("Invalid address network."); + throw const AddressConverterException("Invalid address network."); } } return decAddr.payload; @@ -470,7 +471,7 @@ class AdaByronIcarusAddrEncoder implements BlockchainAddressEncoder { /// Check if the provided network tag is a valid enum value. if (netTag is! ADANetwork) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ADANetwork'); } List chainCodeBytes; @@ -480,7 +481,7 @@ class AdaByronIcarusAddrEncoder implements BlockchainAddressEncoder { } else if (chainCode is List) { chainCodeBytes = chainCode; } else { - throw ArgumentException("invalid chaincode "); + throw const AddressConverterException("invalid chaincode "); } final pubkeyBytes = AddrKeyValidator.validateAndGetEd25519Key(pubKey).compressed; @@ -524,7 +525,7 @@ class AdaByronLegacyAddrEncoder implements BlockchainAddressEncoder { /// Check if the provided network tag is a valid enum value. if (netTag is! ADANetwork) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ADANetwork'); } @@ -533,7 +534,8 @@ class AdaByronLegacyAddrEncoder implements BlockchainAddressEncoder { hdPath = Bip32PathParser.parse(kwargs["hd_path"]); } else { if (kwargs["hd_path"] is! Bip32Path) { - throw ArgumentException("hd path must be string or Bip32Path"); + throw const AddressConverterException( + "hd path must be string or Bip32Path"); } hdPath = kwargs["hd_path"]; } @@ -544,17 +546,18 @@ class AdaByronLegacyAddrEncoder implements BlockchainAddressEncoder { chainCodeBytes = kwargs["chain_code"]; } else { if (kwargs["chain_code"] is! Bip32ChainCode) { - throw ArgumentException("chain code must be bytes or Bip32ChainCode"); + throw const AddressConverterException( + "chain code must be bytes or Bip32ChainCode"); } chainCodeBytes = (kwargs["chain_code"] as Bip32ChainCode).toBytes(); } List hdPathKeyBytes; if (kwargs["hd_path_key"] is! List) { - throw ArgumentException("hd path key must be bytes"); + throw const AddressConverterException("hd path key must be bytes"); } hdPathKeyBytes = kwargs["hd_path_key"]; if (hdPathKeyBytes.length != QuickCrypto.chacha20Polu1305Keysize) { - throw ArgumentException( + throw const AddressConverterException( "HD path key shall be ${QuickCrypto.chacha20Polu1305Keysize}-byte long"); } final pubKeyBytes = diff --git a/lib/bip/address/ada/ada_shelley_addr.dart b/lib/bip/address/ada/ada_shelley_addr.dart index 67dae36..149c682 100644 --- a/lib/bip/address/ada/ada_shelley_addr.dart +++ b/lib/bip/address/ada/ada_shelley_addr.dart @@ -1,17 +1,13 @@ import 'dart:typed_data'; - import 'package:blockchain_utils/bech32/bech32_base.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/address/addr_dec_utils.dart'; import 'package:blockchain_utils/bip/address/addr_key_validator.dart'; import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; +import 'package:blockchain_utils/bip/address/exception/exception.dart'; import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; -import 'package:blockchain_utils/numbers/int_utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; - import 'ada_addres_type.dart'; import 'network.dart'; @@ -66,10 +62,11 @@ class AdaStakeCredential { factory AdaStakeCredential( {required List hash, required AdaStakeCredType type}) { if (hash.length != QuickCrypto.blake2b224DigestSize) { - throw MessageException("Invalid credential hash length. ", details: { - "Excepted": QuickCrypto.blake2b224DigestSize, - "length": hash.length - }); + throw AddressConverterException("Invalid credential hash length. ", + details: { + "Excepted": QuickCrypto.blake2b224DigestSize, + "length": hash.length + }); } return AdaStakeCredential._(type, hash); } @@ -180,7 +177,7 @@ class AdaShelleyAddrDecoder implements BlockchainAddressDecoder { /// Check if the provided network tag is a valid enum value. if (netTag is! ADANetwork) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ADANetwork'); } @@ -211,7 +208,7 @@ class AdaShelleyAddrEncoder implements BlockchainAddressEncoder { final netTag = kwargs["net_tag"] ?? ADANetwork.mainnet; if (netTag is! ADANetwork) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ADANetwork'); } return AdaShelleyAddrUtils.encode( @@ -237,7 +234,7 @@ class AdaShelleyAddrEncoder implements BlockchainAddressEncoder { /// Check if the provided network tag is a valid enum value. if (netTag is! ADANetwork) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ADANetwork'); } @@ -273,7 +270,7 @@ class AdaShelleyStakingAddrDecoder implements BlockchainAddressDecoder { /// Check if the provided network tag is a valid enum value. if (netTag is! ADANetwork) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ADANetwork'); } @@ -303,7 +300,7 @@ class AdaShelleyStakingAddrEncoder implements BlockchainAddressEncoder { /// Check if the provided network tag is a valid enum value. if (netTag is! ADANetwork) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ADANetwork'); } return AdaShelleyAddrUtils.encode( @@ -322,7 +319,7 @@ class AdaShelleyStakingAddrEncoder implements BlockchainAddressEncoder { /// Check if the provided network tag is a valid enum value. if (netTag is! ADANetwork) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ADANetwork'); } @@ -352,7 +349,7 @@ class AdaShelleyEnterpriseDecoder implements BlockchainAddressDecoder { /// Check if the provided network tag is a valid enum value. if (netTag is! ADANetwork) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ADANetwork'); } @@ -381,7 +378,7 @@ class AdaShelleyEnterpriseAddrEncoder implements BlockchainAddressEncoder { /// Check if the provided network tag is a valid enum value. if (netTag is! ADANetwork) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ADANetwork'); } @@ -401,7 +398,7 @@ class AdaShelleyEnterpriseAddrEncoder implements BlockchainAddressEncoder { /// Check if the provided network tag is a valid enum value. if (netTag is! ADANetwork) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ADANetwork'); } @@ -432,7 +429,7 @@ class AdaShelleyPointerDecoder implements BlockchainAddressDecoder { /// Check if the provided network tag is a valid enum value. if (netTag is! ADANetwork) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ADANetwork'); } @@ -464,13 +461,13 @@ class AdaPointerAddrEncoder implements BlockchainAddressEncoder { /// Check if the provided network tag is a valid enum value. if (netTag is! ADANetwork) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ADANetwork'); } final pointer = kwargs["pointer"]; if (pointer is! Pointer) { - throw ArgumentException( + throw const AddressConverterException( 'The provided value for "Pointer" is not of type Pointer.'); } return AdaShelleyAddrUtils.encode( @@ -488,13 +485,13 @@ class AdaPointerAddrEncoder implements BlockchainAddressEncoder { /// Check if the provided network tag is a valid enum value. if (netTag is! ADANetwork) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ADANetwork'); } final pointer = kwargs["pointer"]; if (pointer is! Pointer) { - throw ArgumentException( + throw const AddressConverterException( 'The provided value for "Pointer" is not of type Pointer.'); } diff --git a/lib/bip/address/ada/gneric_addr_decoder.dart b/lib/bip/address/ada/gneric_addr_decoder.dart index 7e35cc3..2a13222 100644 --- a/lib/bip/address/ada/gneric_addr_decoder.dart +++ b/lib/bip/address/ada/gneric_addr_decoder.dart @@ -1,13 +1,12 @@ import 'package:blockchain_utils/base58/base58.dart'; import 'package:blockchain_utils/bech32/bech32_base.dart'; -import 'package:blockchain_utils/binary/binary.dart'; import 'package:blockchain_utils/bip/address/ada/ada_byron_addr.dart'; import 'package:blockchain_utils/bip/address/ada/ada_shelley_addr.dart'; import 'package:blockchain_utils/bip/address/addr_dec_utils.dart'; import 'package:blockchain_utils/bip/address/decoder.dart'; +import 'package:blockchain_utils/bip/address/exception/exception.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'ada_addres_type.dart'; import 'network.dart'; @@ -42,7 +41,7 @@ class AdaGenericAddrDecoder { if (netTag != null) { if (netTag is! ADANetwork) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ADANetwork'); } } @@ -63,7 +62,7 @@ class AdaGenericAddrDecoder { final List addressBytes = addrDecBytes.item2; if (addressBytes.length < QuickCrypto.blake2b224DigestSize + 1) { - throw ArgumentException("Invalid address length."); + throw const AddressConverterException("Invalid address length."); } int header = addressBytes[0]; int networkTag = AdaShelleyAddrUtils.decodeNetworkTag(header); @@ -106,10 +105,10 @@ class AdaGenericAddrDecoder { break; default: - throw ArgumentException("Invalid address prefix $addressType"); + throw AddressConverterException("Invalid address prefix $addressType"); } if (hrp == null || addrDecBytes.item1 != hrp) { - throw ArgumentException("Invalid address hrp ${hrp ?? ''}"); + throw AddressConverterException("Invalid address hrp ${hrp ?? ''}"); } if (addressType == ADAAddressType.byron) { diff --git a/lib/bip/address/ada/network.dart b/lib/bip/address/ada/network.dart index 31d95f2..6dbcb9c 100644 --- a/lib/bip/address/ada/network.dart +++ b/lib/bip/address/ada/network.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/bip/address/exception/exception.dart'; /// An enumeration of Ada Shelley address network tags. class ADANetwork { @@ -32,7 +32,8 @@ class ADANetwork { static ADANetwork fromTag(int tag) { return values.firstWhere( (element) => element.value == tag, - orElse: () => throw ArgumentException("Invalid network tag. $tag"), + orElse: () => + throw AddressConverterException("Invalid network tag. $tag"), ); } @@ -40,7 +41,7 @@ class ADANetwork { if (protocolMagic == null) return ADANetwork.mainnet; return values.firstWhere( (element) => element.protocolMagic == protocolMagic, - orElse: () => throw ArgumentException( + orElse: () => throw const AddressConverterException( "Invalid protocol magic or network does not supported."), ); } diff --git a/lib/bip/address/addr_dec_utils.dart b/lib/bip/address/addr_dec_utils.dart index 0a06087..c9d7469 100644 --- a/lib/bip/address/addr_dec_utils.dart +++ b/lib/bip/address/addr_dec_utils.dart @@ -1,9 +1,7 @@ import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; import 'package:blockchain_utils/bip/ecc/keys/i_keys.dart'; -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/compare/compare.dart'; -import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; +import 'exception/exception.dart'; /// Class for decode address utility functions. class AddrDecUtils { @@ -14,8 +12,8 @@ class AddrDecUtils { ) { final prefixGot = addr.sublist(0, prefix.length); - if (!bytesEqual(prefix, prefixGot)) { - throw ArgumentException( + if (!BytesUtils.bytesEqual(prefix, prefixGot)) { + throw AddressConverterException( 'Invalid prefix (expected $prefix, got $prefixGot)', ); } @@ -31,7 +29,7 @@ class AddrDecUtils { final prefixGot = addr.substring(0, prefix.length); if (prefix != prefixGot) { - throw ArgumentException( + throw AddressConverterException( 'Invalid prefix (expected $prefix, got $prefixGot)', ); } @@ -44,7 +42,7 @@ class AddrDecUtils { {int? minLength}) { if ((minLength != null && addr.length < minLength) || (minLength == null && addr.length != lenExp)) { - throw ArgumentException( + throw AddressConverterException( 'Invalid length (expected ${minLength ?? lenExp}, got ${addr.length})', ); } @@ -56,7 +54,7 @@ class AddrDecUtils { int lenExp, ) { if (addr.length != lenExp) { - throw ArgumentException( + throw AddressConverterException( 'Invalid length (expected $lenExp, got ${addr.length})', ); } @@ -70,7 +68,7 @@ class AddrDecUtils { try { IPublicKey.fromBytes(pubKeyBytes, curveType); } catch (e) { - throw ArgumentException( + throw AddressConverterException( "Invalid $curveType public key (${BytesUtils.toHexString(pubKeyBytes)})"); } } @@ -83,10 +81,8 @@ class AddrDecUtils { ) { final checksumBytesGot = checksumFct(payloadBytes); - if (!bytesEqual(checksumBytesExp, checksumBytesGot)) { - throw ArgumentException( - 'Invalid checksum', - ); + if (!BytesUtils.bytesEqual(checksumBytesExp, checksumBytesGot)) { + throw const AddressConverterException('Invalid checksum'); } } diff --git a/lib/bip/address/addr_key_validator.dart b/lib/bip/address/addr_key_validator.dart index 8bc147d..06a9eb2 100644 --- a/lib/bip/address/addr_key_validator.dart +++ b/lib/bip/address/addr_key_validator.dart @@ -1,13 +1,13 @@ import 'package:blockchain_utils/bip/ecc/keys/i_keys.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'exception/exception.dart'; /// Class for address utility functions. class AddrKeyValidator { /// validate argrument by key static T validateAddressArgs(Map kwargs, String key) { if (!kwargs.containsKey(key) || kwargs[key] is! T) { - throw ArgumentException( + throw AddressConverterException( 'Invalid or Missing required parameters: $key as type $T'); } return kwargs[key] as T; diff --git a/lib/bip/address/aptos_addr.dart b/lib/bip/address/aptos_addr.dart index 9bcb7bc..ec1fd2c 100644 --- a/lib/bip/address/aptos_addr.dart +++ b/lib/bip/address/aptos_addr.dart @@ -3,7 +3,7 @@ import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'addr_key_validator.dart'; diff --git a/lib/bip/address/decoders.dart b/lib/bip/address/decoders.dart index 5595657..4ea2ed3 100644 --- a/lib/bip/address/decoders.dart +++ b/lib/bip/address/decoders.dart @@ -106,3 +106,5 @@ export 'xtz_addr.dart' show XtzAddrDecoder; /// Export statement for Zilliqa (ZIL) address decoder. export 'zil_addr.dart' show ZilAddrDecoder; + +export 'ton_addr.dart' show TonAddrDecoder, TonAddressUtils; diff --git a/lib/bip/address/encoders.dart b/lib/bip/address/encoders.dart index 415702e..6671721 100644 --- a/lib/bip/address/encoders.dart +++ b/lib/bip/address/encoders.dart @@ -27,7 +27,7 @@ export 'algo_addr.dart' show AlgoAddrEncoder; export 'aptos_addr.dart' show AptosAddrEncoder; /// Export statement for Atom address encoder. -export 'atom_addr.dart' show AtomAddrEncoder; +export 'atom_addr.dart' show AtomAddrEncoder, AtomNist256P1AddrEncoder; /// Export statements for Avalanche (AVAX) address encoders. export 'avax_addr.dart' show AvaxXChainAddrEncoder, AvaxPChainAddrEncoder; @@ -42,7 +42,7 @@ export 'egld_addr.dart' show EgldAddrEncoder; export 'eos_addr.dart' show EosAddrEncoder; /// Export statement for Ergo address encoder. -export 'ergo.dart' show ErgoP2PKHAddrEncoder; +export 'ergo.dart' show ErgoP2PKHAddrEncoder, ErgoNetworkTypes; /// Export statement for Ethereum address encoder. export 'eth_addr.dart' show EthAddrEncoder; @@ -98,7 +98,7 @@ export 'substrate_addr.dart' export 'trx_addr.dart' show TrxAddrEncoder; /// Export statement for Stellar (XLM) address encoder. -export 'xlm_addr.dart' show XlmAddrEncoder; +export 'xlm_addr.dart' show XlmAddrEncoder, XlmAddrTypes; /// Export statements for Monero (XMR) address encoders. export 'xmr_addr.dart' show XmrAddrEncoder, XmrIntegratedAddrEncoder; @@ -107,7 +107,10 @@ export 'xmr_addr.dart' show XmrAddrEncoder, XmrIntegratedAddrEncoder; export 'xrp_addr.dart' show XrpAddrEncoder, XrpXAddrEncoder, XRPAddressUtils; /// Export statement for Tezos (XTZ) address encoder. -export 'xtz_addr.dart' show XtzAddrEncoder; +export 'xtz_addr.dart' show XtzAddrEncoder, XtzAddrPrefixes; /// Export statement for Zilliqa (ZIL) address encoder. export 'zil_addr.dart' show ZilAddrEncoder; + +export 'ton_addr.dart' + show TonAddrEncoder, TonAddressUtils, FriendlyAddressFlags; diff --git a/lib/bip/address/ergo.dart b/lib/bip/address/ergo.dart index fcec32a..7e5be8e 100644 --- a/lib/bip/address/ergo.dart +++ b/lib/bip/address/ergo.dart @@ -7,8 +7,8 @@ import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; import 'package:blockchain_utils/bip/ecc/keys/ecdsa_keys.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/numbers/int_utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/utils/utils.dart'; +import 'exception/exception.dart'; /// An enumeration representing different Ergo address types. class ErgoAddressTypes { @@ -88,7 +88,7 @@ class ErgoP2PKHAddrDecoder implements BlockchainAddressDecoder { /// Validate network type if (netType is! ErgoNetworkTypes) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ErgoNetworkTypes'); } final addrDecBytes = Base58Decoder.decode(addr); @@ -134,7 +134,7 @@ class ErgoP2PKHAddrEncoder implements BlockchainAddressEncoder { /// Validate network type if (netType is! ErgoNetworkTypes) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of ErgoNetworkTypes'); } diff --git a/lib/bip/address/eth_addr.dart b/lib/bip/address/eth_addr.dart index 668e912..0183ee0 100644 --- a/lib/bip/address/eth_addr.dart +++ b/lib/bip/address/eth_addr.dart @@ -3,11 +3,10 @@ import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; import 'package:blockchain_utils/bip/ecc/keys/i_keys.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/string/string.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'addr_key_validator.dart'; import 'encoder.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'exception/exception.dart'; /// Constants related to Ethereum addresses. class EthAddrConst { @@ -82,7 +81,7 @@ class EthAddrDecoder implements BlockchainAddressDecoder { AddrDecUtils.validateLength(addrNoPrefix, EthAddrConst.addrLen); if (!skipChecksum && addrNoPrefix != EthAddrUtils._checksumEncode(addrNoPrefix)) { - throw ArgumentException("Invalid checksum encoding"); + throw const AddressConverterException("Invalid checksum encoding"); } return BytesUtils.fromHexString(addrNoPrefix); } diff --git a/lib/bip/address/exception/exception.dart b/lib/bip/address/exception/exception.dart new file mode 100644 index 0000000..79613c4 --- /dev/null +++ b/lib/bip/address/exception/exception.dart @@ -0,0 +1,11 @@ +import 'package:blockchain_utils/exception/exceptions.dart'; + +class AddressConverterException implements BlockchainUtilsException { + @override + final String message; + + @override + final Map? details; + + const AddressConverterException(this.message, {this.details}); +} diff --git a/lib/bip/address/fil_addr.dart b/lib/bip/address/fil_addr.dart index 208dc81..9e19680 100644 --- a/lib/bip/address/fil_addr.dart +++ b/lib/bip/address/fil_addr.dart @@ -5,7 +5,7 @@ import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'exception/exception.dart'; /// Enum representing different address types for Filecoin (FIL) addresses. class FillAddrTypes { @@ -70,7 +70,7 @@ class _FilAddrUtils { addr, CoinsConf.filecoin.params.addrPrefix!); int addrTypeGot = addrNoPrefix[0].codeUnits.first - "0".codeUnits.first; if (addrType.value != addrTypeGot) { - throw ArgumentException( + throw AddressConverterException( "Invalid address type (expected ${addrType.value}, got $addrTypeGot)"); } List addrDecBytes = Base32Decoder.decode( diff --git a/lib/bip/address/icx_addr.dart b/lib/bip/address/icx_addr.dart index 7f37347..c6adba1 100644 --- a/lib/bip/address/icx_addr.dart +++ b/lib/bip/address/icx_addr.dart @@ -5,7 +5,7 @@ import 'package:blockchain_utils/bip/address/encoder.dart'; import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; import 'package:blockchain_utils/bip/ecc/keys/i_keys.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// Defines constants related to ICON (ICX) addresses. class IcxAddrConst { diff --git a/lib/bip/address/inj_addr.dart b/lib/bip/address/inj_addr.dart index 81d38e6..6577cf7 100644 --- a/lib/bip/address/inj_addr.dart +++ b/lib/bip/address/inj_addr.dart @@ -4,7 +4,7 @@ import 'package:blockchain_utils/bip/address/eth_addr.dart'; import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// Implementation of the [BlockchainAddressDecoder] for INJ (Injective Protocol) addresses. class InjAddrDecoder implements BlockchainAddressDecoder { diff --git a/lib/bip/address/near_addr.dart b/lib/bip/address/near_addr.dart index 2eeb678..deb5881 100644 --- a/lib/bip/address/near_addr.dart +++ b/lib/bip/address/near_addr.dart @@ -3,8 +3,7 @@ import 'package:blockchain_utils/bip/address/addr_key_validator.dart'; import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; import 'package:blockchain_utils/bip/ecc/keys/ed25519_keys.dart'; -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/string/string.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// Implementation of the [BlockchainAddressDecoder] for Near Protocol addresses. class NearAddrDecoder implements BlockchainAddressDecoder { diff --git a/lib/bip/address/neo_addr.dart b/lib/bip/address/neo_addr.dart index fc29acb..ae052f5 100644 --- a/lib/bip/address/neo_addr.dart +++ b/lib/bip/address/neo_addr.dart @@ -1,15 +1,12 @@ import 'dart:typed_data'; - import 'package:blockchain_utils/base58/base58_base.dart'; import 'package:blockchain_utils/bip/address/addr_dec_utils.dart'; import 'package:blockchain_utils/bip/address/addr_key_validator.dart'; import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/compare/compare.dart'; -import 'package:blockchain_utils/numbers/int_utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/utils/utils.dart'; +import 'exception/exception.dart'; /// A class that defines constants for Neo (NEO) addresses. class NeoAddrConst { @@ -50,8 +47,8 @@ class NeoAddrDecoder implements BlockchainAddressDecoder { List verGot = IntUtils.toBytes(addrDecBytes[0], length: IntUtils.bitlengthInBytes(addrDecBytes[0]), byteOrder: Endian.little); - if (!bytesEqual(verGot, verBytes)) { - throw ArgumentException( + if (!BytesUtils.bytesEqual(verGot, verBytes)) { + throw AddressConverterException( "Invalid version (expected ${BytesUtils.toHexString(verBytes)}, " "got ${BytesUtils.toHexString(verGot)})"); } diff --git a/lib/bip/address/okex_addr.dart b/lib/bip/address/okex_addr.dart index 1391d4f..b5b13f3 100644 --- a/lib/bip/address/okex_addr.dart +++ b/lib/bip/address/okex_addr.dart @@ -4,9 +4,8 @@ import 'package:blockchain_utils/bip/address/eth_addr.dart'; import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/string/string.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/utils/utils.dart'; +import 'exception/exception.dart'; /// Implementation of the [BlockchainAddressDecoder] for OKExChain addresses. class OkexAddrDecoder implements BlockchainAddressDecoder { @@ -39,7 +38,7 @@ class OkexAddrDecoder implements BlockchainAddressDecoder { {"skip_chksum_enc": true}); } catch (e) { if (e is Bech32ChecksumError) { - throw ArgumentException('Invalid bech32 checksum'); + throw const AddressConverterException('Invalid bech32 checksum'); } rethrow; } diff --git a/lib/bip/address/one_addr.dart b/lib/bip/address/one_addr.dart index 5b03e54..0b4893b 100644 --- a/lib/bip/address/one_addr.dart +++ b/lib/bip/address/one_addr.dart @@ -3,8 +3,7 @@ import 'package:blockchain_utils/bip/address/eth_addr.dart'; import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/string/string.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// Implementation of the [BlockchainAddressDecoder] for Harmony (ONE) addresses. class OneAddrDecoder implements BlockchainAddressDecoder { diff --git a/lib/bip/address/p2pkh_addr.dart b/lib/bip/address/p2pkh_addr.dart index cde6b8f..a75527c 100644 --- a/lib/bip/address/p2pkh_addr.dart +++ b/lib/bip/address/p2pkh_addr.dart @@ -1,12 +1,12 @@ import 'package:blockchain_utils/base58/base58.dart'; import 'package:blockchain_utils/bech32/bch_bech32.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/address/addr_dec_utils.dart'; import 'package:blockchain_utils/bip/address/addr_key_validator.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/compare/compare.dart'; import 'decoder.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'exception/exception.dart'; /// Enumeration representing different modes for public keys used in P2PKH addresses. /// @@ -79,11 +79,11 @@ class P2PKHAddrEncoder implements BlockchainAddressEncoder { final List netVerBytes = kwargs["net_ver"]; final alphabet = kwargs["base58_alph"] ?? Base58Alphabets.bitcoin; if (alphabet is! Base58Alphabets) { - throw ArgumentException("invalid base58 alphabet"); + throw const AddressConverterException("invalid base58 alphabet"); } final pubKeyModes = kwargs["pub_key_mode"] ?? PubKeyModes.compressed; if (pubKeyModes is! PubKeyModes) { - throw ArgumentException("invalid pub key mode"); + throw const AddressConverterException("invalid pub key mode"); } /// Validate and process the public key as a Secp256k1 key. @@ -132,8 +132,8 @@ class BchP2PKHAddrDecoder implements BlockchainAddressDecoder { List addrDecBytes = result.item2; /// Validate that the decoded network version matches the expected network version. - if (!bytesEqual(netVerBytes, netVerBytesGot)) { - throw ArgumentException("Invalid net version"); + if (!BytesUtils.bytesEqual(netVerBytes, netVerBytesGot)) { + throw const AddressConverterException("Invalid net version"); } /// Validate the length of the decoded address. diff --git a/lib/bip/address/p2tr_addr.dart b/lib/bip/address/p2tr_addr.dart index 1601a3a..35b3070 100644 --- a/lib/bip/address/p2tr_addr.dart +++ b/lib/bip/address/p2tr_addr.dart @@ -1,18 +1,14 @@ import 'package:blockchain_utils/bech32/segwit_bech32.dart'; -import 'package:blockchain_utils/compare/compare.dart'; -import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'exception/exception.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/address/addr_dec_utils.dart'; import 'package:blockchain_utils/bip/address/addr_key_validator.dart'; import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; import 'package:blockchain_utils/bip/ecc/keys/ecdsa_keys.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/binary/utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curves.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/ec_projective_point.dart'; -import 'package:blockchain_utils/numbers/int_utils.dart'; -import '../../string/string.dart'; /// Constants related to P2TR (Pay-to-Taproot) addresses. class P2TRConst { @@ -49,7 +45,7 @@ class P2TRUtils { /// - ArgumentException if the tag is not a string or bytes. static List taggedHash(dynamic tag, List dataBytes) { if (tag! is String && tag! is List) { - throw ArgumentException("tag must be bytes or string"); + throw const AddressConverterException("tag must be bytes or string"); } List tagHash = tag is String ? QuickCrypto.sha256Hash(StringUtils.encode(tag)) : tag; @@ -90,12 +86,12 @@ class P2TRUtils { final BigInt p = Curves.curveSecp256k1.p; final BigInt x = pubKeyPoint.x; if (x >= p) { - throw MessageException("Unable to compute LiftX point"); + throw const AddressConverterException("Unable to compute LiftX point"); } final ySq = (x.modPow(BigInt.from(3), p) + BigInt.from(7)) % p; final y = ySq.modPow((p + BigInt.one) ~/ BigInt.from(4), p); if (y.modPow(BigInt.two, p) != ySq) { - throw MessageException("Unable to compute LiftX point"); + throw const AddressConverterException("Unable to compute LiftX point"); } BigInt result = (y & BigInt.one) == BigInt.zero ? y : p - y; return ProjectiveECCPoint( @@ -115,7 +111,7 @@ class P2TRUtils { /// for Taproot, where 'a' and 'b' are the input byte slices. It ensures that 'a' and 'b' /// are sorted and concatenated before tagging the hash with "TapBranch". static List _tapBranchTaggedHash(List a, List b) { - if (isLessThanBytes(a, b)) { + if (BytesUtils.isLessThanBytes(a, b)) { return taggedHash("TapBranch", [...a, ...b]); } return taggedHash("TapBranch", [...b, ...a]); @@ -140,7 +136,8 @@ class P2TRUtils { final tap = _tapBranchTaggedHash(left, right); return tap; } - throw ArgumentException("List cannot have more than 2 branches."); + throw const AddressConverterException( + "List cannot have more than 2 branches."); } /// _calculateTweek computes and returns the TapTweak value based on the ECPublic key @@ -221,7 +218,7 @@ class P2TRAddrDecoder implements BlockchainAddressDecoder { /// Check the witness version. if (witVerGot != P2TRConst.witnessVer) { - throw ArgumentException( + throw AddressConverterException( 'Invalid witness version (expected ${P2TRConst.witnessVer}, got $witVerGot)'); } diff --git a/lib/bip/address/p2wpkh_addr.dart b/lib/bip/address/p2wpkh_addr.dart index 1814c33..3158417 100644 --- a/lib/bip/address/p2wpkh_addr.dart +++ b/lib/bip/address/p2wpkh_addr.dart @@ -3,7 +3,7 @@ import 'package:blockchain_utils/bip/address/addr_key_validator.dart'; import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'exception/exception.dart'; /// Constants related to P2WPKH (Pay-to-Witness-Public-Key-Hash) addresses. class P2WPKHAddrConst { @@ -45,7 +45,7 @@ class P2WPKHAddrDecoder implements BlockchainAddressDecoder { /// Check the witness version. if (witVerGot != P2WPKHAddrConst.witnessVer) { - throw MessageException( + throw AddressConverterException( 'Invalid witness version (expected ${P2WPKHAddrConst.witnessVer}, got $witVerGot)'); } diff --git a/lib/bip/address/substrate_addr.dart b/lib/bip/address/substrate_addr.dart index ae2039d..a0b2211 100644 --- a/lib/bip/address/substrate_addr.dart +++ b/lib/bip/address/substrate_addr.dart @@ -1,7 +1,11 @@ import 'package:blockchain_utils/bip/address/addr_key_validator.dart'; import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; +import 'package:blockchain_utils/crypto/quick_crypto.dart'; +import 'package:blockchain_utils/ss58/ss58_base.dart'; +import 'package:blockchain_utils/utils/utils.dart'; +import 'exception/exception.dart'; /// Utility class for decoding and working with Substrate addresses. class _SubstrateAddrUtils { @@ -12,12 +16,12 @@ class _SubstrateAddrUtils { final ss58FormatGot = decodedResult.item1; final addrDecBytes = decodedResult.item2; if (addrDecBytes.length != encodeBytesLength) { - throw ArgumentException( + throw AddressConverterException( "Invalid address bytes. (expected $encodeBytesLength, got ${addrDecBytes.length})"); } if (ss58Format != null && ss58Format != ss58FormatGot) { - throw ArgumentException( + throw AddressConverterException( "Invalid SS58 format (expected $ss58Format, got $ss58FormatGot)"); } @@ -26,7 +30,7 @@ class _SubstrateAddrUtils { static String encode(List pubKeyBytes, int ss58Format) { if (pubKeyBytes.length != encodeBytesLength) { - throw ArgumentException( + throw AddressConverterException( "Invalid pubkey length (excepted $encodeBytesLength, got ${pubKeyBytes.length}) "); } return SS58Encoder.encode(pubKeyBytes, ss58Format); @@ -216,7 +220,7 @@ class SubstrateGenericAddrEncoder implements BlockchainAddressEncoder { } return SubstrateSr25519AddrEncoder().encodeKey(pubKey, kwargs); } catch (e) { - throw ArgumentException( + throw const AddressConverterException( "Invalid ed25519, secp256k1 or sr25519 public key bytes"); } } diff --git a/lib/bip/address/ton_addr.dart b/lib/bip/address/ton_addr.dart new file mode 100644 index 0000000..eb40341 --- /dev/null +++ b/lib/bip/address/ton_addr.dart @@ -0,0 +1,235 @@ +// MIT License + +// Copyright (c) 2022-2023 Whales Corp. (all contributions until 2023-04-27) +// Copyright (c) 2023+ The TON Authors (all contributions from 2023-04-27) +// Copyright (c) 2024+ MRT Network (Dart Package). + +// 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:blockchain_utils/bip/address/addr_key_validator.dart'; +import 'package:blockchain_utils/bip/address/decoder.dart'; +import 'package:blockchain_utils/bip/address/encoder.dart'; +import 'package:blockchain_utils/crypto/crypto/crc16/crc16.dart'; +import 'package:blockchain_utils/utils/utils.dart'; +import 'exception/exception.dart'; + +class DecodeAddressResult { + final int workchain; + final List hash; + DecodeAddressResult( + {required this.workchain, + required this.hash, + required List flags}) + : flags = List.unmodifiable(flags); + final List flags; + bool get isFriendly => flags.isNotEmpty; + bool get isTestOnly => flags.contains(FriendlyAddressFlags.test); + bool get isBounceable => flags.contains(FriendlyAddressFlags.bounceable); +} + +class FriendlyAddressFlags { + final String name; + final int flag; + const FriendlyAddressFlags._(this.name, this.flag); + static const FriendlyAddressFlags bounceable = + FriendlyAddressFlags._("bounceable", 0x11); + static const FriendlyAddressFlags nonBounceable = + FriendlyAddressFlags._("nonBounceable", 0x51); + static const FriendlyAddressFlags test = + FriendlyAddressFlags._("nonBounceable", 0x80); +} + +class _TonAddressConst { + static const int friendlyAddressLength = 48; + static const int addressHashLength = 32; + static const int friendlyAddressBytesLength = 36; +} + +class TonAddressUtils { + static final RegExp _friendlyRegixAddress = RegExp(r'[A-Za-z0-9+/_-]+'); + static bool isFriendly(String source) { + if (source.length == _TonAddressConst.friendlyAddressLength && + _friendlyRegixAddress.hasMatch(source)) { + return true; + } + return false; + } + + static bool isRaw(String source) { + final parts = source.split(':'); + try { + int.parse(parts[0]); + final hashBytes = BytesUtils.fromHexString(parts[1]); + if (hashBytes.length == _TonAddressConst.addressHashLength) { + return true; + } + return false; + } catch (e) { + return false; + } + } + + static DecodeAddressResult fromFriendlyAddress(String address) { + final data = StringUtils.encode(address, type: StringEncoding.base64); + // 1 byte tag + 1 byte workchain + 32 bytes hash + 2 byte crc + if (data.length != _TonAddressConst.friendlyAddressBytesLength) { + throw AddressConverterException( + "Unknown address type. byte length is not equal to ${_TonAddressConst.friendlyAddressBytesLength}", + details: {"length": data.length}); + } + + // Prepare data + final addr = data.sublist(0, 34); + final crc = data.sublist(34, 36); + final calcedCrc = Crc16.quickIntDigest(addr); + if (!BytesUtils.bytesEqual(crc, calcedCrc)) { + throw AddressConverterException("Invalid checksum", + details: {"excepted": calcedCrc, "checksum": crc}); + } + List flags = []; + // Parse tag + int tag = addr[0]; + // bool isTestOnly = false; + // bool isBounceable = false; + if ((tag & FriendlyAddressFlags.test.flag) != 0) { + flags.add(FriendlyAddressFlags.test); + tag ^= FriendlyAddressFlags.test.flag; + } + if (tag != FriendlyAddressFlags.bounceable.flag && + tag != FriendlyAddressFlags.nonBounceable.flag) { + throw AddressConverterException("Unknown address tag", + details: {"tag": tag}); + } + if (tag == FriendlyAddressFlags.bounceable.flag) { + flags.add(FriendlyAddressFlags.bounceable); + } else { + flags.add(FriendlyAddressFlags.nonBounceable); + } + int? workchain; + if (addr[1] == mask8) { + workchain = -1; + } else { + workchain = addr[1]; + } + final hashPart = addr.sublist(2, 34); + return DecodeAddressResult( + workchain: workchain, hash: hashPart, flags: flags); + } + + static DecodeAddressResult fromRawAddress(String address) { + try { + final parts = address.split(':'); + final int workChain = int.parse(parts[0]); + final hash = BytesUtils.fromHexString(parts[1]); + return DecodeAddressResult(hash: hash, workchain: workChain, flags: []); + } catch (e) { + throw AddressConverterException("Invalid raw address", + details: {"address": address}); + } + } + + static String encodeAddress( + {required List hash, + required int workChain, + bool bounceable = true, + bool testOnly = false, + bool urlSafe = false}) { + int tag = bounceable + ? FriendlyAddressFlags.bounceable.flag + : FriendlyAddressFlags.nonBounceable.flag; + if (testOnly) { + tag |= FriendlyAddressFlags.test.flag; + } + final List addr = + List.unmodifiable([tag, workChain & mask8, ...hash]); + final addrBytes = [...addr, ...Crc16.quickIntDigest(addr)]; + + final encode = StringUtils.decode(addrBytes, type: StringEncoding.base64); + if (urlSafe) { + return encode.replaceAll('+', '-').replaceAll('/', '_'); + } + return encode; + } + + static DecodeAddressResult decodeAddress(String address) { + if (isFriendly(address)) { + return fromFriendlyAddress(address); + } else if (isRaw(address)) { + return fromRawAddress(address); + } else { + throw AddressConverterException('Unknown address type.', + details: {"address": address}); + } + } + + static List validateAddressHash(List bytes) { + if (bytes.length != _TonAddressConst.addressHashLength) { + throw AddressConverterException("Invalid address hash length.", details: { + "excepted": _TonAddressConst.addressHashLength, + "length": bytes.length + }); + } + return BytesUtils.toBytes(bytes, unmodifiable: true); + } +} + +class TonAddrDecoder implements BlockchainAddressDecoder { + @override + List decodeAddr(String addr, [Map kwargs = const {}]) { + final int? workChain = + AddrKeyValidator.nullOrValidateAddressArgs(kwargs, "workchain"); + final decode = TonAddressUtils.decodeAddress(addr); + if (workChain != null && workChain != decode.workchain) { + throw AddressConverterException("Invalid address workchain.", + details: {"excepted": workChain, "workchain": decode.workchain}); + } + return decode.hash; + } + + DecodeAddressResult decodeWithResult(String addr, + [Map kwargs = const {}]) { + final int? workChain = + AddrKeyValidator.nullOrValidateAddressArgs(kwargs, "workchain"); + final decode = TonAddressUtils.decodeAddress(addr); + if (workChain != null && workChain != decode.workchain) { + throw AddressConverterException("Invalid address workchain.", + details: {"excepted": workChain, "workchain": decode.workchain}); + } + return decode; + } +} + +class TonAddrEncoder implements BlockchainAddressEncoder { + @override + String encodeKey(List hash, [Map kwargs = const {}]) { + final int workChain = + AddrKeyValidator.validateAddressArgs(kwargs, "workchain"); + final bool bounceable = AddrKeyValidator.nullOrValidateAddressArgs( + kwargs, "bounceable") ?? + true; + final bool urlSafe = + AddrKeyValidator.nullOrValidateAddressArgs(kwargs, "url_safe") ?? + true; + + return TonAddressUtils.encodeAddress( + hash: hash, + workChain: workChain, + bounceable: bounceable, + urlSafe: urlSafe); + } +} diff --git a/lib/bip/address/trx_addr.dart b/lib/bip/address/trx_addr.dart index 5b4104d..e29e30d 100644 --- a/lib/bip/address/trx_addr.dart +++ b/lib/bip/address/trx_addr.dart @@ -4,7 +4,7 @@ import 'package:blockchain_utils/bip/address/eth_addr.dart'; import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; class TrxAddressUtils { static const List prefix = [0x41]; diff --git a/lib/bip/address/xlm_addr.dart b/lib/bip/address/xlm_addr.dart index cb7f332..d4e401d 100644 --- a/lib/bip/address/xlm_addr.dart +++ b/lib/bip/address/xlm_addr.dart @@ -6,7 +6,7 @@ import 'package:blockchain_utils/bip/ecc/keys/i_keys.dart'; import 'package:blockchain_utils/bip/ecc/keys/ed25519_keys.dart'; import 'package:blockchain_utils/crypto/crypto/x_modem_crc/x_modem_crc.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'exception/exception.dart'; import 'encoder.dart'; @@ -78,7 +78,7 @@ class XlmAddrDecoder implements BlockchainAddressDecoder { /// ``` final addrType = kwargs['addr_type'] ?? XlmAddrTypes.pubKey; if (addrType is! XlmAddrTypes) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of XlmAddrTypes'); } @@ -96,7 +96,7 @@ class XlmAddrDecoder implements BlockchainAddressDecoder { final addrTypeGot = payloadBytes[0]; if (addrType.value != addrTypeGot) { - throw ArgumentException( + throw AddressConverterException( 'Invalid address type (expected ${addrType.value}, got $addrTypeGot)'); } @@ -132,7 +132,7 @@ class XlmAddrEncoder implements BlockchainAddressEncoder { String encodeKey(List pubKey, [Map kwargs = const {}]) { final addrType = kwargs['addr_type'] ?? XlmAddrTypes.pubKey; if (addrType is! XlmAddrTypes) { - throw ArgumentException( + throw const AddressConverterException( 'Address type is not an enumerative of XlmAddrTypes'); } diff --git a/lib/bip/address/xmr_addr.dart b/lib/bip/address/xmr_addr.dart index 7a485db..b17f701 100644 --- a/lib/bip/address/xmr_addr.dart +++ b/lib/bip/address/xmr_addr.dart @@ -58,9 +58,8 @@ import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; import 'package:blockchain_utils/bip/ecc/keys/ed25519_keys.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/compare/compare.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/utils/utils.dart'; +import 'exception/exception.dart'; import 'addr_key_validator.dart'; /// Constants related to Monero (XMR) addresses. @@ -115,13 +114,13 @@ class _XmrAddrUtils { /// Check payment ID if (paymentIdBytes == null || paymentIdBytes.length != XmrAddrConst.paymentIdByteLen) { - throw ArgumentException('Invalid payment ID'); + throw const AddressConverterException('Invalid payment ID'); } final paymentIdGotBytes = payloadBytesWithoutPrefix.sublist( payloadBytesWithoutPrefix.length - XmrAddrConst.paymentIdByteLen); - if (!bytesEqual(paymentIdBytes, paymentIdGotBytes)) { - throw ArgumentException( + if (!BytesUtils.bytesEqual(paymentIdBytes, paymentIdGotBytes)) { + throw AddressConverterException( 'Invalid payment ID (expected ${BytesUtils.toHexString(paymentIdBytes)}, ' 'got ${BytesUtils.toHexString(paymentIdGotBytes)})'); } @@ -150,7 +149,7 @@ class _XmrAddrUtils { }) { if (paymentIdBytes != null && paymentIdBytes.length != XmrAddrConst.paymentIdByteLen) { - throw ArgumentException('Invalid payment ID length'); + throw const AddressConverterException('Invalid payment ID length'); } final paymentIdBytesSafe = paymentIdBytes ?? List.from([]); diff --git a/lib/bip/address/xrp_addr.dart b/lib/bip/address/xrp_addr.dart index 1ceec37..2ca9fff 100644 --- a/lib/bip/address/xrp_addr.dart +++ b/lib/bip/address/xrp_addr.dart @@ -1,9 +1,14 @@ +import 'package:blockchain_utils/base58/base58.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/address/addr_dec_utils.dart'; import 'package:blockchain_utils/bip/address/addr_key_validator.dart'; import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/bip/ecc/bip_ecc.dart'; +import 'package:blockchain_utils/crypto/quick_crypto.dart'; +import 'exception/exception.dart'; +import 'p2pkh_addr.dart'; /// Constants related to XRP (Ripple) addresses. class _XRPAddressConst { @@ -31,7 +36,7 @@ class XRPAddressUtils { /// throws ArgumentException if the address hash length is not equal to QuickCrypto.hash160DigestSize. static String hashToAddress(List addrHash) { if (addrHash.length != QuickCrypto.hash160DigestSize) { - throw ArgumentException( + throw AddressConverterException( "address hash must be ${QuickCrypto.hash160DigestSize} bytes length but got ${addrHash.length}"); } @@ -66,7 +71,7 @@ class XRPAddressUtils { static String hashToXAddress( List addrHash, List xAddrPrefix, int? tag) { if (tag != null && tag > mask32) { - throw ArgumentException( + throw const AddressConverterException( "Invalid tag. Tag should be lower than 2^32 for Ripple X address"); } List addrBytes = [...xAddrPrefix, ...addrHash]; @@ -98,14 +103,16 @@ class XRPAddressUtils { addrDecBytes.sublist(0, _XRPAddressConst.xAddressPrefixLength); if (prefix != null) { - if (!bytesEqual(prefix, prefixBytes)) { - throw ArgumentException( + if (!BytesUtils.bytesEqual(prefix, prefixBytes)) { + throw AddressConverterException( 'Invalid prefix (expected $prefix, got $prefixBytes)'); } } else { - if (!bytesEqual(prefixBytes, _XRPAddressConst._xAddressPrefixMain) && - !bytesEqual(prefixBytes, _XRPAddressConst._xAddressPrefixTest)) { - throw ArgumentException( + if (!BytesUtils.bytesEqual( + prefixBytes, _XRPAddressConst._xAddressPrefixMain) && + !BytesUtils.bytesEqual( + prefixBytes, _XRPAddressConst._xAddressPrefixTest)) { + throw const AddressConverterException( 'Invalid prefix for mainnet or testnet ripple address'); } } @@ -117,12 +124,13 @@ class XRPAddressUtils { .sublist(addrDecBytes.length - _XRPAddressConst.xAddressTagLength); int tagFlag = tagBytes[0]; if (tagFlag != 0 && tagFlag != 1) { - throw ArgumentException( + throw AddressConverterException( 'Invalid tag flag, tag flag should be 0 or 1 but got ${tagBytes[0]}'); } tagBytes = tagBytes.sublist(1); - if (tagFlag == 0 && !bytesEqual(tagBytes, List.filled(8, 0))) { - throw ArgumentException("tag bytes must be zero for flag 0"); + if (tagFlag == 0 && !BytesUtils.bytesEqual(tagBytes, List.filled(8, 0))) { + throw const AddressConverterException( + "tag bytes must be zero for flag 0"); } int? tag; @@ -185,7 +193,8 @@ class XRPAddressUtils { return xAddr.item1; } } catch (e) { - throw ArgumentException("invalid ripple X or classic address"); + throw const AddressConverterException( + "invalid ripple X or classic address"); } } @@ -299,7 +308,7 @@ class XrpAddrEncoder implements BlockchainAddressEncoder { if (publicType is! EllipticCurveTypes || (publicType != EllipticCurveTypes.secp256k1 && publicType != EllipticCurveTypes.ed25519)) { - throw ArgumentException( + throw const AddressConverterException( 'Missing required parameters: curve_type, curvetype must be EllipticCurveTypes.secp256k1 or EllipticCurveTypes.ed25519'); } if (publicType == EllipticCurveTypes.secp256k1) { diff --git a/lib/bip/address/xtz_addr.dart b/lib/bip/address/xtz_addr.dart index d8afacc..2a8ca1e 100644 --- a/lib/bip/address/xtz_addr.dart +++ b/lib/bip/address/xtz_addr.dart @@ -1,8 +1,9 @@ +import 'package:blockchain_utils/base58/base58.dart'; import 'package:blockchain_utils/bip/address/addr_key_validator.dart'; import 'package:blockchain_utils/bip/address/decoder.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; -import 'package:blockchain_utils/blockchain_utils.dart'; - +import 'package:blockchain_utils/crypto/quick_crypto.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'addr_dec_utils.dart'; /// Enum defining address prefixes for Tezos (XTZ) blockchain addresses. diff --git a/lib/bip/algorand/mnemonic/algorand_mnemonic_decoder.dart b/lib/bip/algorand/mnemonic/algorand_mnemonic_decoder.dart index 81a18f4..919ec47 100644 --- a/lib/bip/algorand/mnemonic/algorand_mnemonic_decoder.dart +++ b/lib/bip/algorand/mnemonic/algorand_mnemonic_decoder.dart @@ -52,7 +52,7 @@ class AlgorandMnemonicDecoder extends MnemonicDecoderBase { final chksumWordIdx = AlgorandMnemonicUtils.computeChecksumWordIndex(entropyBytes); if (chksumWordIdx != chksumWordIdxExp) { - throw MnemonicChecksumError( + throw MnemonicException( 'Invalid checksum (expected ${wordsList.getWordAtIdx(chksumWordIdx)}, ' 'got ${wordsList.getWordAtIdx(chksumWordIdxExp)})'); } diff --git a/lib/bip/bip/bip32/base/bip32_base.dart b/lib/bip/bip/bip32/base/bip32_base.dart index f833596..b229c1f 100644 --- a/lib/bip/bip/bip32/base/bip32_base.dart +++ b/lib/bip/bip/bip32/base/bip32_base.dart @@ -126,7 +126,7 @@ abstract class Bip32Base { final pathInstance = Bip32PathParser.parse(path); if (depth.depth > 0 && pathInstance.isAbsolute) { - throw ArgumentException( + throw const ArgumentException( 'Absolute paths can only be derived from a master key, not child ones'); } Bip32Base derivedObject = this; diff --git a/lib/bip/bip/bip32/base/ibip32_key_derivator.dart b/lib/bip/bip/bip32/base/ibip32_key_derivator.dart index 56c0f48..b317ac8 100644 --- a/lib/bip/bip/bip32/base/ibip32_key_derivator.dart +++ b/lib/bip/bip/bip32/base/ibip32_key_derivator.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_keys.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// An abstract class that defines methods for BIP-32 key derivation. /// diff --git a/lib/bip/bip/bip32/base/ibip32_mst_key_generator.dart b/lib/bip/bip/bip32/base/ibip32_mst_key_generator.dart index ca65300..00adab1 100644 --- a/lib/bip/bip/bip32/base/ibip32_mst_key_generator.dart +++ b/lib/bip/bip/bip32/base/ibip32_mst_key_generator.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// An abstract class that defines a method for generating master keys from a seed. /// diff --git a/lib/bip/bip/bip32/bip32_ex.dart b/lib/bip/bip/bip32/bip32_ex.dart index c296922..ab241f4 100644 --- a/lib/bip/bip/bip32/bip32_ex.dart +++ b/lib/bip/bip/bip32/bip32_ex.dart @@ -9,8 +9,11 @@ class Bip32KeyError implements BlockchainUtilsException { @override final String message; + @override + final Map? details; + /// Creates a `Bip32KeyError` with an optional error message. - const Bip32KeyError(this.message); + const Bip32KeyError(this.message, {this.details}); @override String toString() { @@ -27,8 +30,11 @@ class Bip32PathError implements BlockchainUtilsException { @override final String message; + @override + final Map? details; + /// Creates a `Bip32PathError` with an optional error message. - const Bip32PathError(this.message); + const Bip32PathError(this.message, {this.details}); @override String toString() { diff --git a/lib/bip/bip/bip32/bip32_key_data.dart b/lib/bip/bip/bip32/bip32_key_data.dart index 91f261a..e129d72 100644 --- a/lib/bip/bip/bip32/bip32_key_data.dart +++ b/lib/bip/bip/bip32/bip32_key_data.dart @@ -1,9 +1,5 @@ import 'dart:typed_data'; - -import 'package:blockchain_utils/binary/bit_utils.dart'; -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/compare/compare.dart'; -import 'package:blockchain_utils/numbers/int_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; /// Class container for BIP32 key data constants. @@ -57,7 +53,7 @@ class Bip32FingerPrint { factory Bip32FingerPrint([List? fprint]) { fprint ??= List.from(Bip32KeyDataConst.fingerprintMasterKey); if (fprint.length < fixedLength()) { - throw ArgumentException("Invalid fingerprint length"); + throw const ArgumentException("Invalid fingerprint length"); } fprint = fprint.sublist(0, fixedLength()); return Bip32FingerPrint._(fprint); @@ -77,7 +73,8 @@ class Bip32FingerPrint { /// Get if the fingerprint corresponds to a master key. bool isMasterKey() { - return bytesEqual(toBytes(), Bip32KeyDataConst.fingerprintMasterKey); + return BytesUtils.bytesEqual( + toBytes(), Bip32KeyDataConst.fingerprintMasterKey); } } @@ -132,8 +129,9 @@ class Bip32Depth { /// BIP32 key index class. /// It represents a BIP32 key index. class Bip32KeyIndex { - late int _index; - int get index => _index; + final int index; + + const Bip32KeyIndex._(this.index); /// Harden the specified index and return it. factory Bip32KeyIndex.hardenIndex(int index) { @@ -153,14 +151,14 @@ class Bip32KeyIndex { index, Bip32KeyDataConst.keyIndexHardenedBitNum); } - Bip32KeyIndex(int index) { + factory Bip32KeyIndex(int index) { if (index < 0 || index > Bip32KeyDataConst.keyIndexMaxVal) { throw ArgumentException("Invalid key index ($index)"); } - _index = index; + return Bip32KeyIndex._(index); } - Bip32KeyIndex.fromBytes(List bytes) { - _index = IntUtils.fromBytes(bytes, byteOrder: Endian.little); + factory Bip32KeyIndex.fromBytes(List bytes) { + return Bip32KeyIndex(IntUtils.fromBytes(bytes, byteOrder: Endian.little)); } /// Get the fixed length in bytes. diff --git a/lib/bip/bip/bip32/bip32_key_net_ver.dart b/lib/bip/bip/bip32/bip32_key_net_ver.dart index f9aea0e..3293f5c 100644 --- a/lib/bip/bip/bip32/bip32_key_net_ver.dart +++ b/lib/bip/bip/bip32/bip32_key_net_ver.dart @@ -13,7 +13,7 @@ class Bip32KeyNetVersions { /// constractur for Bip32KeyNetVersions Bip32KeyNetVersions(List pubNetVer, List privNetVer) { if (pubNetVer.length != length || privNetVer.length != length) { - throw ArgumentException("Invalid key net version length"); + throw const ArgumentException("Invalid key net version length"); } _pubNetVer = pubNetVer; diff --git a/lib/bip/bip/bip32/bip32_key_ser.dart b/lib/bip/bip/bip32/bip32_key_ser.dart index ab0b798..9c916b1 100644 --- a/lib/bip/bip/bip32/bip32_key_ser.dart +++ b/lib/bip/bip/bip32/bip32_key_ser.dart @@ -4,10 +4,7 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_ex.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_key_net_ver.dart'; import 'package:blockchain_utils/bip/ecc/keys/i_keys.dart'; -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/compare/compare.dart'; -import 'package:blockchain_utils/numbers/int_utils.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// The `Bip32KeySerConst` class contains constants related to the serialization /// of Bip32 keys. These constants specify the length of serialized public and @@ -118,9 +115,9 @@ class Bip32KeyDeserializer { List serKeyBytes, Bip32KeyNetVersions keyNetVer) { final keyNetVerGot = serKeyBytes.sublist(0, Bip32KeyNetVersions.length); - if (bytesEqual(keyNetVerGot, keyNetVer.public)) { + if (BytesUtils.bytesEqual(keyNetVerGot, keyNetVer.public)) { return true; - } else if (bytesEqual(keyNetVerGot, keyNetVer.private)) { + } else if (BytesUtils.bytesEqual(keyNetVerGot, keyNetVer.private)) { return false; } else { throw Bip32KeyError( diff --git a/lib/bip/bip/bip32/bip32_keys.dart b/lib/bip/bip/bip32/bip32_keys.dart index 6ad3d4f..194f2a4 100644 --- a/lib/bip/bip/bip32/bip32_keys.dart +++ b/lib/bip/bip/bip32/bip32_keys.dart @@ -25,7 +25,7 @@ abstract class Bip32KeyBase { /// Gets the extended representation of the BIP32 key. String get toExtended; - String toHex(); + String toHex({bool lowerCase = true, String? prefix = ""}); } /// Represents a BIP32 public key with associated data such as the elliptic curve type, @@ -91,8 +91,10 @@ class Bip32PublicKey extends Bip32KeyBase { } @override - String toHex() { - return pubKey.toHex(); + String toHex( + {bool withPrefix = true, bool lowerCase = true, String? prefix = ""}) { + return pubKey.toHex( + lowerCase: lowerCase, prefix: prefix, withPrefix: withPrefix); } } @@ -141,14 +143,11 @@ class Bip32PrivateKey extends Bip32KeyBase { EllipticCurveTypes curveType, ) { return Bip32PrivateKey( - IPrivateKey.fromBytes(keyBytes, curveType), - keyData, - keyNetVer, - ); + IPrivateKey.fromBytes(keyBytes, curveType), keyData, keyNetVer); } @override - String toHex() { - return privKey.toHex(); + String toHex({bool lowerCase = true, String? prefix = ""}) { + return privKey.toHex(lowerCase: lowerCase, prefix: prefix); } } diff --git a/lib/bip/bip/bip32/khalow/bip32_kholaw_ed25519_key_derivator.dart b/lib/bip/bip/bip32/khalow/bip32_kholaw_ed25519_key_derivator.dart index c0c6e49..0bc5f03 100644 --- a/lib/bip/bip/bip32/khalow/bip32_kholaw_ed25519_key_derivator.dart +++ b/lib/bip/bip/bip32/khalow/bip32_kholaw_ed25519_key_derivator.dart @@ -1,6 +1,6 @@ import 'dart:typed_data'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_ex.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_keys.dart'; diff --git a/lib/bip/bip/bip32/khalow/bip32_kholaw_key_derivator_base.dart b/lib/bip/bip/bip32/khalow/bip32_kholaw_key_derivator_base.dart index fa06f68..ec49a77 100644 --- a/lib/bip/bip/bip32/khalow/bip32_kholaw_key_derivator_base.dart +++ b/lib/bip/bip/bip32/khalow/bip32_kholaw_key_derivator_base.dart @@ -5,7 +5,7 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_keys.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/edwards.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// Define an abstract class 'Bip32KholawEd25519KeyDerivatorBase' that implements the 'IBip32KeyDerivator' interface. /// This class provides a base for deriving Ed25519 keys with the Kholaw scheme. diff --git a/lib/bip/bip/bip32/khalow/bip32_kholaw_mst_key_generator.dart b/lib/bip/bip/bip32/khalow/bip32_kholaw_mst_key_generator.dart index eb249ec..97d2089 100644 --- a/lib/bip/bip/bip32/khalow/bip32_kholaw_mst_key_generator.dart +++ b/lib/bip/bip/bip32/khalow/bip32_kholaw_mst_key_generator.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/bip/bip32/base/ibip32_mst_key_generator.dar import 'package:blockchain_utils/bip/bip/bip32/slip10/bip32_slip10_mst_key_generator.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// Constants for generating master keys for Bip32KholawEd25519 keys. /// @@ -44,7 +44,7 @@ class Bip32KholawEd25519MstKeyGenerator implements IBip32MstKeyGenerator { @override Tuple, List> generateFromSeed(List seedBytes) { if (seedBytes.length < Bip32KholawMstKeyGeneratorConst.seedMinByteLen) { - throw ArgumentException("Invalid seed length"); + throw const ArgumentException("Invalid seed length"); } final hashDigest = _hashRepeatedly(seedBytes, List.from(Bip32KholawMstKeyGeneratorConst.masterKeyHmacKey)); diff --git a/lib/bip/bip/bip32/slip10/bip32_slip10_key_derivator.dart b/lib/bip/bip/bip32/slip10/bip32_slip10_key_derivator.dart index 6222a83..18fbcea 100644 --- a/lib/bip/bip/bip32/slip10/bip32_slip10_key_derivator.dart +++ b/lib/bip/bip/bip32/slip10/bip32_slip10_key_derivator.dart @@ -1,13 +1,12 @@ import 'dart:typed_data'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/bip/bip32/base/ibip32_key_derivator.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_keys.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_getter.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; /// Constants related to the Bip32 Slip10 Derivator. class Bip32Slip10DerivatorConst { diff --git a/lib/bip/bip/bip32/slip10/bip32_slip10_mst_key_generator.dart b/lib/bip/bip/bip32/slip10/bip32_slip10_mst_key_generator.dart index 6b4aca0..1bf8518 100644 --- a/lib/bip/bip/bip32/slip10/bip32_slip10_mst_key_generator.dart +++ b/lib/bip/bip/bip32/slip10/bip32_slip10_mst_key_generator.dart @@ -3,7 +3,7 @@ import 'package:blockchain_utils/bip/ecc/keys/i_keys.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// Constants used by the Slip-10-based master key generator. /// diff --git a/lib/bip/bip/bip38/bip38_addr.dart b/lib/bip/bip/bip38/bip38_addr.dart index 5e1d0ee..41fa3e6 100644 --- a/lib/bip/bip/bip38/bip38_addr.dart +++ b/lib/bip/bip/bip38/bip38_addr.dart @@ -55,7 +55,7 @@ import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/string/string.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// This class defines a constant value for the length of the address hash. /// diff --git a/lib/bip/bip/bip38/bip38_base.dart b/lib/bip/bip/bip38/bip38_base.dart index d5d857c..4104419 100644 --- a/lib/bip/bip/bip38/bip38_base.dart +++ b/lib/bip/bip/bip38/bip38_base.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:blockchain_utils/bip/bip/bip38/bip38_no_ec.dart'; import 'bip38_ec.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// Helper class for BIP38 encryption and decryption operations. /// diff --git a/lib/bip/bip/bip38/bip38_ec.dart b/lib/bip/bip/bip38/bip38_ec.dart index dc15ae9..d7fd9ad 100644 --- a/lib/bip/bip/bip38/bip38_ec.dart +++ b/lib/bip/bip/bip38/bip38_ec.dart @@ -1,21 +1,15 @@ import 'dart:typed_data'; import 'package:blockchain_utils/base58/base58.dart'; -import 'package:blockchain_utils/numbers/int_utils.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:blockchain_utils/bip/bip/bip38/bip38_addr.dart'; import 'package:blockchain_utils/bip/ecc/keys/ecdsa_keys.dart'; import 'package:blockchain_utils/bip/ecc/keys/secp256k1_keys_ecdsa.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/binary/bit_utils.dart'; -import 'package:blockchain_utils/binary/utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curves.dart'; import 'package:blockchain_utils/crypto/crypto/scrypt/scrypt.dart'; -import 'package:blockchain_utils/compare/compare.dart'; -import 'package:blockchain_utils/string/string.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; // /// Constants for BIP38 encryption and decryption operations. @@ -301,8 +295,8 @@ class Bip38EcKeysGenerator { Secp256k1PublicKeyEcdsa.fromBytes(intPassphraseBytes.sublist(16)); /// Check if the magic number is valid. - if (!bytesEqual(magic, Bip38EcConst.intPassMagicNoLotSeq) && - !bytesEqual(magic, Bip38EcConst.intPassMagicWithLotSeq)) { + if (!BytesUtils.bytesEqual(magic, Bip38EcConst.intPassMagicNoLotSeq) && + !BytesUtils.bytesEqual(magic, Bip38EcConst.intPassMagicWithLotSeq)) { throw ArgumentException( 'Invalid magic (${BytesUtils.toHexString(magic)})'); } @@ -383,7 +377,7 @@ class Bip38EcKeysGenerator { } /// Set the 'lot and sequence' bit if the magic number matches 'with lot/seq'. - if (bytesEqual(magic, Bip38EcConst.intPassMagicWithLotSeq)) { + if (BytesUtils.bytesEqual(magic, Bip38EcConst.intPassMagicWithLotSeq)) { flagbyteInt = BitUtils.setBit(flagbyteInt, Bip38EcConst.flagBitLotSeq); } return IntUtils.toBytes(flagbyteInt, @@ -427,7 +421,7 @@ class Bip38EcDecrypter { final encryptedPart2 = privKeyEncBytes.sublist(23); /// Verify the prefix of the encrypted private key. - if (!bytesEqual(prefix, Bip38EcConst.encKeyPrefix)) { + if (!BytesUtils.bytesEqual(prefix, Bip38EcConst.encKeyPrefix)) { throw ArgumentException( 'Invalid prefix (${BytesUtils.toHexString(prefix)})'); } @@ -453,7 +447,7 @@ class Bip38EcDecrypter { toPub.publicKey.point.toBytes(), flagOptions.item1); /// Verify the extracted address hash matches the expected value. - if (!bytesEqual(addressHash, addressHashGot)) { + if (!BytesUtils.bytesEqual(addressHash, addressHashGot)) { throw ArgumentException( 'Invalid address hash (expected: ${BytesUtils.toHexString(addressHash)}, got: ${BytesUtils.toHexString(addressHashGot)})'); } diff --git a/lib/bip/bip/bip38/bip38_no_ec.dart b/lib/bip/bip/bip38/bip38_no_ec.dart index 02ece3d..f4936a6 100644 --- a/lib/bip/bip/bip38/bip38_no_ec.dart +++ b/lib/bip/bip/bip38/bip38_no_ec.dart @@ -3,12 +3,9 @@ import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:blockchain_utils/bip/bip/bip38/bip38_addr.dart'; import 'package:blockchain_utils/bip/ecc/keys/secp256k1_keys_ecdsa.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/scrypt/scrypt.dart'; -import 'package:blockchain_utils/compare/compare.dart'; -import 'package:blockchain_utils/string/string.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; /// Constants for BIP38 encryption and decryption without ECDSA. /// @@ -207,7 +204,7 @@ class Bip38NoEcDecrypter { final encryptedHalf2 = privKeyEncBytes.sublist(23); // Check prefix and flagbyte - if (!bytesEqual(prefix, Bip38NoEcConst.encKeyPrefix)) { + if (!BytesUtils.bytesEqual(prefix, Bip38NoEcConst.encKeyPrefix)) { throw ArgumentException( 'Invalid prefix (${BytesUtils.toHexString(prefix)})'); } @@ -235,7 +232,7 @@ class Bip38NoEcDecrypter { // Verify the address hash final addressHashGot = Bip38NoEcUtils.addressHash(privKeyBytes, pubKeyMode); - if (!bytesEqual(addressHash, addressHashGot)) { + if (!BytesUtils.bytesEqual(addressHash, addressHashGot)) { throw ArgumentException( 'Invalid address hash (expected: ${BytesUtils.toHexString(addressHash)}, ' 'got: ${BytesUtils.toHexString(addressHashGot)})'); diff --git a/lib/bip/bip/bip39/bip39_mnemonic_decoder.dart b/lib/bip/bip/bip39/bip39_mnemonic_decoder.dart index 1667190..c8d8dcf 100644 --- a/lib/bip/bip/bip39/bip39_mnemonic_decoder.dart +++ b/lib/bip/bip/bip39/bip39_mnemonic_decoder.dart @@ -1,8 +1,7 @@ -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic.dart'; import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic_utils.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/binary/utils.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_decoder_base.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_ex.dart'; @@ -112,12 +111,12 @@ class Bip39MnemonicDecoder extends MnemonicDecoderBase { throw ArgumentException('Mnemonic words count is not valid ($wCount)'); } final wordsList = findLanguage(mnemonicObj).item1; - final mnemonicBinStr = _mnemonicToBinaryStr(mnemonicObj, wordsList); + final mnemonicBinStr = mnemonicToBinaryStr(mnemonicObj, wordsList); final checksumBinStr = mnemonicBinStr .substring(mnemonicBinStr.length - _getChecksumLen(mnemonicBinStr)); final checksumBinStrGot = _computeChecksumBinaryStr(mnemonicBinStr); if (checksumBinStr != checksumBinStrGot) { - throw MnemonicChecksumError( + throw MnemonicException( 'Invalid checksum (expected $checksumBinStr, got $checksumBinStrGot)'); } @@ -145,7 +144,7 @@ class Bip39MnemonicDecoder extends MnemonicDecoderBase { } /// mnemonic to binary - String _mnemonicToBinaryStr(Mnemonic mnemonic, MnemonicWordsList wordsList) { + String mnemonicToBinaryStr(Mnemonic mnemonic, MnemonicWordsList wordsList) { final mnemonicBinStr = mnemonic.toList().map((word) { final wordIdx = wordsList.getWordIdx(word); return BigintUtils.toBinary( diff --git a/lib/bip/bip/bip39/bip39_mnemonic_encoder.dart b/lib/bip/bip/bip39/bip39_mnemonic_encoder.dart index 43e604f..559c0a6 100644 --- a/lib/bip/bip/bip39/bip39_mnemonic_encoder.dart +++ b/lib/bip/bip/bip39/bip39_mnemonic_encoder.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/bip/bip39/bip39_entropy_generator.dart'; import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic.dart'; import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic_utils.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_encoder_base.dart'; import 'package:blockchain_utils/exception/exception.dart'; diff --git a/lib/bip/bip/bip39/bip39_mnemonic_utils.dart b/lib/bip/bip/bip39/bip39_mnemonic_utils.dart index 9a228d3..8368d9e 100644 --- a/lib/bip/bip/bip39/bip39_mnemonic_utils.dart +++ b/lib/bip/bip/bip39/bip39_mnemonic_utils.dart @@ -1,6 +1,10 @@ +import 'package:blockchain_utils/bip/algorand/mnemonic/algorand_mnemonic.dart'; +import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_utils.dart'; -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/utils/utils.dart'; +import 'bip39_mnemonic.dart'; /// Retrieves a list of BIP39 words based on the specified language. /// @@ -14,7 +18,7 @@ class Bip39WordsListGetter extends MnemonicWordsListGetterBase { if (language is! Bip39Languages && language is! AlgorandLanguages && language is! ElectrumV2Languages) { - throw ArgumentException( + throw const ArgumentException( "Language is not an enumerative of Bip39Languages"); } return loadWordsList(language, Bip39MnemonicConst.wordsListNum); diff --git a/lib/bip/bip/bip39/bip39_mnemonic_validator.dart b/lib/bip/bip/bip39/bip39_mnemonic_validator.dart index 6989e92..30ee90d 100644 --- a/lib/bip/bip/bip39/bip39_mnemonic_validator.dart +++ b/lib/bip/bip/bip39/bip39_mnemonic_validator.dart @@ -1,5 +1,6 @@ import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic.dart'; import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic_decoder.dart'; +import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_validator.dart'; /// Validates BIP39 mnemonics based on a specified language. @@ -10,10 +11,21 @@ import 'package:blockchain_utils/bip/mnemonic/mnemonic_validator.dart'; /// language's word list and can be successfully decoded. /// The [isValid] method can be used to check the validity of a given /// mnemonic phrase. -class Bip39MnemonicValidator extends MnemonicValidator { +class Bip39MnemonicValidator extends MnemonicValidator { /// Creates a new instance of the Bip39MnemonicValidator. /// /// The [language] parameter specifies the language used for the word list. Bip39MnemonicValidator([Bip39Languages? language]) : super(Bip39MnemonicDecoder(language)); + + bool validateWords(String mnemonic) { + try { + final mn = Mnemonic.fromString(mnemonic); + final language = decoder.findLanguage(mn).item1; + decoder.mnemonicToBinaryStr(mn, language); + return true; + } catch (e) { + return false; + } + } } diff --git a/lib/bip/bip/bip39/bip39_seed_generator.dart b/lib/bip/bip/bip39/bip39_seed_generator.dart index 2e76a6c..25cc498 100644 --- a/lib/bip/bip/bip39/bip39_seed_generator.dart +++ b/lib/bip/bip/bip39/bip39_seed_generator.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic_validator.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; -import 'package:blockchain_utils/string/string.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// Constants related to Bip39 seed generation. class Bip39SeedGeneratorConst { diff --git a/lib/bip/bip/bip44/base/bip44_base.dart b/lib/bip/bip/bip44/base/bip44_base.dart index 788859e..209cf09 100644 --- a/lib/bip/bip/bip44/base/bip44_base.dart +++ b/lib/bip/bip/bip44/base/bip44_base.dart @@ -11,7 +11,7 @@ import 'package:blockchain_utils/bip/bip/conf/bip_coin_conf.dart'; import 'package:blockchain_utils/bip/cardano/bip32/cardano_icarus_bip32.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'bip44_keys.dart'; @@ -112,7 +112,7 @@ abstract class Bip44Base { bip = Bip32Slip10Nist256p1.fromSeed(seedBytes, coin.keyNetVer); break; default: - throw ArgumentException("invaid type"); + throw const ArgumentException("invaid type"); } final validate = _validate(bip, coin); bip32 = validate.item1; @@ -146,7 +146,7 @@ abstract class Bip44Base { bip = Bip32Slip10Nist256p1.fromExtendedKey(extendedKey, coin.keyNetVer); break; default: - throw ArgumentException("invaid type"); + throw const ArgumentException("invaid type"); } final validate = _validate(bip, coin); bip32 = validate.item1; @@ -184,7 +184,7 @@ abstract class Bip44Base { keyData: keyData, keyNetVer: coin.keyNetVer); break; default: - throw ArgumentException("invaid type"); + throw const ArgumentException("invaid type"); } final validate = _validate(bip, coin); bip32 = validate.item1; @@ -222,7 +222,7 @@ abstract class Bip44Base { keyData: keyData, keyNetVer: coin.keyNetVer); break; default: - throw ArgumentException("invaid type"); + throw const ArgumentException("invaid type"); } final validate = _validate(bip, coin); bip32 = validate.item1; diff --git a/lib/bip/bip/bip44/base/bip44_base_ex.dart b/lib/bip/bip/bip44/base/bip44_base_ex.dart index b173cf8..19f1cf0 100644 --- a/lib/bip/bip/bip44/base/bip44_base_ex.dart +++ b/lib/bip/bip/bip44/base/bip44_base_ex.dart @@ -9,10 +9,13 @@ class Bip44DepthError implements BlockchainUtilsException { @override final String message; + @override + final Map? details; + /// Create a `Bip44DepthError` with an optional error message. /// /// - [message]: An optional error message to provide more context. - const Bip44DepthError(this.message); + const Bip44DepthError(this.message, {this.details}); @override String toString() { diff --git a/lib/bip/bip/bip44/base/bip44_keys.dart b/lib/bip/bip/bip44/base/bip44_keys.dart index 82b7227..a125843 100644 --- a/lib/bip/bip/bip44/base/bip44_keys.dart +++ b/lib/bip/bip/bip44/base/bip44_keys.dart @@ -1,7 +1,6 @@ -import 'package:blockchain_utils/bip/address/ada/ada_shelley_addr.dart'; import 'package:blockchain_utils/bip/address/encoder.dart'; +import 'package:blockchain_utils/bip/address/encoders.dart'; import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; -import 'package:blockchain_utils/bip/address/xmr_addr.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_keys.dart'; import 'package:blockchain_utils/bip/bip/conf/bip_coin_conf.dart'; @@ -68,12 +67,17 @@ class Bip44PublicKey { String get toAddress { BlockchainAddressEncoder encoder = coinConf.encoder(); if (encoder is AdaShelleyAddrEncoder) { - throw ArgumentException( + throw const ArgumentException( 'Use the CardanoShelley class to get Cardano Shelley addresses'); } // Exception for Monero if (encoder is XmrAddrEncoder) { - throw ArgumentException('Use the Monero class to get Monero addresses'); + throw const ArgumentException( + 'Use the Monero class to get Monero addresses'); + } + if (encoder is TonAddrEncoder) { + throw const ArgumentException( + 'Ton Address must be generated with hash of contract state. use TonAddrEncoder to encode address.'); } return encoder.encodeKey( pubKey.pubKey.compressed, coinConf.getParams(pubKey)); diff --git a/lib/bip/bip/conf/bip44/bip44_coins.dart b/lib/bip/bip/conf/bip44/bip44_coins.dart index d7789a1..49e3c70 100644 --- a/lib/bip/bip/conf/bip44/bip44_coins.dart +++ b/lib/bip/bip/conf/bip44/bip44_coins.dart @@ -332,6 +332,12 @@ class Bip44Coins implements CryptoCoins { /// Zcash Testnet static const zcashTestnet = Bip44Coins._('zcashTestnet'); + /// Ton Testnet + static const tonTestnet = Bip44Coins._('tonTestnet'); + + /// Ton Testnet + static const tonMainnet = Bip44Coins._('tonMainnet'); + // Fields and methods @override @@ -448,7 +454,14 @@ class Bip44Coins implements CryptoCoins { Bip44Coins.zcash: Bip44Conf.zcashMainNet, Bip44Coins.zcashTestnet: Bip44Conf.zcashTestNet, Bip44Coins.zilliqa: Bip44Conf.zilliqa, + Bip44Coins.tonTestnet: Bip44Conf.tonTestnet, + Bip44Coins.tonMainnet: Bip44Conf.tonMainnet, }; @override BipProposal get proposal => BipProposal.bip44; + + @override + String toString() { + return "Bip44Coins.$name"; + } } diff --git a/lib/bip/bip/conf/bip44/bip44_conf.dart b/lib/bip/bip/conf/bip44/bip44_conf.dart index 3af1938..735bf41 100644 --- a/lib/bip/bip/conf/bip44/bip44_conf.dart +++ b/lib/bip/bip/conf/bip44/bip44_conf.dart @@ -1,29 +1,4 @@ -import 'package:blockchain_utils/bip/address/ada/ada_byron_addr.dart'; -import 'package:blockchain_utils/bip/address/algo_addr.dart'; -import 'package:blockchain_utils/bip/address/aptos_addr.dart'; -import 'package:blockchain_utils/bip/address/atom_addr.dart'; -import 'package:blockchain_utils/bip/address/avax_addr.dart'; -import 'package:blockchain_utils/bip/address/egld_addr.dart'; -import 'package:blockchain_utils/bip/address/eos_addr.dart'; -import 'package:blockchain_utils/bip/address/ergo.dart'; -import 'package:blockchain_utils/bip/address/eth_addr.dart'; -import 'package:blockchain_utils/bip/address/fil_addr.dart'; -import 'package:blockchain_utils/bip/address/icx_addr.dart'; -import 'package:blockchain_utils/bip/address/inj_addr.dart'; -import 'package:blockchain_utils/bip/address/nano_addr.dart'; -import 'package:blockchain_utils/bip/address/near_addr.dart'; -import 'package:blockchain_utils/bip/address/neo_addr.dart'; -import 'package:blockchain_utils/bip/address/okex_addr.dart'; -import 'package:blockchain_utils/bip/address/one_addr.dart'; -import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; -import 'package:blockchain_utils/bip/address/sol_addr.dart'; -import 'package:blockchain_utils/bip/address/substrate_addr.dart'; -import 'package:blockchain_utils/bip/address/trx_addr.dart'; -import 'package:blockchain_utils/bip/address/xlm_addr.dart'; -import 'package:blockchain_utils/bip/address/xmr_addr.dart'; -import 'package:blockchain_utils/bip/address/xrp_addr.dart'; -import 'package:blockchain_utils/bip/address/xtz_addr.dart'; -import 'package:blockchain_utils/bip/address/zil_addr.dart'; +import 'package:blockchain_utils/bip/address/encoders.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_const.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_key_net_ver.dart'; import 'package:blockchain_utils/bip/bip/conf/bip_bitcoin_cash_conf.dart'; @@ -1352,4 +1327,27 @@ class Bip44Conf { addressEncoder: ([dynamic kwargs]) => ZilAddrEncoder(), addrParams: {}, ); + + static final CoinConfig tonMainnet = CoinConfig( + coinNames: CoinsConf.tonMainnet.coinName, + coinIdx: Slip44.ton, + isTestnet: false, + defPath: derPathHardenedShort, + keyNetVer: Bip44Conf.bip44BtcKeyNetVerMain, + wifNetVer: null, + type: EllipticCurveTypes.ed25519, + addressEncoder: ([dynamic kwargs]) => TonAddrEncoder(), + addrParams: {"workchain": CoinsConf.tonMainnet.params.workchain}, + ); + static final CoinConfig tonTestnet = CoinConfig( + coinNames: CoinsConf.tonTestnet.coinName, + coinIdx: Slip44.testnet, + isTestnet: true, + defPath: derPathHardenedShort, + keyNetVer: Bip44Conf.bip44BtcKeyNetVerMain, + wifNetVer: null, + type: EllipticCurveTypes.ed25519, + addressEncoder: ([dynamic kwargs]) => TonAddrEncoder(), + addrParams: {"workchain": CoinsConf.tonTestnet.params.workchain}, + ); } diff --git a/lib/bip/bip/conf/bip_coins.dart b/lib/bip/bip/conf/bip_coins.dart index 8df6b86..5f542bd 100644 --- a/lib/bip/bip/conf/bip_coins.dart +++ b/lib/bip/bip/conf/bip_coins.dart @@ -1,5 +1,16 @@ +import 'package:blockchain_utils/bip/bip/bip32/bip32.dart'; +import 'package:blockchain_utils/bip/bip/bip44/bip44_base.dart'; +import 'package:blockchain_utils/bip/bip/bip49/bip49_base.dart'; +import 'package:blockchain_utils/bip/bip/bip84/bip84_base.dart'; +import 'package:blockchain_utils/bip/bip/bip86/bip86_base.dart'; +import 'package:blockchain_utils/bip/bip/conf/bip44/bip44_coins.dart'; +import 'package:blockchain_utils/bip/bip/conf/bip49/bip49_coins.dart'; +import 'package:blockchain_utils/bip/bip/conf/bip84/bip84_coins.dart'; +import 'package:blockchain_utils/bip/bip/conf/bip86/bip86_coins.dart'; import 'package:blockchain_utils/bip/bip/conf/bip_coin_conf.dart'; -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/bip/cardano/cip1852/cip1852.dart'; +import 'package:blockchain_utils/bip/cardano/cip1852/conf/cip1852_coins.dart'; +import 'package:blockchain_utils/exception/exception.dart'; /// An abstract class representing a collection of cryptocurrency coins. /// diff --git a/lib/bip/cardano/bip32/cardano_byron_legacy_key_derivator.dart b/lib/bip/cardano/bip32/cardano_byron_legacy_key_derivator.dart index c4da070..a300d78 100644 --- a/lib/bip/cardano/bip32/cardano_byron_legacy_key_derivator.dart +++ b/lib/bip/cardano/bip32/cardano_byron_legacy_key_derivator.dart @@ -1,12 +1,10 @@ import 'dart:typed_data'; - -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_keys.dart'; import 'package:blockchain_utils/bip/bip/bip32/khalow/bip32_kholaw_key_derivator_base.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_getter.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; -import 'package:blockchain_utils/binary/binary_operation.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/edwards.dart'; /// A class responsible for deriving key pairs using the Cardano Byron legacy key derivation process diff --git a/lib/bip/cardano/bip32/cardano_byron_legacy_mst_key_generator.dart b/lib/bip/cardano/bip32/cardano_byron_legacy_mst_key_generator.dart index 8a535cf..2a51959 100644 --- a/lib/bip/cardano/bip32/cardano_byron_legacy_mst_key_generator.dart +++ b/lib/bip/cardano/bip32/cardano_byron_legacy_mst_key_generator.dart @@ -1,9 +1,8 @@ import 'package:blockchain_utils/bip/bip/bip32/base/ibip32_mst_key_generator.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/binary/bit_utils.dart'; import 'package:blockchain_utils/cbor/types/bytes.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// A class that holds constants related to the Cardano Byron legacy master key generation process. class CardanoByronLegacyMstKeyGeneratorConst { diff --git a/lib/bip/cardano/bip32/cardano_icarus_mst_key_generator.dart b/lib/bip/cardano/bip32/cardano_icarus_mst_key_generator.dart index d1909ee..bb6b48e 100644 --- a/lib/bip/cardano/bip32/cardano_icarus_mst_key_generator.dart +++ b/lib/bip/cardano/bip32/cardano_icarus_mst_key_generator.dart @@ -1,13 +1,11 @@ import 'package:blockchain_utils/bip/bip/bip32/base/ibip32_mst_key_generator.dart'; import 'package:blockchain_utils/bip/bip/bip32/slip10/bip32_slip10_mst_key_generator.dart'; import 'package:blockchain_utils/bip/ecc/keys/ed25519_kholaw_keys.dart'; -import 'package:blockchain_utils/binary/bit_utils.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:blockchain_utils/crypto/crypto/hmac/hmac.dart'; import 'package:blockchain_utils/crypto/crypto/pbkdf2/pbkdf2.dart'; -import 'package:blockchain_utils/string/string.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; /// A class that holds constants related to the Cardano Icarus master key generation process. class CardanoIcarusMasterKeyGeneratorConst { diff --git a/lib/bip/cardano/byron/cardano_byron_legacy.dart b/lib/bip/cardano/byron/cardano_byron_legacy.dart index acb2429..767fb72 100644 --- a/lib/bip/cardano/byron/cardano_byron_legacy.dart +++ b/lib/bip/cardano/byron/cardano_byron_legacy.dart @@ -59,7 +59,7 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_keys.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_path.dart'; import 'package:blockchain_utils/bip/cardano/bip32/cardano_byron_legacy_bip32.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/string/string.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// A class that holds constants related to the Cardano Byron legacy key derivation process. class CardanoByronLegacyConst { diff --git a/lib/bip/cardano/shelley/cardano_shelley.dart b/lib/bip/cardano/shelley/cardano_shelley.dart index 42e2e69..8ecb79f 100644 --- a/lib/bip/cardano/shelley/cardano_shelley.dart +++ b/lib/bip/cardano/shelley/cardano_shelley.dart @@ -17,7 +17,8 @@ class CardanoShelley { /// Throws an `ArgumentException` if the provided Bip object is not a Cip1852 instance. factory CardanoShelley.fromCip1852Object(Bip44Base bip) { if (bip is! Cip1852) { - throw ArgumentException("The Bip object shall be a Cip1852 instance"); + throw const ArgumentException( + "The Bip object shall be a Cip1852 instance"); } return CardanoShelley(bip, __deriveStakingKeys(bip)); } @@ -31,10 +32,12 @@ class CardanoShelley { /// Throws an `ArgumentException` if the provided Bip object is below the account level or if `bipSk` is not at the address index level. CardanoShelley(Bip44Base bip, Bip44Base bipSk) { if (bip.level.value < Bip44Levels.account.value) { - throw ArgumentException("The bipObj shall not be below account level"); + throw const ArgumentException( + "The bipObj shall not be below account level"); } if (bipSk.level != Bip44Levels.addressIndex) { - throw ArgumentException("The bipSkObj shall be of address index level"); + throw const ArgumentException( + "The bipSkObj shall be of address index level"); } bip44 = bip; bip44Sk = bipSk; diff --git a/lib/bip/coin_conf/coin_conf.dart b/lib/bip/coin_conf/coin_conf.dart index 85c2297..c1f1922 100644 --- a/lib/bip/coin_conf/coin_conf.dart +++ b/lib/bip/coin_conf/coin_conf.dart @@ -77,6 +77,7 @@ class CoinParams { // Address versions this.addrVer, + this.workchain, }); // Network versions for Pay-to-Public-Key-Hash (P2PKH) addresses @@ -125,4 +126,6 @@ class CoinParams { // Address versions final List? addrVer; + // Ton workchain ID + final int? workchain; } diff --git a/lib/bip/coin_conf/coins_conf.dart b/lib/bip/coin_conf/coins_conf.dart index 3a56322..471fe06 100644 --- a/lib/bip/coin_conf/coins_conf.dart +++ b/lib/bip/coin_conf/coins_conf.dart @@ -678,4 +678,12 @@ class CoinsConf { addrHrp: Slip173.zilliqa, ), ); + + static const CoinConf tonTestnet = CoinConf( + coinName: CoinNames("The Open Network", "tTON"), + params: CoinParams(workchain: -1)); + + static const CoinConf tonMainnet = CoinConf( + coinName: CoinNames("The Open Network", "TON"), + params: CoinParams(workchain: 0)); } diff --git a/lib/bip/ecc/keys/ed25519_blake2b_keys.dart b/lib/bip/ecc/keys/ed25519_blake2b_keys.dart index 8ee7340..1305d28 100644 --- a/lib/bip/ecc/keys/ed25519_blake2b_keys.dart +++ b/lib/bip/ecc/keys/ed25519_blake2b_keys.dart @@ -52,7 +52,7 @@ OF THE POSSIBILITY OF SUCH DAMAGE. */ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/ecc/keys/ed25519_keys.dart'; import 'package:blockchain_utils/bip/ecc/keys/i_keys.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; @@ -132,8 +132,13 @@ class Ed25519Blake2bPublicKey implements IPublicKey { } @override - String toHex() { - return BytesUtils.toHexString(compressed); + String toHex( + {bool withPrefix = true, bool lowerCase = true, String? prefix = ""}) { + List key = _publicKey.point.toBytes(); + if (withPrefix) { + key = compressed; + } + return BytesUtils.toHexString(key, prefix: prefix, lowerCase: lowerCase); } } @@ -149,7 +154,7 @@ class Ed25519Blake2bPrivateKey implements IPrivateKey { /// Then, it initializes an EdDSA private key using the Edward generator and BLAKE2b hash function. factory Ed25519Blake2bPrivateKey.fromBytes(List keyBytes) { if (keyBytes.length != Ed25519KeysConst.privKeyByteLen) { - throw ArgumentException("invalid private key length"); + throw const ArgumentException("invalid private key length"); } final edwardGenerator = Curves.generatorED25519; final eddsaPrivateKey = @@ -192,7 +197,7 @@ class Ed25519Blake2bPrivateKey implements IPrivateKey { } @override - String toHex() { - return BytesUtils.toHexString(raw); + String toHex({bool lowerCase = true, String? prefix = ""}) { + return BytesUtils.toHexString(raw, lowerCase: lowerCase, prefix: prefix); } } diff --git a/lib/bip/ecc/keys/ed25519_keys.dart b/lib/bip/ecc/keys/ed25519_keys.dart index ac51cb5..255ab46 100644 --- a/lib/bip/ecc/keys/ed25519_keys.dart +++ b/lib/bip/ecc/keys/ed25519_keys.dart @@ -1,6 +1,5 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; -import 'package:blockchain_utils/compare/compare.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curves.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/eddsa/privatekey.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/eddsa/publickey.dart'; @@ -39,8 +38,8 @@ class Ed25519PublicKey implements IPublicKey { if (keyBytes.length == Ed25519KeysConst.pubKeyByteLen + Ed25519KeysConst.pubKeyPrefix.length) { final prefix = keyBytes.sublist(0, Ed25519KeysConst.pubKeyPrefix.length); - if (bytesEqual(prefix, Ed25519KeysConst.pubKeyPrefix) || - bytesEqual(prefix, Ed25519KeysConst.xrpPubKeyPrefix)) { + if (BytesUtils.bytesEqual(prefix, Ed25519KeysConst.pubKeyPrefix) || + BytesUtils.bytesEqual(prefix, Ed25519KeysConst.xrpPubKeyPrefix)) { keyBytes = keyBytes.sublist(1); } } @@ -97,8 +96,13 @@ class Ed25519PublicKey implements IPublicKey { } @override - String toHex() { - return BytesUtils.toHexString(compressed); + String toHex( + {bool withPrefix = true, bool lowerCase = true, String? prefix = ""}) { + List key = _publicKey.point.toBytes(); + if (withPrefix) { + key = compressed; + } + return BytesUtils.toHexString(key, prefix: prefix, lowerCase: lowerCase); } } @@ -113,7 +117,7 @@ class Ed25519PrivateKey implements IPrivateKey { /// Then, it initializes an EdDSA private key using the Edward generator and SHA512 hash function. factory Ed25519PrivateKey.fromBytes(List keyBytes) { if (keyBytes.length != Ed25519KeysConst.privKeyByteLen) { - throw ArgumentException("invalid private key length"); + throw const ArgumentException("invalid private key length"); } final edwardGenerator = Curves.generatorED25519; final eddsaPrivateKey = @@ -157,7 +161,7 @@ class Ed25519PrivateKey implements IPrivateKey { } @override - String toHex() { - return BytesUtils.toHexString(raw); + String toHex({bool lowerCase = true, String? prefix = ""}) { + return BytesUtils.toHexString(raw, lowerCase: lowerCase, prefix: prefix); } } diff --git a/lib/bip/ecc/keys/ed25519_kholaw_keys.dart b/lib/bip/ecc/keys/ed25519_kholaw_keys.dart index 399d2b0..ff80a00 100644 --- a/lib/bip/ecc/keys/ed25519_kholaw_keys.dart +++ b/lib/bip/ecc/keys/ed25519_kholaw_keys.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/ecc/keys/i_keys.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; import 'package:blockchain_utils/bip/ecc/keys/ed25519_keys.dart'; @@ -85,8 +85,13 @@ class Ed25519KholawPublicKey implements IPublicKey { } @override - String toHex() { - return BytesUtils.toHexString(compressed); + String toHex( + {bool withPrefix = true, bool lowerCase = true, String? prefix = ""}) { + List key = _publicKey.point.toBytes(); + if (withPrefix) { + key = compressed; + } + return BytesUtils.toHexString(key, prefix: prefix, lowerCase: lowerCase); } } @@ -104,7 +109,7 @@ class Ed25519KholawPrivateKey implements IPrivateKey { /// and stores any extended key data. factory Ed25519KholawPrivateKey.fromBytes(List keyBytes) { if (keyBytes.length != Ed25519KholawKeysConst.privKeyByteLen) { - throw ArgumentException("invalid private key length"); + throw const ArgumentException("invalid private key length"); } final edwardGenerator = Curves.generatorED25519; final eddsaPrivateKey = @@ -149,7 +154,7 @@ class Ed25519KholawPrivateKey implements IPrivateKey { } @override - String toHex() { - return BytesUtils.toHexString(raw); + String toHex({bool lowerCase = true, String? prefix = ""}) { + return BytesUtils.toHexString(raw, lowerCase: lowerCase, prefix: prefix); } } diff --git a/lib/bip/ecc/keys/ed25519_monero_keys.dart b/lib/bip/ecc/keys/ed25519_monero_keys.dart index d7c4214..dacb726 100644 --- a/lib/bip/ecc/keys/ed25519_monero_keys.dart +++ b/lib/bip/ecc/keys/ed25519_monero_keys.dart @@ -52,7 +52,7 @@ OF THE POSSIBILITY OF SUCH DAMAGE. */ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/ecc/keys/i_keys.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; import 'package:blockchain_utils/bip/ecc/keys/ed25519_keys.dart'; @@ -124,8 +124,13 @@ class Ed25519MoneroPublicKey implements IPublicKey { } @override - String toHex() { - return BytesUtils.toHexString(compressed); + String toHex( + {bool withPrefix = true, bool lowerCase = true, String? prefix = ""}) { + List key = _publicKey.point.toBytes(); + if (withPrefix) { + key = compressed; + } + return BytesUtils.toHexString(key, prefix: prefix, lowerCase: lowerCase); } } @@ -141,7 +146,7 @@ class Ed25519MoneroPrivateKey implements IPrivateKey { /// Then, it initializes an EdDSA private key using the Ed25519 generator and the specified keyBytes. factory Ed25519MoneroPrivateKey.fromBytes(List keyBytes) { if (keyBytes.length != Ed25519KeysConst.privKeyByteLen) { - throw ArgumentException("invalid private key length"); + throw const ArgumentException("invalid private key length"); } final gn = Curves.generatorED25519; final prv = EDDSAPrivateKey.fromKhalow(gn, keyBytes); @@ -184,7 +189,7 @@ class Ed25519MoneroPrivateKey implements IPrivateKey { } @override - String toHex() { - return BytesUtils.toHexString(raw); + String toHex({bool lowerCase = true, String? prefix = ""}) { + return BytesUtils.toHexString(raw, lowerCase: lowerCase, prefix: prefix); } } diff --git a/lib/bip/ecc/keys/i_keys.dart b/lib/bip/ecc/keys/i_keys.dart index fd848f4..1276a40 100644 --- a/lib/bip/ecc/keys/i_keys.dart +++ b/lib/bip/ecc/keys/i_keys.dart @@ -68,7 +68,8 @@ abstract class IPublicKey { /// Get the abstract point representation of the public key. AbstractPoint get point; - String toHex(); + String toHex( + {bool withPrefix = true, bool lowerCase = true, String? prefix = ""}); } /// An abstract class representing a generic private key interface for different elliptic curve types. @@ -121,5 +122,5 @@ abstract class IPrivateKey { } } - String toHex(); + String toHex({bool lowerCase = true, String? prefix = ""}); } diff --git a/lib/bip/ecc/keys/nist256p1_keys.dart b/lib/bip/ecc/keys/nist256p1_keys.dart index 4dd7d57..2856248 100644 --- a/lib/bip/ecc/keys/nist256p1_keys.dart +++ b/lib/bip/ecc/keys/nist256p1_keys.dart @@ -52,7 +52,7 @@ OF THE POSSIBILITY OF SUCH DAMAGE. */ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/ecc/keys/ecdsa_keys.dart'; import 'package:blockchain_utils/bip/ecc/keys/i_keys.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; @@ -123,8 +123,10 @@ class Nist256p1PublicKey implements IPublicKey { } @override - String toHex() { - return BytesUtils.toHexString(compressed); + String toHex( + {bool withPrefix = true, bool lowerCase = true, String? prefix = ""}) { + return BytesUtils.toHexString(compressed, + prefix: prefix, lowerCase: lowerCase); } } @@ -176,7 +178,7 @@ class Nist256p1PrivateKey implements IPrivateKey { } @override - String toHex() { - return BytesUtils.toHexString(raw); + String toHex({bool lowerCase = true, String? prefix = ""}) { + return BytesUtils.toHexString(raw, lowerCase: lowerCase, prefix: prefix); } } diff --git a/lib/bip/ecc/keys/secp256k1_keys_ecdsa.dart b/lib/bip/ecc/keys/secp256k1_keys_ecdsa.dart index a7b7b90..8d6db50 100644 --- a/lib/bip/ecc/keys/secp256k1_keys_ecdsa.dart +++ b/lib/bip/ecc/keys/secp256k1_keys_ecdsa.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/ecc/keys/ecdsa_keys.dart'; import 'package:blockchain_utils/bip/ecc/keys/i_keys.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; @@ -70,8 +70,10 @@ class Secp256k1PublicKeyEcdsa implements IPublicKey { } @override - String toHex() { - return BytesUtils.toHexString(compressed); + String toHex( + {bool withPrefix = true, bool lowerCase = true, String? prefix = ""}) { + return BytesUtils.toHexString(compressed, + prefix: prefix, lowerCase: lowerCase); } } @@ -123,7 +125,7 @@ class Secp256k1PrivateKeyEcdsa implements IPrivateKey { } @override - String toHex() { - return BytesUtils.toHexString(raw); + String toHex({bool lowerCase = true, String? prefix = ""}) { + return BytesUtils.toHexString(raw, lowerCase: lowerCase, prefix: prefix); } } diff --git a/lib/bip/ecc/keys/sr25519_keys.dart b/lib/bip/ecc/keys/sr25519_keys.dart index ee7354c..59d65f3 100644 --- a/lib/bip/ecc/keys/sr25519_keys.dart +++ b/lib/bip/ecc/keys/sr25519_keys.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/ecc/keys/i_keys.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/ristretto_point.dart'; @@ -72,8 +72,10 @@ class Sr25519PublicKey implements IPublicKey { } @override - String toHex() { - return BytesUtils.toHexString(compressed); + String toHex( + {bool withPrefix = true, bool lowerCase = true, String? prefix = ""}) { + return BytesUtils.toHexString(compressed, + prefix: prefix, lowerCase: lowerCase); } } @@ -124,7 +126,7 @@ class Sr25519PrivateKey implements IPrivateKey { } @override - String toHex() { - return BytesUtils.toHexString(raw); + String toHex({bool lowerCase = true, String? prefix = ""}) { + return BytesUtils.toHexString(raw, lowerCase: lowerCase, prefix: prefix); } } diff --git a/lib/bip/electrum/electrum_v1.dart b/lib/bip/electrum/electrum_v1.dart index 10411c9..bc29fac 100644 --- a/lib/bip/electrum/electrum_v1.dart +++ b/lib/bip/electrum/electrum_v1.dart @@ -1,7 +1,7 @@ import 'dart:typed_data'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; @@ -10,7 +10,6 @@ import 'package:blockchain_utils/bip/ecc/keys/ecdsa_keys.dart'; import 'package:blockchain_utils/bip/ecc/keys/secp256k1_keys_ecdsa.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curves.dart'; -import 'package:blockchain_utils/string/string.dart'; /// Electrum V1 is a class that represents a pair of public and private keys for the Secp256k1 elliptic curve. class ElectrumV1 { @@ -45,7 +44,7 @@ class ElectrumV1 { /// Get the master private key, throwing an exception if it's a public-only key. IPrivateKey get masterPrivateKey { if (isPublicOnly) { - throw MessageException( + throw const MessageException( 'Public-only deterministic keys have no private half'); } return privateKey!; @@ -59,7 +58,7 @@ class ElectrumV1 { /// Get a private key for a specific change and address index, throwing an exception if it's a public-only key. IPrivateKey getPrivateKey(int changeIndex, int addrIndex) { if (isPublicOnly) { - throw MessageException( + throw const MessageException( 'Public-only deterministic keys have no private half'); } return _derivePrivateKey(changeIndex, addrIndex); diff --git a/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_generator.dart b/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_generator.dart index 16e1a19..fbf3a87 100644 --- a/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_generator.dart +++ b/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_generator.dart @@ -43,7 +43,7 @@ class ElectrumV1MnemonicGenerator { ElectrumV1WordsNum.values .firstWhere((element) => element.value == wordsNum); } on StateError { - throw ArgumentException("invalid words num"); + throw const ArgumentException("invalid words num"); } final wNum = ElectrumV1WordsNum.values .firstWhere((element) => element.value == wordsNum); diff --git a/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_utils.dart b/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_utils.dart index d16eba1..dd07db1 100644 --- a/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_utils.dart +++ b/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_utils.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/bip/electrum/mnemonic_v1/electrum_v1_mnemonic.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_utils.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; /// A class responsible for fetching Electrum V1 mnemonic word lists based on language. @@ -21,7 +21,7 @@ class ElectrumV1WordsListGetter extends MnemonicWordsListGetterBase { @override MnemonicWordsList getByLanguage(MnemonicLanguages language) { if (language is! ElectrumV1Languages) { - throw ArgumentException( + throw const ArgumentException( "Language is not an enumerative of Bip39Languages"); } return loadWordsList(language, ElectrumV1MnemonicConst.wordsListNum); diff --git a/lib/bip/electrum/mnemonic_v1/electrum_v1_seed_generator.dart b/lib/bip/electrum/mnemonic_v1/electrum_v1_seed_generator.dart index 18f342c..9c8ff75 100644 --- a/lib/bip/electrum/mnemonic_v1/electrum_v1_seed_generator.dart +++ b/lib/bip/electrum/mnemonic_v1/electrum_v1_seed_generator.dart @@ -2,9 +2,8 @@ import 'dart:core'; import 'package:blockchain_utils/bip/electrum/mnemonic_v1/electrum_v1_mnemonic.dart'; import 'package:blockchain_utils/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_decoder.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/string/string.dart'; /// Constants related to the generation of Electrum V1 seeds. class ElectrumV1SeedGeneratorConst { @@ -41,7 +40,7 @@ class ElectrumV1SeedGenerator { static List _generateSeed(List entropyBytes) { final entropy = StringUtils.encode(BytesUtils.toHexString(entropyBytes)); List h = entropy; - for (int _ = 0; _ < ElectrumV1SeedGeneratorConst.hashIterationNum; _++) { + for (int i = 0; i < ElectrumV1SeedGeneratorConst.hashIterationNum; i++) { h = QuickCrypto.sha256Hash(List.from([...h, ...entropy])); } return h; diff --git a/lib/bip/electrum/mnemonic_v2/electrum_v2_entropy_generator.dart b/lib/bip/electrum/mnemonic_v2/electrum_v2_entropy_generator.dart index 9808d65..28995ce 100644 --- a/lib/bip/electrum/mnemonic_v2/electrum_v2_entropy_generator.dart +++ b/lib/bip/electrum/mnemonic_v2/electrum_v2_entropy_generator.dart @@ -29,7 +29,7 @@ class ElectrumV2EntropyGenerator extends EntropyGenerator { /// [bitLen]: The desired bit length for generating Electrum V2 entropy. ElectrumV2EntropyGenerator(int bitLen) : super(bitLen) { if (!isValidEntropyBitLen(bitLen)) { - throw ArgumentException('Entropy bit length is not valid'); + throw const ArgumentException('Entropy bit length is not valid'); } } diff --git a/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_decoder.dart b/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_decoder.dart index 0a2a923..6eb6e92 100644 --- a/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_decoder.dart +++ b/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_decoder.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic_utils.dart'; import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic.dart'; import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_utils.dart'; @@ -50,7 +50,7 @@ class ElectrumV2MnemonicDecoder extends MnemonicDecoderBase { /// Check the validity of the mnemonic for the specified mnemonic type if (!ElectrumV2MnemonicUtils.isValidMnemonic(mnemonicObj, mnemonicType)) { - throw ArgumentException('Invalid mnemonic'); + throw const ArgumentException('Invalid mnemonic'); } /// Get the list of words from the mnemonic diff --git a/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_encoder.dart b/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_encoder.dart index 233fcae..f5beb54 100644 --- a/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_encoder.dart +++ b/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_encoder.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic_utils.dart'; import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_entropy_generator.dart'; import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic.dart'; @@ -37,7 +37,7 @@ class ElectrumV2MnemonicEncoder extends MnemonicEncoderBase { /// Check if the entropy bits are sufficient for a valid mnemonic if (!ElectrumV2EntropyGenerator.areEntropyBitsEnough(entropyInt)) { - throw ArgumentException( + throw const ArgumentException( 'Entropy bit length is not enough for generating a valid mnemonic'); } @@ -57,7 +57,7 @@ class ElectrumV2MnemonicEncoder extends MnemonicEncoderBase { /// Check if the resulting mnemonic is valid for the specified mnemonic type if (!ElectrumV2MnemonicUtils.isValidMnemonic(mnemonicObj, mnemonicType)) { - throw ArgumentException( + throw const ArgumentException( 'Entropy bytes are not suitable for generating a valid mnemonic'); } return mnemonicObj; diff --git a/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_generator.dart b/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_generator.dart index 18cebf9..c9f2b37 100644 --- a/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_generator.dart +++ b/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_generator.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_entropy_generator.dart'; import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic.dart'; import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_encoder.dart'; @@ -86,6 +86,6 @@ class ElectrumV2MnemonicGenerator { } } - throw ArgumentException('Unable to generate a valid mnemonic'); + throw const ArgumentException('Unable to generate a valid mnemonic'); } } diff --git a/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_utils.dart b/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_utils.dart index 7cf12ed..dd5bc8f 100644 --- a/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_utils.dart +++ b/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_utils.dart @@ -1,10 +1,9 @@ import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic_validator.dart'; import 'package:blockchain_utils/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_validator.dart'; import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; -import 'package:blockchain_utils/string/string.dart'; /// Constants related to Electrum V2 mnemonic utilities. class ElectrumV2MnemonicUtilsConst { diff --git a/lib/bip/electrum/mnemonic_v2/electrum_v2_seed_generator.dart b/lib/bip/electrum/mnemonic_v2/electrum_v2_seed_generator.dart index ad2bade..417a263 100644 --- a/lib/bip/electrum/mnemonic_v2/electrum_v2_seed_generator.dart +++ b/lib/bip/electrum/mnemonic_v2/electrum_v2_seed_generator.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic.d import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_validator.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; -import 'package:blockchain_utils/string/string.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// Constants and configurations related to Electrum V2 seed generation. class ElectrumV2SeedGeneratorConst { diff --git a/lib/bip/mnemonic/mnemonic_decoder_base.dart b/lib/bip/mnemonic/mnemonic_decoder_base.dart index 3da9ca8..2341bb1 100644 --- a/lib/bip/mnemonic/mnemonic_decoder_base.dart +++ b/lib/bip/mnemonic/mnemonic_decoder_base.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_utils.dart'; -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// An abstract base class for mnemonic phrase decoding in various languages and word lists. /// diff --git a/lib/bip/mnemonic/mnemonic_ex.dart b/lib/bip/mnemonic/mnemonic_ex.dart index 0479e3f..c8fc45b 100644 --- a/lib/bip/mnemonic/mnemonic_ex.dart +++ b/lib/bip/mnemonic/mnemonic_ex.dart @@ -1,15 +1,15 @@ import 'package:blockchain_utils/exception/exception.dart'; -/// An exception representing an error related to the checksum validation of a mnemonic phrase. -/// -/// This exception is thrown when the checksum of a mnemonic phrase is found to be invalid -/// during mnemonic validation or when attempting to derive a key from the mnemonic phrase. -class MnemonicChecksumError implements BlockchainUtilsException { - const MnemonicChecksumError(this.message); - +/// An exception representing an error related to mnemonic. +class MnemonicException implements BlockchainUtilsException { @override final String message; + @override + final Map? details; + + const MnemonicException(this.message, {this.details}); + @override String toString() { return message; diff --git a/lib/bip/mnemonic/mnemonic_utils.dart b/lib/bip/mnemonic/mnemonic_utils.dart index a0ef06f..dd71331 100644 --- a/lib/bip/mnemonic/mnemonic_utils.dart +++ b/lib/bip/mnemonic/mnemonic_utils.dart @@ -1,8 +1,7 @@ import 'dart:typed_data'; import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/numbers/int_utils.dart'; /// An abstract class representing different languages for mnemonic phrases. /// Classes implementing this interface must provide word lists and language values. diff --git a/lib/bip/mnemonic/mnemonic_validator.dart b/lib/bip/mnemonic/mnemonic_validator.dart index 2d78da0..d9c63c8 100644 --- a/lib/bip/mnemonic/mnemonic_validator.dart +++ b/lib/bip/mnemonic/mnemonic_validator.dart @@ -5,8 +5,8 @@ import 'package:blockchain_utils/bip/mnemonic/mnemonic_decoder_base.dart'; /// The `MnemonicValidator` class provides methods to validate and determine the /// validity of mnemonic phrases using a specified `MnemonicDecoderBase`. It can /// check whether a given mnemonic phrase is valid and adheres to the expected format. -class MnemonicValidator { - final MnemonicDecoderBase decoder; +class MnemonicValidator { + final T decoder; /// Creates a new instance of the MnemonicValidator with the provided [decoder]. /// diff --git a/lib/bip/monero/conf/monero_conf.dart b/lib/bip/monero/conf/monero_conf.dart index 978f176..a0b3352 100644 --- a/lib/bip/monero/conf/monero_conf.dart +++ b/lib/bip/monero/conf/monero_conf.dart @@ -11,7 +11,8 @@ class MoneroConf { /// is not an instance of MoneroCoins, an error is thrown. static MoneroCoinConf getCoin(CryptoCoins coin) { if (coin is! MoneroCoins) { - throw ArgumentException("Coin type is not an enumerative of MoneroCoins"); + throw const ArgumentException( + "Coin type is not an enumerative of MoneroCoins"); } return coinToConf[coin.value]!; } diff --git a/lib/bip/monero/mnemonic/monero_mnemonic_decoder.dart b/lib/bip/monero/mnemonic/monero_mnemonic_decoder.dart index fd97d2b..147ec20 100644 --- a/lib/bip/monero/mnemonic/monero_mnemonic_decoder.dart +++ b/lib/bip/monero/mnemonic/monero_mnemonic_decoder.dart @@ -60,7 +60,7 @@ class MoneroMnemonicDecoder extends MnemonicDecoderBase { /// /// This method checks whether the provided Monero mnemonic words have a valid checksum /// by comparing them to the expected checksum. If the checksum is invalid, it throws - /// a MnemonicChecksumError. + /// a MnemonicException. /// /// [words]: The list of Monero mnemonic words to validate. /// [language]: The Monero language used in the mnemonic. @@ -71,7 +71,7 @@ class MoneroMnemonicDecoder extends MnemonicDecoderBase { final checkSum = MoneroMnemonicUtils.computeChecksum( words.sublist(0, words.length - 1), language); if (words.last != checkSum) { - throw MnemonicChecksumError( + throw MnemonicException( 'Invalid checksum (expected $checkSum, got ${words.last})'); } // ignore: empty_catches diff --git a/lib/bip/monero/mnemonic/monero_mnemonic_encoder.dart b/lib/bip/monero/mnemonic/monero_mnemonic_encoder.dart index 24fe6d7..c79b992 100644 --- a/lib/bip/monero/mnemonic/monero_mnemonic_encoder.dart +++ b/lib/bip/monero/mnemonic/monero_mnemonic_encoder.dart @@ -1,9 +1,12 @@ import 'dart:typed_data'; - import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_encoder_base.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_utils.dart'; -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; + +import 'monero_entropy_generator.dart'; +import 'monero_mnemonic.dart'; +import 'monero_mnemonic_utils.dart'; /// An abstract base class for encoding entropy into Monero mnemonics. /// diff --git a/lib/bip/monero/mnemonic/monero_mnemonic_generator.dart b/lib/bip/monero/mnemonic/monero_mnemonic_generator.dart index 64e0452..fd8d887 100644 --- a/lib/bip/monero/mnemonic/monero_mnemonic_generator.dart +++ b/lib/bip/monero/mnemonic/monero_mnemonic_generator.dart @@ -1,5 +1,8 @@ import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/exception/exception.dart'; +import 'monero_entropy_generator.dart'; +import 'monero_mnemonic.dart'; +import 'monero_mnemonic_encoder.dart'; /// A class containing constants related to Monero mnemonic generation. /// diff --git a/lib/bip/monero/mnemonic/monero_mnemonic_utils.dart b/lib/bip/monero/mnemonic/monero_mnemonic_utils.dart index 479919e..ca7df8a 100644 --- a/lib/bip/monero/mnemonic/monero_mnemonic_utils.dart +++ b/lib/bip/monero/mnemonic/monero_mnemonic_utils.dart @@ -3,8 +3,7 @@ import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_utils.dart'; import 'package:blockchain_utils/crypto/crypto/crc32/crc32.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/string/string.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// A class that retrieves Monero mnemonic word lists by language. /// @@ -24,7 +23,7 @@ class MoneroWordsListGetter extends MnemonicWordsListGetterBase { @override MnemonicWordsList getByLanguage(MnemonicLanguages language) { if (language is! MoneroLanguages) { - throw ArgumentException( + throw const ArgumentException( "Language is not an enumerative of MoneroLanguages"); } return loadWordsList(language, MoneroMnemonicConst.wordsListNum); diff --git a/lib/bip/monero/monero_exc.dart b/lib/bip/monero/monero_exc.dart index 5652be9..8f5821e 100644 --- a/lib/bip/monero/monero_exc.dart +++ b/lib/bip/monero/monero_exc.dart @@ -7,10 +7,13 @@ class MoneroKeyError implements BlockchainUtilsException { @override final String message; + @override + final Map? details; + /// Constructs a MoneroKeyError with an optional error message. /// /// [message]: An optional error message describing the key-related issue. - const MoneroKeyError(this.message); + const MoneroKeyError(this.message, {this.details}); /// Returns a string representation of the exception. @override diff --git a/lib/bip/monero/monero_keys.dart b/lib/bip/monero/monero_keys.dart index 344060f..98a31d5 100644 --- a/lib/bip/monero/monero_keys.dart +++ b/lib/bip/monero/monero_keys.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/ecc/keys/i_keys.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; import 'package:blockchain_utils/bip/ecc/keys/ed25519_keys.dart'; @@ -112,8 +112,10 @@ class MoneroPublicKey implements IPublicKey { } @override - String toHex() { - return BytesUtils.toHexString(compressed); + String toHex( + {bool withPrefix = true, bool lowerCase = true, String? prefix = ""}) { + return BytesUtils.toHexString(compressed, + prefix: prefix, lowerCase: lowerCase); } } @@ -187,7 +189,7 @@ class MoneroPrivateKey implements IPrivateKey { } @override - String toHex() { - return BytesUtils.toHexString(raw); + String toHex({bool lowerCase = true, String? prefix = ""}) { + return BytesUtils.toHexString(raw, lowerCase: lowerCase, prefix: prefix); } } diff --git a/lib/bip/monero/monero_subaddr.dart b/lib/bip/monero/monero_subaddr.dart index ba6d9c2..3e77692 100644 --- a/lib/bip/monero/monero_subaddr.dart +++ b/lib/bip/monero/monero_subaddr.dart @@ -1,15 +1,12 @@ import 'dart:typed_data'; import 'package:blockchain_utils/exception/exception.dart'; - -import 'package:blockchain_utils/numbers/int_utils.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/address/xmr_addr.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/utils/ed25519_utils.dart'; import 'package:blockchain_utils/bip/monero/monero_keys.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curves.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/edwards.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; /// A class containing constants related to Monero subaddresses. class MoneroSubaddressConst { diff --git a/lib/bip/slip/slip32/slip32.dart b/lib/bip/slip/slip32/slip32.dart index 9d9526d..ffdb60f 100644 --- a/lib/bip/slip/slip32/slip32.dart +++ b/lib/bip/slip/slip32/slip32.dart @@ -166,7 +166,7 @@ class Slip32KeyDeserializer { keyNetVer.private) { return false; } else { - throw ArgumentException("Invalid extended key (wrong net version)"); + throw const ArgumentException("Invalid extended key (wrong net version)"); } } diff --git a/lib/bip/slip/slip44/slip44.dart b/lib/bip/slip/slip44/slip44.dart index 5571556..24d8a6c 100644 --- a/lib/bip/slip/slip44/slip44.dart +++ b/lib/bip/slip/slip44/slip44.dart @@ -76,6 +76,7 @@ class Slip44 { static const int bitcoinSv = 236; static const int algorand = 283; static const int zilliqa = 313; + static const int ton = 607; static const int terra = 330; static const int polkadot = 354; static const int nearProtocol = 397; diff --git a/lib/bip/substrate/conf/substrate_conf.dart b/lib/bip/substrate/conf/substrate_conf.dart index bb41c6f..9451a95 100644 --- a/lib/bip/substrate/conf/substrate_conf.dart +++ b/lib/bip/substrate/conf/substrate_conf.dart @@ -12,7 +12,7 @@ class SubstrateConf { /// is not an instance of SubstrateCoins, an error is thrown. static SubstrateCoinConf getCoin(CryptoCoins coin) { if (coin is! SubstrateCoins) { - throw ArgumentException( + throw const ArgumentException( "Coin type is not an enumerative of SubstrateCoins"); } return coinToConf[coin.value]!; diff --git a/lib/bip/substrate/scale/substrate_scale_enc_bytes.dart b/lib/bip/substrate/scale/substrate_scale_enc_bytes.dart index ba31fc6..7326f34 100644 --- a/lib/bip/substrate/scale/substrate_scale_enc_bytes.dart +++ b/lib/bip/substrate/scale/substrate_scale_enc_bytes.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/substrate/scale/substrate_scale_enc_base.dart'; import 'package:blockchain_utils/bip/substrate/scale/substrate_scale_enc_cuint.dart'; -import 'package:blockchain_utils/string/string.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// A Substrate SCALE encoder for string values represented as bytes. class SubstrateScaleBytesEncoder extends SubstrateScaleEncoderBase { diff --git a/lib/bip/substrate/scale/substrate_scale_enc_cuint.dart b/lib/bip/substrate/scale/substrate_scale_enc_cuint.dart index fdf60dc..67d1b4e 100644 --- a/lib/bip/substrate/scale/substrate_scale_enc_cuint.dart +++ b/lib/bip/substrate/scale/substrate_scale_enc_cuint.dart @@ -1,5 +1,7 @@ import 'dart:typed_data'; -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; +import 'package:blockchain_utils/utils/utils.dart'; +import 'substrate_scale_enc_base.dart'; /// Constants related to Substrate SCALE Compact Uint (CUint) encoding. class SubstrateScaleCUintEncoderConst { diff --git a/lib/bip/substrate/scale/substrate_scale_enc_uint.dart b/lib/bip/substrate/scale/substrate_scale_enc_uint.dart index e5c2fa9..b44dd77 100644 --- a/lib/bip/substrate/scale/substrate_scale_enc_uint.dart +++ b/lib/bip/substrate/scale/substrate_scale_enc_uint.dart @@ -1,6 +1,6 @@ import 'dart:typed_data'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'substrate_scale_enc_base.dart'; /// An abstract base class for encoding unsigned integers in Substrate SCALE format. diff --git a/lib/bip/substrate/substrate_base.dart b/lib/bip/substrate/substrate_base.dart index 13fd866..d17d332 100644 --- a/lib/bip/substrate/substrate_base.dart +++ b/lib/bip/substrate/substrate_base.dart @@ -50,7 +50,7 @@ class _SubstrateUtils { static List getSecretKey( List seedBytes, SubstrateKeyAlgorithm curve) { if (seedBytes.length < SubstrateConst.seedMinByteLen) { - throw ArgumentException( + throw const ArgumentException( 'Seed length is too small, it shall be at least ${SubstrateConst.seedMinByteLen} bytes', ); } diff --git a/lib/bip/substrate/substrate_ex.dart b/lib/bip/substrate/substrate_ex.dart index 864c4a6..2b52f92 100644 --- a/lib/bip/substrate/substrate_ex.dart +++ b/lib/bip/substrate/substrate_ex.dart @@ -6,8 +6,11 @@ class SubstrateKeyError implements BlockchainUtilsException { @override final String message; + @override + final Map? details; + /// Creates a new instance of [SubstrateKeyError] with an optional [message]. - const SubstrateKeyError(this.message); + const SubstrateKeyError(this.message, {this.details}); @override String toString() { @@ -21,8 +24,11 @@ class SubstratePathError implements BlockchainUtilsException { @override final String message; + @override + final Map? details; + /// Creates a new instance of [SubstratePathError] with an optional [message]. - const SubstratePathError(this.message); + const SubstratePathError(this.message, {this.details}); @override String toString() { diff --git a/lib/bip/ton/mnemonic/ton_entropy_generator.dart b/lib/bip/ton/mnemonic/ton_entropy_generator.dart new file mode 100644 index 0000000..902c523 --- /dev/null +++ b/lib/bip/ton/mnemonic/ton_entropy_generator.dart @@ -0,0 +1,72 @@ +import 'package:blockchain_utils/bip/mnemonic/entropy_generator.dart'; +import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; +import 'package:blockchain_utils/crypto/quick_crypto.dart'; +import 'package:blockchain_utils/utils/utils.dart'; + +/// The TonEntropyGeneratorUtils class provides utility methods for handling entropy +/// generation and validation related to the TON (The Open Network) blockchain. It +/// includes methods to determine if a given entropy corresponds to a basic seed, +/// a password-protected seed, and if a password is required based on a mnemonic phrase. +class TonEntropyGeneratorUtils { + /// Constants defining the number of iterations for the PBKDF2 key derivation function. + static const int basicSeedPbkdfIterations = 390; + static const int passwordSeedPbkdfIterations = 1; + static const String seedVersionSalt = "TON seed version"; + static const String seedFastVersionSalt = "TON fast seed version"; + + /// Determines if the provided entropy is a basic seed by using PBKDF2 with a predefined + /// salt and iteration count. Returns true if the derived key's first byte is 0. + static bool isBasicSeed(List entropy) { + final scrypt = QuickCrypto.pbkdf2DeriveKey( + password: entropy, + salt: seedVersionSalt.codeUnits, + iterations: basicSeedPbkdfIterations); + return scrypt[0] == 0; + } + + /// Determines if the provided entropy is a password-protected seed by using PBKDF2 with + /// a predefined salt and a single iteration. Returns true if the derived key's first byte is 1. + static bool isPasswordSeed(List entropy) { + final scrypt = QuickCrypto.pbkdf2DeriveKey( + password: entropy, + salt: seedFastVersionSalt.codeUnits, + iterations: passwordSeedPbkdfIterations); + return scrypt[0] == 1; + } + + /// Checks if a password is needed for the given mnemonic by generating its entropy and + /// evaluating it with isPasswordSeed and isBasicSeed methods. + static bool isPasswordNeed(Mnemonic mnemonic) { + final entropy = generateEnteropy(mnemonic); + return isPasswordSeed(entropy) && !isBasicSeed(entropy); + } + + /// Generates entropy from a given mnemonic and optional passphrase using HMAC-SHA512. + static List generateEnteropy(Mnemonic mnemonic, {String password = ""}) { + return QuickCrypto.hmacSha512Hash( + StringUtils.encode(mnemonic.toStr()), StringUtils.encode(password)); + } +} + +/// The TonMnemonicEntropyGenerator class extends EntropyGenerator to provide specific +/// entropy generation functionalities tailored for TON mnemonic phrases. +class TonMnemonicEntropyGenerator extends EntropyGenerator { + /// Constructor initializing the base EntropyGenerator with the given bit length. + TonMnemonicEntropyGenerator(int bitLen) : super(bitLen); + + /// Validates if the given bit length for entropy is within the acceptable range (88 to 528 bits). + static bool isValidEntropyBitLen(int bitLen) { + return bitLen >= 88 && bitLen <= 528; + } + + /// Validates if the given byte length for entropy corresponds to a valid bit length. + static bool isValidEntropyByteLen(int byteLen) { + return isValidEntropyBitLen(byteLen * 8); + } + + /// Generates random entropy based on the bit length provided at initialization. + @override + List generate() { + return QuickCrypto.generateRandom((bitlen / 8).ceil()); + } +} diff --git a/lib/bip/ton/mnemonic/ton_mnemonic_encoder.dart b/lib/bip/ton/mnemonic/ton_mnemonic_encoder.dart new file mode 100644 index 0000000..ee4ee9a --- /dev/null +++ b/lib/bip/ton/mnemonic/ton_mnemonic_encoder.dart @@ -0,0 +1,48 @@ +import 'package:blockchain_utils/utils/utils.dart'; +import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic.dart'; +import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic_utils.dart'; +import 'package:blockchain_utils/bip/mnemonic/mnemonic_encoder_base.dart'; +import 'package:blockchain_utils/bip/mnemonic/mnemonic_ex.dart'; +import 'ton_entropy_generator.dart'; +import 'ton_mnemonic_language.dart'; + +/// The TonMnemonicEncoder class extends MnemonicEncoderBase to provide functionality +/// for encoding entropy bytes into a BIP-39 mnemonic phrase, specifically tailored for +/// the TON (The Open Network) blockchain. +class TonMnemonicEncoder extends MnemonicEncoderBase { + /// Constructor initializes the encoder with a specified language for the mnemonic. + /// Defaults to English if no language is specified. + TonMnemonicEncoder( + [TonMnemonicLanguages language = TonMnemonicLanguages.english]) + : super(language, Bip39WordsListGetter()); + + /// Overrides the encode method to convert entropy bytes into a BIP-39 mnemonic phrase. + @override + Bip39Mnemonic encode(List entropyBytes) { + /// Validates the length of the entropy bytes. + final entropyByteLen = entropyBytes.length; + if (!TonMnemonicEntropyGenerator.isValidEntropyByteLen(entropyByteLen)) { + throw MnemonicException( + 'Entropy byte length ($entropyByteLen) is not valid'); + } + + /// Converts entropy bytes to a binary string with zero padding. + final entropyBinStr = + BytesUtils.toBinary(entropyBytes, zeroPadBitLen: entropyByteLen * 8); + + /// Converts the binary string to a list of mnemonic words. + List mnemonic = []; + for (int i = 0; + i < entropyBinStr.length; + i += Bip39MnemonicConst.wordBitLen) { + if (i + Bip39MnemonicConst.wordBitLen > entropyBinStr.length) break; + final wordBinStr = + entropyBinStr.substring(i, i + Bip39MnemonicConst.wordBitLen); + final wordIdx = int.parse(wordBinStr, radix: 2); + mnemonic.add(wordsList.getWordAtIdx(wordIdx)); + } + + /// Returns a BIP-39 mnemonic phrase constructed from the list of words. + return Bip39Mnemonic.fromList(mnemonic); + } +} diff --git a/lib/bip/ton/mnemonic/ton_mnemonic_generator.dart b/lib/bip/ton/mnemonic/ton_mnemonic_generator.dart new file mode 100644 index 0000000..c7da30f --- /dev/null +++ b/lib/bip/ton/mnemonic/ton_mnemonic_generator.dart @@ -0,0 +1,65 @@ +import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic.dart'; +import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; +import 'package:blockchain_utils/bip/mnemonic/mnemonic_ex.dart'; +import 'ton_entropy_generator.dart'; +import 'ton_mnemonic_encoder.dart'; +import 'ton_mnemonic_language.dart'; +import 'ton_mnemonic_validator.dart'; + +/// The TonMnemonicGeneratorUtils class provides utility methods for validating +/// the number of mnemonic words and calculating the corresponding bit length. +class TonMnemonicGeneratorUtils { + /// Validates that the number of mnemonic words is within the acceptable range (8 to 48). + static void validateWordsNum(int wordsNum) { + if (wordsNum < 8 || wordsNum > 48) { + throw const MnemonicException( + "Invalid mnemonic words count. Words number must be between 8 and 48"); + } + } + + /// Returns the bit length corresponding to the number of mnemonic words. + static int getBitlength(int wordsNum) { + validateWordsNum(wordsNum); + return (wordsNum * Bip39MnemonicConst.wordBitLen); + } +} + +/// The TonMnemonicGenerator class is responsible for generating BIP-39 mnemonic phrases +/// either from a specified number of words or directly from entropy bytes. +class TonMnemonicGenerator { + final TonMnemonicEncoder _mnemonicEncoder; + + /// Constructor initializes the mnemonic encoder with the specified language. + /// Defaults to English if no language is specified. + TonMnemonicGenerator( + [TonMnemonicLanguages language = TonMnemonicLanguages.english]) + : _mnemonicEncoder = TonMnemonicEncoder(language); + + /// Generates a mnemonic phrase from a specified number of words, ensuring it is valid + /// according to the TOM mnemonic validator. + Mnemonic fromWordsNumber(int wordsNum, {String password = ""}) { + final validator = TomMnemonicValidator(); + Mnemonic mnemonic; + while (true) { + final int entropyBitLen = _entropyBitLenFromWordsNum(wordsNum); + final List entropyBytes = + TonMnemonicEntropyGenerator(entropyBitLen).generate(); + mnemonic = fromEntropy(entropyBytes); + if (!validator.isValid(mnemonic, password: password)) { + continue; + } + break; + } + return mnemonic; + } + + /// Encodes the given entropy bytes into a mnemonic phrase using the encoder. + Mnemonic fromEntropy(List entropyBytes) { + return _mnemonicEncoder.encode(entropyBytes); + } + + /// Calculates the bit length of entropy required for the specified number of words. + int _entropyBitLenFromWordsNum(int wordsNum) { + return TonMnemonicGeneratorUtils.getBitlength(wordsNum); + } +} diff --git a/lib/bip/ton/mnemonic/ton_mnemonic_language.dart b/lib/bip/ton/mnemonic/ton_mnemonic_language.dart new file mode 100644 index 0000000..d3fe236 --- /dev/null +++ b/lib/bip/ton/mnemonic/ton_mnemonic_language.dart @@ -0,0 +1,37 @@ +import 'package:blockchain_utils/bip/bip/bip39/bip39.dart'; +import 'package:blockchain_utils/bip/mnemonic/mnemonic_ex.dart'; +import 'package:blockchain_utils/bip/mnemonic/mnemonic_utils.dart'; +import 'package:blockchain_utils/bip/bip/bip39/word_list/languages.dart' + as languages; + +/// The TonMnemonicLanguages class implements the Bip39Languages interface to +/// provide support for BIP-39 mnemonic languages, specifically tailored for TON (The Open Network). +class TonMnemonicLanguages implements Bip39Languages { + @override + final String name; + + /// Predefined constant for the English language. + static const TonMnemonicLanguages english = TonMnemonicLanguages._("English"); + + /// Private constructor for defining language instances. + const TonMnemonicLanguages._(this.name); + + /// List of all supported TonMnemonicLanguages instances. + static const List values = [english]; + + // Retrieves the word list associated with the language instance. + @override + List get wordList { + switch (this) { + case TonMnemonicLanguages.english: + return languages.bip39WordList(Bip39Languages.english); + default: + throw const MnemonicException( + "TonMnemonicLanguages only support english"); + } + } + + /// Provides a list of all mnemonic language values. + @override + List get languageValues => TonMnemonicLanguages.values; +} diff --git a/lib/bip/ton/mnemonic/ton_mnemonic_validator.dart b/lib/bip/ton/mnemonic/ton_mnemonic_validator.dart new file mode 100644 index 0000000..8378cc2 --- /dev/null +++ b/lib/bip/ton/mnemonic/ton_mnemonic_validator.dart @@ -0,0 +1,38 @@ +import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; +import 'package:blockchain_utils/bip/mnemonic/mnemonic_ex.dart'; +import 'ton_entropy_generator.dart'; +import 'ton_mnemonic_generator.dart'; + +/// The TomMnemonicValidator class provides methods for validating TON (The Open Network) +/// mnemonic phrases. It ensures the mnemonic meets the required criteria for word count +/// and checks if a passphrase is needed or if it is a basic seed. +class TomMnemonicValidator { + /// Validates the given mnemonic string, optionally with a password. + void validate(Mnemonic mnemonic, {String password = ""}) { + /// Validates the number of words in the mnemonic. + TonMnemonicGeneratorUtils.validateWordsNum(mnemonic.wordsCount()); + + /// Checks if the mnemonic requires a passphrase but one is not provided. + if (password.isNotEmpty && + !TonEntropyGeneratorUtils.isPasswordNeed(mnemonic)) { + throw const MnemonicException("Invalid Ton mnemonic. is Basic seed."); + } + + /// Generates entropy from the mnemonic and passphrase, then checks if it is a basic seed. + if (!TonEntropyGeneratorUtils.isBasicSeed( + TonEntropyGeneratorUtils.generateEnteropy(mnemonic, + password: password))) { + throw const MnemonicException("Invalid Ton mnemonic."); + } + } + + /// Determines if the given mnemonic string is valid, optionally with a passphrase. + bool isValid(Mnemonic mnemonic, {String password = ""}) { + try { + validate(mnemonic, password: password); + return true; + } catch (e) { + return false; + } + } +} diff --git a/lib/bip/ton/mnemonic/ton_seed_generator.dart b/lib/bip/ton/mnemonic/ton_seed_generator.dart new file mode 100644 index 0000000..3f27282 --- /dev/null +++ b/lib/bip/ton/mnemonic/ton_seed_generator.dart @@ -0,0 +1,39 @@ +import 'package:blockchain_utils/crypto/quick_crypto.dart'; +import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; +import 'package:blockchain_utils/utils/utils.dart'; +import 'ton_entropy_generator.dart'; +import 'ton_mnemonic_validator.dart'; + +/// The _TonSeedGeneratorConst class contains constants used for the TonSeedGenerator. +class _TonSeedGeneratorConst { + static const int seedPbkdf2Rounds = 100000; + static const String defaultTonSalt = "TON default seed"; +} + +/// The TonSeedGenerator class is responsible for generating a seed from a mnemonic phrase. +/// It can optionally validate the mnemonic according to TON specifications and use a passphrase. +class TonSeedGenerator { + const TonSeedGenerator(this.mnemonic); + final Mnemonic mnemonic; + + /// Generates a seed from the mnemonic, with optional passphrase and salt. + /// If validateTonMnemonic is true, it validates the mnemonic before generating the seed. + List generate( + {String password = "", + String salt = _TonSeedGeneratorConst.defaultTonSalt, + bool validateTonMnemonic = false}) { + if (validateTonMnemonic) { + TomMnemonicValidator().validate(mnemonic, password: password); + } + + /// Generates entropy from the mnemonic and passphrase. + final hash = + TonEntropyGeneratorUtils.generateEnteropy(mnemonic, password: password); + + /// Derives a key using PBKDF2 with the generated hash, salt, and a specified number of iterations. + return QuickCrypto.pbkdf2DeriveKey( + password: hash, + salt: StringUtils.encode(salt), + iterations: _TonSeedGeneratorConst.seedPbkdf2Rounds); + } +} diff --git a/lib/bip/ton/ton.dart b/lib/bip/ton/ton.dart new file mode 100644 index 0000000..7e3e94d --- /dev/null +++ b/lib/bip/ton/ton.dart @@ -0,0 +1,6 @@ +export 'mnemonic/ton_entropy_generator.dart'; +export 'mnemonic/ton_mnemonic_encoder.dart'; +export 'mnemonic/ton_mnemonic_generator.dart'; +export 'mnemonic/ton_mnemonic_language.dart'; +export 'mnemonic/ton_mnemonic_validator.dart'; +export 'mnemonic/ton_seed_generator.dart'; diff --git a/lib/bip/wif/wif.dart b/lib/bip/wif/wif.dart index 92bdd9e..b4fde9d 100644 --- a/lib/bip/wif/wif.dart +++ b/lib/bip/wif/wif.dart @@ -55,7 +55,7 @@ import 'package:blockchain_utils/base58/base58.dart'; import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:blockchain_utils/bip/ecc/keys/secp256k1_keys_ecdsa.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; /// Constants related to Wallet Import Format (WIF). @@ -106,7 +106,7 @@ class WifDecoder { {List netVer = const []}) { List privKeyBytes = Base58Decoder.checkDecode(wif); if (netVer.isEmpty || privKeyBytes[0] != netVer[0]) { - throw ArgumentException('Invalid net version'); + throw const ArgumentException('Invalid net version'); } privKeyBytes = privKeyBytes.sublist(1); PubKeyModes pubKeyMode; @@ -114,13 +114,13 @@ class WifDecoder { privKeyBytes.sublist(0, privKeyBytes.length - 1))) { // Check the compressed public key suffix if (privKeyBytes[privKeyBytes.length - 1] != WifConst.comprPubKeySuffix) { - throw ArgumentException('Invalid compressed public key suffix'); + throw const ArgumentException('Invalid compressed public key suffix'); } privKeyBytes = privKeyBytes.sublist(0, privKeyBytes.length - 1); pubKeyMode = PubKeyModes.compressed; } else { if (!Secp256k1PrivateKeyEcdsa.isValidBytes(privKeyBytes)) { - throw ArgumentException('Invalid decoded key'); + throw const ArgumentException('Invalid decoded key'); } pubKeyMode = PubKeyModes.uncompressed; } diff --git a/lib/blockchain_utils.dart b/lib/blockchain_utils.dart index 6e125bb..cd8b1be 100644 --- a/lib/blockchain_utils.dart +++ b/lib/blockchain_utils.dart @@ -24,7 +24,7 @@ export 'crypto/quick_crypto.dart'; export 'hex/hex.dart'; /// Export for tools related to managing secret wallets. -export 'secret_wallet/secret_wallet.dart'; +export 'secret_wallet/web3_storage_defination.dart'; /// Export for SS58 (Substrate/Polkadot/Stash encoding) utilities. export 'ss58/ss58.dart'; @@ -59,29 +59,27 @@ export 'bip/substrate/substrate.dart'; /// Export for Wallet Import Format (WIF) encoding and decoding utilities. export 'bip/wif/wif.dart'; -/// Exports utility functions related to string operations. -export 'string/string.dart'; - -/// Exports utility functions related to binary operations. -export 'binary/binary.dart'; - /// Exports the BitcoinSigner class for Bitcoin signing operations. export 'signer/signer.dart'; /// Exports modules related to ECC (Elliptic Curve Cryptography) in the context of BIP. export 'bip/ecc/bip_ecc.dart'; -/// Exports utility functions related to BigInt operations. -export 'numbers/bigint_utils.dart'; +/// Exports utility functions related to TON mnemonic. +export 'bip/ton/ton.dart'; + +/// Exports utility functions related to mnemonic. +export 'bip/mnemonic/mnemonic.dart'; + +/// Exports utility functions related to numeric, bytes and strings. +export 'utils/utils.dart'; /// Exports utility functions related to numbers operations. -export 'numbers/numbers.dart'; +export 'utils/numbers/numbers.dart'; /// Exceptions export 'exception/exceptions.dart'; -export 'tuple/tuple.dart'; - -export 'compare/compare.dart'; +export 'utils/compare/compare.dart'; export 'layout/layout.dart'; diff --git a/lib/cbor/core/cbor.dart b/lib/cbor/core/cbor.dart index fed4879..b38c8d9 100644 --- a/lib/cbor/core/cbor.dart +++ b/lib/cbor/core/cbor.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/types/types.dart'; import 'package:blockchain_utils/cbor/utils/cbor_utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; @@ -73,7 +73,7 @@ abstract class CborNumeric implements CborObject { } else if (val is CborSafeIntValue) { return val.value; } - throw ArgumentException("invalid cbornumeric"); + throw const ArgumentException("invalid cbornumeric"); } /// Convert the CborNumeric object to an integer. diff --git a/lib/cbor/types/base.dart b/lib/cbor/types/base.dart index d8b1a0a..73ac11b 100644 --- a/lib/cbor/types/base.dart +++ b/lib/cbor/types/base.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; import 'package:blockchain_utils/cbor/types/string.dart'; diff --git a/lib/cbor/types/bigfloat.dart b/lib/cbor/types/bigfloat.dart index 221c014..d3b2b42 100644 --- a/lib/cbor/types/bigfloat.dart +++ b/lib/cbor/types/bigfloat.dart @@ -1,9 +1,8 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; import 'package:blockchain_utils/cbor/types/bigint.dart'; import 'package:blockchain_utils/cbor/core/cbor.dart'; -import 'package:blockchain_utils/compare/compare.dart'; import 'int64.dart'; /// A class representing a CBOR (Concise Binary Object Representation) BigFloat value. @@ -66,7 +65,7 @@ class CborBigFloatValue implements CborObject { operator ==(other) { if (other is! CborBigFloatValue) return false; - return iterableIsEqual(value, other.value); + return CompareUtils.iterableIsEqual(value, other.value); } /// ovveride hash code diff --git a/lib/cbor/types/bigint.dart b/lib/cbor/types/bigint.dart index fa2928d..7ba3f42 100644 --- a/lib/cbor/types/bigint.dart +++ b/lib/cbor/types/bigint.dart @@ -1,8 +1,7 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; import 'package:blockchain_utils/cbor/core/cbor.dart'; -import 'package:blockchain_utils/numbers/numbers.dart'; /// A class representing a CBOR (Concise Binary Object Representation) Bigint value. class CborBigIntValue implements CborNumeric { diff --git a/lib/cbor/types/boolean.dart b/lib/cbor/types/boolean.dart index e5b1399..715d985 100644 --- a/lib/cbor/types/boolean.dart +++ b/lib/cbor/types/boolean.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; import 'package:blockchain_utils/cbor/core/cbor.dart'; diff --git a/lib/cbor/types/bytes.dart b/lib/cbor/types/bytes.dart index 9cd4d4e..9a4653b 100644 --- a/lib/cbor/types/bytes.dart +++ b/lib/cbor/types/bytes.dart @@ -1,8 +1,7 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; import 'package:blockchain_utils/cbor/core/cbor.dart'; -import 'package:blockchain_utils/compare/compare.dart'; /// A class representing a CBOR (Concise Binary Object Representation) bytes value. class CborBytesValue implements CborObject { @@ -34,7 +33,7 @@ class CborBytesValue implements CborObject { operator ==(other) { if (other is! CborBytesValue) return false; - return bytesEqual(other.value, value); + return BytesUtils.bytesEqual(other.value, value); } /// ovveride hash code diff --git a/lib/cbor/types/cbor_tag.dart b/lib/cbor/types/cbor_tag.dart index ef1f6d9..5172be0 100644 --- a/lib/cbor/types/cbor_tag.dart +++ b/lib/cbor/types/cbor_tag.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/core/cbor.dart'; diff --git a/lib/cbor/types/datetime.dart b/lib/cbor/types/datetime.dart index 3b84be1..d7bf759 100644 --- a/lib/cbor/types/datetime.dart +++ b/lib/cbor/types/datetime.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/utils/extentions.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; diff --git a/lib/cbor/types/decimal.dart b/lib/cbor/types/decimal.dart index 8b41319..0d3eef4 100644 --- a/lib/cbor/types/decimal.dart +++ b/lib/cbor/types/decimal.dart @@ -1,10 +1,9 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/types/int64.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; import 'package:blockchain_utils/cbor/types/bigint.dart'; import 'package:blockchain_utils/cbor/core/cbor.dart'; -import 'package:blockchain_utils/compare/compare.dart'; /// A class representing a CBOR (Concise Binary Object Representation) Dcecimal value. class CborDecimalFracValue implements CborObject { @@ -65,7 +64,7 @@ class CborDecimalFracValue implements CborObject { @override operator ==(other) { if (other is! CborDecimalFracValue) return false; - return iterableIsEqual(value, other.value); + return CompareUtils.iterableIsEqual(value, other.value); } /// ovveride hash code diff --git a/lib/cbor/types/double.dart b/lib/cbor/types/double.dart index 0c51370..aee488f 100644 --- a/lib/cbor/types/double.dart +++ b/lib/cbor/types/double.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/utils/float_utils.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; diff --git a/lib/cbor/types/int.dart b/lib/cbor/types/int.dart index 54b3fd6..939d1c3 100644 --- a/lib/cbor/types/int.dart +++ b/lib/cbor/types/int.dart @@ -1,6 +1,9 @@ -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/cbor/core/cbor.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; +import 'package:blockchain_utils/utils/utils.dart'; + +import 'bigint.dart'; /// A class representing a CBOR (Concise Binary Object Representation) int value. class CborIntValue implements CborNumeric { diff --git a/lib/cbor/types/int64.dart b/lib/cbor/types/int64.dart index a89a383..783d379 100644 --- a/lib/cbor/types/int64.dart +++ b/lib/cbor/types/int64.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/types/types.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; diff --git a/lib/cbor/types/list.dart b/lib/cbor/types/list.dart index 142ae0e..21a1e6f 100644 --- a/lib/cbor/types/list.dart +++ b/lib/cbor/types/list.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; import 'package:blockchain_utils/cbor/core/cbor.dart'; diff --git a/lib/cbor/types/map.dart b/lib/cbor/types/map.dart index 93984a9..2a60389 100644 --- a/lib/cbor/types/map.dart +++ b/lib/cbor/types/map.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; import 'package:blockchain_utils/cbor/core/cbor.dart'; diff --git a/lib/cbor/types/mime.dart b/lib/cbor/types/mime.dart index 4550f69..2c6d63e 100644 --- a/lib/cbor/types/mime.dart +++ b/lib/cbor/types/mime.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; import 'package:blockchain_utils/cbor/core/cbor.dart'; diff --git a/lib/cbor/types/null.dart b/lib/cbor/types/null.dart index 1c84f22..6a22f3d 100644 --- a/lib/cbor/types/null.dart +++ b/lib/cbor/types/null.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; import 'package:blockchain_utils/cbor/core/cbor.dart'; diff --git a/lib/cbor/types/regex.dart b/lib/cbor/types/regex.dart index 57fcb3d..83b5b50 100644 --- a/lib/cbor/types/regex.dart +++ b/lib/cbor/types/regex.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; import 'package:blockchain_utils/cbor/types/string.dart'; diff --git a/lib/cbor/types/set.dart b/lib/cbor/types/set.dart index 7094a92..18fbf5b 100644 --- a/lib/cbor/types/set.dart +++ b/lib/cbor/types/set.dart @@ -1,8 +1,7 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; import 'package:blockchain_utils/cbor/core/cbor.dart'; -import 'package:blockchain_utils/compare/compare.dart'; /// A class representing a CBOR (Concise Binary Object Representation) Set value. class CborSetValue implements CborObject { @@ -44,7 +43,7 @@ class CborSetValue implements CborObject { @override operator ==(other) { if (other is! CborSetValue) return false; - return iterableIsEqual(value, other.value); + return CompareUtils.iterableIsEqual(value, other.value); } /// override hashcode diff --git a/lib/cbor/types/string.dart b/lib/cbor/types/string.dart index 34b3ed1..e88ba26 100644 --- a/lib/cbor/types/string.dart +++ b/lib/cbor/types/string.dart @@ -1,9 +1,7 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; import 'package:blockchain_utils/cbor/core/cbor.dart'; -import 'package:blockchain_utils/compare/compare.dart'; -import 'package:blockchain_utils/string/string.dart'; /// A class representing a CBOR (Concise Binary Object Representation) String value. abstract class CborString implements CborObject { @@ -89,7 +87,7 @@ class CborIndefiniteStringValue extends CborString { @override operator ==(other) { if (other is! CborIndefiniteStringValue) return false; - return iterableIsEqual(value, other.value); + return CompareUtils.iterableIsEqual(value, other.value); } /// override hashcode diff --git a/lib/cbor/types/url.dart b/lib/cbor/types/url.dart index 659aa9e..ef15f46 100644 --- a/lib/cbor/types/url.dart +++ b/lib/cbor/types/url.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/cbor/utils/dynamic_bytes.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; import 'package:blockchain_utils/cbor/types/string.dart'; diff --git a/lib/cbor/utils/cbor_utils.dart b/lib/cbor/utils/cbor_utils.dart index d603a14..2afaa1d 100644 --- a/lib/cbor/utils/cbor_utils.dart +++ b/lib/cbor/utils/cbor_utils.dart @@ -1,7 +1,10 @@ import 'dart:typed_data'; -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/cbor/core/cbor.dart'; +import 'package:blockchain_utils/cbor/types/types.dart'; import 'package:blockchain_utils/cbor/utils/float_utils.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; +import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/utils/utils.dart'; class CborUtils { /// Decode a CBOR (Concise Binary Object Representation) data stream represented by a List. @@ -67,7 +70,7 @@ class CborUtils { "invalid or unsuported cbor tag major: $majorTag "); } } - throw ArgumentException("invalid or unsuported cbor tag"); + throw const ArgumentException("invalid or unsuported cbor tag"); } static Tuple, int> _parsBytes(int info, List cborBytes) { @@ -124,21 +127,21 @@ class CborUtils { if (tags.isEmpty) { toObj = CborStringValue(toString); } else if (CborBase64Types.values - .any((element) => bytesEqual(tags, element.tag))) { + .any((element) => BytesUtils.bytesEqual(tags, element.tag))) { final baseType = CborBase64Types.values - .firstWhere((element) => bytesEqual(tags, element.tag)); + .firstWhere((element) => BytesUtils.bytesEqual(tags, element.tag)); tags.clear(); toObj = CborBaseUrlValue(toString, baseType); - } else if (bytesEqual(tags, CborTags.mime)) { + } else if (BytesUtils.bytesEqual(tags, CborTags.mime)) { tags.clear(); toObj = CborMimeValue(toString); - } else if (bytesEqual(tags, CborTags.uri)) { + } else if (BytesUtils.bytesEqual(tags, CborTags.uri)) { tags.clear(); toObj = CborUriValue(toString); - } else if (bytesEqual(tags, CborTags.regexp)) { + } else if (BytesUtils.bytesEqual(tags, CborTags.regexp)) { tags.clear(); toObj = CborRegxpValue(toString); - } else if (bytesEqual(tags, CborTags.dateString)) { + } else if (BytesUtils.bytesEqual(tags, CborTags.dateString)) { tags.clear(); final time = parseRFC3339DateTime(toString); toObj = CborStringDateValue(time); @@ -164,10 +167,10 @@ class CborUtils { } final bytes = _parsBytes(info, cborBytes.sublist(i)); CborObject? val; - if (bytesEqual(tags, CborTags.negBigInt) || - bytesEqual(tags, CborTags.posBigInt)) { + if (BytesUtils.bytesEqual(tags, CborTags.negBigInt) || + BytesUtils.bytesEqual(tags, CborTags.posBigInt)) { BigInt big = BigintUtils.fromBytes(bytes.item1); - if (bytesEqual(tags, CborTags.negBigInt)) { + if (BytesUtils.bytesEqual(tags, CborTags.negBigInt)) { big = ~big; } tags.clear(); @@ -221,11 +224,11 @@ class CborUtils { index += decodeData.item2; if (index == cborBytes.length) break; } - if (bytesEqual(tags, CborTags.bigFloat) || - bytesEqual(tags, CborTags.decimalFrac)) { + if (BytesUtils.bytesEqual(tags, CborTags.bigFloat) || + BytesUtils.bytesEqual(tags, CborTags.decimalFrac)) { return Tuple(_decodeCborBigfloatOrDecimal(objects, tags), index); } - if (bytesEqual(tags, CborTags.set)) { + if (BytesUtils.bytesEqual(tags, CborTags.set)) { tags.clear(); final toObj = CborSetValue(objects.toSet()); return Tuple(tags.isEmpty ? toObj : CborTagValue(toObj, tags), index); @@ -251,9 +254,9 @@ class CborUtils { List objects, List tags) { objects = objects.whereType().toList(); if (objects.length != 2) { - throw MessageException("invalid bigFloat array length"); + throw const MessageException("invalid bigFloat array length"); } - if (bytesEqual(tags, CborTags.decimalFrac)) { + if (BytesUtils.bytesEqual(tags, CborTags.decimalFrac)) { tags.clear(); final toObj = CborDecimalFracValue.fromCborNumeric( objects[0] as CborNumeric, objects[1] as CborNumeric); @@ -271,16 +274,16 @@ class CborUtils { CborObject? obj; switch (info) { case SimpleTags.simpleFalse: - obj = CborBoleanValue(false); + obj = const CborBoleanValue(false); break; case SimpleTags.simpleTrue: - obj = CborBoleanValue(true); + obj = const CborBoleanValue(true); break; case SimpleTags.simpleNull: - obj = CborNullValue(); + obj = const CborNullValue(); break; case SimpleTags.simpleUndefined: - obj = CborUndefinedValue(); + obj = const CborUndefinedValue(); break; default: } @@ -310,9 +313,9 @@ class CborUtils { offset = offset + 8; break; default: - throw MessageException("Invalid simpleOrFloatTags"); + throw const MessageException("Invalid simpleOrFloatTags"); } - if (bytesEqual(tags, CborTags.dateEpoch)) { + if (BytesUtils.bytesEqual(tags, CborTags.dateEpoch)) { final dt = DateTime.fromMillisecondsSinceEpoch((val * 1000).round()); tags.clear(); obj = CborEpochFloatValue(dt); @@ -339,7 +342,7 @@ class CborUtils { numericValue = CborIntValue(numb); } final index = data.item2 + i; - if (bytesEqual(tags, CborTags.dateEpoch)) { + if (BytesUtils.bytesEqual(tags, CborTags.dateEpoch)) { final dt = DateTime.fromMillisecondsSinceEpoch(numericValue.toInt() * 1000); tags.clear(); diff --git a/lib/cbor/utils/dynamic_bytes.dart b/lib/cbor/utils/dynamic_bytes.dart index 6f8e883..4055c8d 100644 --- a/lib/cbor/utils/dynamic_bytes.dart +++ b/lib/cbor/utils/dynamic_bytes.dart @@ -1,5 +1,5 @@ -import 'package:blockchain_utils/blockchain_utils.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// A class for tracking and building a sequence of bytes (List) for CBOR encoding. class CborBytesTracker { diff --git a/lib/cbor/utils/float_utils.dart b/lib/cbor/utils/float_utils.dart index 647ab0b..d9d496e 100644 --- a/lib/cbor/utils/float_utils.dart +++ b/lib/cbor/utils/float_utils.dart @@ -18,7 +18,7 @@ import 'dart:typed_data'; import 'package:blockchain_utils/cbor/core/tags.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; // Enum representing different floating-point formats and their characteristics. class FloatLength { @@ -124,18 +124,18 @@ class FloatUtils { static Tuple _isLessThan(double value, [Endian? endian]) { if (value.isNaN || value.isInfinite) { - return Tuple(true, true); + return const Tuple(true, true); } final int bits = _toBits(value, endian); final isLesThan16 = _dobuleLessThan(bits, FloatLength.bytes16); if (isLesThan16) { - return Tuple(true, true); + return const Tuple(true, true); } final isLessThan32 = _dobuleLessThan(bits, FloatLength.bytes32); if (isLessThan32) { - return Tuple(false, true); + return const Tuple(false, true); } - return Tuple(false, false); + return const Tuple(false, false); } static bool _dobuleLessThan(int bits, FloatLength type) { @@ -242,13 +242,13 @@ class FloatUtils { switch (decodFloatType) { case FloatLength.bytes16: if (!isLessThan16) { - throw ArgumentException("overflow bytes"); + throw const ArgumentException("overflow bytes"); } bytes = _encodeFloat16(endianness); break; case FloatLength.bytes32: if (!isLessThan32) { - throw ArgumentException("overflow bytes"); + throw const ArgumentException("overflow bytes"); } bytes = _encodeFloat32(endianness); break; @@ -262,7 +262,7 @@ class FloatUtils { /// Decode a 16-bit floating-point value from a byte array and return it as a double. static double floatFromBytes16(List bytes) { if (bytes.length != 2) { - throw ArgumentException( + throw const ArgumentException( 'Input byte array must be exactly 2 bytes long for Float16'); } diff --git a/lib/compare/compare.dart b/lib/compare/compare.dart deleted file mode 100644 index 3e70684..0000000 --- a/lib/compare/compare.dart +++ /dev/null @@ -1,74 +0,0 @@ -import 'dart:core'; - -/// Compare two lists of bytes for equality. -/// This function compares two lists of bytes 'a' and 'b' for equality. It returns true -/// if the lists are equal (including null check), false if they have different lengths -/// or contain different byte values, and true if the lists reference the same object. -bool bytesEqual(List? a, List? b) { - /// Check if 'a' is null and handle null comparison. - if (a == null) { - return b == null; - } - - /// Check if 'b' is null or if the lengths of 'a' and 'b' are different. - if (b == null || a.length != b.length) { - return false; - } - - /// Check if 'a' and 'b' reference the same object (identity comparison). - if (identical(a, b)) { - return true; - } - - /// Compare the individual byte values in 'a' and 'b'. - for (int index = 0; index < a.length; index += 1) { - if (a[index] != b[index]) { - return false; - } - } - - /// If no differences were found, the lists are equal. - return true; -} - -/// Compare two lists of bytes for equality. -/// This function compares two lists of bytes 'a' and 'b' for equality. It returns true -/// if the lists are equal (including null check), false if they have different lengths -/// or contain different byte values, and true if the lists reference the same object. -bool iterableIsEqual(Iterable? a, Iterable? b) { - /// Check if 'a' is null and handle null comparison. - if (a == null) { - return b == null; - } - - /// Check if 'b' is null or if the lengths of 'a' and 'b' are different. - if (b == null || a.length != b.length) { - return false; - } - - /// Check if 'a' and 'b' reference the same object (identity comparison). - if (identical(a, b)) { - return true; - } - - /// Compare the individual byte values in 'a' and 'b'. - for (int index = 0; index < a.length; index += 1) { - if (a.elementAt(index) != b.elementAt(index)) { - return false; - } - } - - /// If no differences were found, the lists are equal. - return true; -} - -bool isLessThanBytes(List thashedA, List thashedB) { - for (int i = 0; i < thashedA.length && i < thashedB.length; i++) { - if (thashedA[i] < thashedB[i]) { - return true; - } else if (thashedA[i] > thashedB[i]) { - return false; - } - } - return thashedA.length < thashedB.length; -} diff --git a/lib/crypto/crypto/aes/aes.dart b/lib/crypto/crypto/aes/aes.dart index 63c4a03..d29629e 100644 --- a/lib/crypto/crypto/aes/aes.dart +++ b/lib/crypto/crypto/aes/aes.dart @@ -1,5 +1,5 @@ import 'package:blockchain_utils/crypto/crypto/blockcipher/blockcipher.dart'; -import 'package:blockchain_utils/binary/binary_operation.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; import 'aes_lib.dart' as aes_lib; @@ -71,10 +71,11 @@ class AES implements BlockCipher { @override AES setKey(List key, [bool noDecryption = false]) { if (key.length != 16 && key.length != 24 && key.length != 32) { - throw ArgumentException("AES: wrong key size (must be 16, 24, or 32)"); + throw const ArgumentException( + "AES: wrong key size (must be 16, 24, or 32)"); } if (_keyLen != key.length) { - throw ArgumentException("AES: initialized with different key size"); + throw const ArgumentException("AES: initialized with different key size"); } _encKey ??= List.filled(key.length + 28, 0, growable: false); @@ -130,14 +131,14 @@ class AES implements BlockCipher { List encryptBlock(List src, [List? dst]) { final out = dst ?? List.filled(blockSize, 0); if (src.length != blockSize) { - throw ArgumentException("AES: invalid source block size"); + throw const ArgumentException("AES: invalid source block size"); } if (out.length != blockSize) { - throw ArgumentException("AES: invalid destination block size"); + throw const ArgumentException("AES: invalid destination block size"); } if (_encKey == null) { - throw MessageException("AES: encryption key is not available"); + throw const MessageException("AES: encryption key is not available"); } _lib.encryptBlock(_encKey!, src, out); @@ -164,14 +165,14 @@ class AES implements BlockCipher { List decryptBlock(List src, [List? dst]) { final out = dst ?? List.filled(blockSize, 0); if (src.length != blockSize) { - throw ArgumentException("AES: invaiid source block size"); + throw const ArgumentException("AES: invaiid source block size"); } if (out.length != blockSize) { - throw ArgumentException("AES: invalid destination block size"); + throw const ArgumentException("AES: invalid destination block size"); } if (_decKey == null) { - throw MessageException( + throw const MessageException( "AES: decrypting with an instance created with noDecryption option"); } else { _lib.decryptBlock(_decKey!, src, out); diff --git a/lib/crypto/crypto/aes/aes_lib.dart b/lib/crypto/crypto/aes/aes_lib.dart index e5b0d4e..29460bc 100644 --- a/lib/crypto/crypto/aes/aes_lib.dart +++ b/lib/crypto/crypto/aes/aes_lib.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/binary_operation.dart'; +import 'package:blockchain_utils/utils/utils.dart'; class AESLib { AESLib._() { diff --git a/lib/crypto/crypto/aes/padding.dart b/lib/crypto/crypto/aes/padding.dart index 2866687..40f60d8 100644 --- a/lib/crypto/crypto/aes/padding.dart +++ b/lib/crypto/crypto/aes/padding.dart @@ -67,11 +67,11 @@ class BlockCipherPadding { int paddedDataLen = paddedData.length; if (paddedDataLen == 0) { - throw ArgumentException('Zero-length input cannot be unpadded'); + throw const ArgumentException('Zero-length input cannot be unpadded'); } if (paddedDataLen % blockSize != 0) { - throw ArgumentException('Input data is not padded'); + throw const ArgumentException('Input data is not padded'); } int paddingLen; @@ -79,34 +79,34 @@ class BlockCipherPadding { if (style == PaddingAlgorithm.pkcs7 || style == PaddingAlgorithm.x923) { paddingLen = paddedData[paddedDataLen - 1]; if (paddingLen < 1 || paddingLen > blockSize) { - throw ArgumentException('incorrect padding'); + throw const ArgumentException('incorrect padding'); } if (style == PaddingAlgorithm.pkcs7) { for (int i = 1; i <= paddingLen; i++) { if (paddedData[paddedDataLen - i] != paddingLen) { - throw ArgumentException('incorrect padding'); + throw const ArgumentException('incorrect padding'); } } } else { for (int i = 1; i < paddingLen; i++) { if (paddedData[paddedDataLen - i - 1] != 0) { - throw ArgumentException('incorrect padding'); + throw const ArgumentException('incorrect padding'); } } } } else { int index = paddedData.lastIndexOf(128); if (index < 0) { - throw ArgumentException('incorrect padding'); + throw const ArgumentException('incorrect padding'); } paddingLen = paddedDataLen - index; if (paddingLen < 1 || paddingLen > blockSize) { - throw ArgumentException('incorrect padding'); + throw const ArgumentException('incorrect padding'); } for (int i = 1; i < paddingLen; i++) { if (paddedData[index + i] != 0) { - throw ArgumentException('incorrect padding'); + throw const ArgumentException('incorrect padding'); } } } diff --git a/lib/crypto/crypto/cdsa/curve/curve.dart b/lib/crypto/crypto/cdsa/curve/curve.dart index f0eb507..5c1c08d 100644 --- a/lib/crypto/crypto/cdsa/curve/curve.dart +++ b/lib/crypto/crypto/cdsa/curve/curve.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// This class represents a finite field elliptic curve defined over a prime field (Fp). class CurveFp extends Curve { diff --git a/lib/crypto/crypto/cdsa/ecdsa/private_key.dart b/lib/crypto/crypto/cdsa/ecdsa/private_key.dart index f0ffcae..f093023 100644 --- a/lib/crypto/crypto/cdsa/ecdsa/private_key.dart +++ b/lib/crypto/crypto/cdsa/ecdsa/private_key.dart @@ -1,7 +1,7 @@ import 'dart:typed_data'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/ecdsa/signature.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/ec_projective_point.dart'; import 'public_key.dart'; @@ -23,7 +23,7 @@ class ECDSAPrivateKey { /// factory ECDSAPrivateKey.fromBytes(List bytes, ProjectiveECCPoint curve) { if (bytes.length != curve.curve.baselen) { - throw ArgumentException("Invalid length of private key"); + throw const ArgumentException("Invalid length of private key"); } final secexp = BigintUtils.fromBytes(bytes, byteOrder: Endian.big); final ECDSAPublicKey publicKey = ECDSAPublicKey(curve, curve * secexp); @@ -62,7 +62,7 @@ class ECDSAPrivateKey { } if (r == BigInt.zero) { - throw MessageException("unlucky random number r"); + throw const MessageException("unlucky random number r"); } BigInt s = @@ -70,7 +70,7 @@ class ECDSAPrivateKey { n; if (s == BigInt.zero) { - throw MessageException("unlucky random number s"); + throw const MessageException("unlucky random number s"); } return ECDSASignature(r, s); diff --git a/lib/crypto/crypto/cdsa/ecdsa/public_key.dart b/lib/crypto/crypto/cdsa/ecdsa/public_key.dart index ab25ce4..a2292e2 100644 --- a/lib/crypto/crypto/cdsa/ecdsa/public_key.dart +++ b/lib/crypto/crypto/cdsa/ecdsa/public_key.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/ecdsa/signature.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/base.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/ec_projective_point.dart'; @@ -26,19 +26,20 @@ class ECDSAPublicKey { if (!(BigInt.zero <= point.x && point.x < p) || !(BigInt.zero <= point.y && point.y < p)) { - throw ArgumentException("The public point has x or y out of range."); + throw const ArgumentException( + "The public point has x or y out of range."); } if (verify && !curve.containsPoint(point.x, point.y)) { - throw ArgumentException("AffinePointt does not lay on the curve"); + throw const ArgumentException("AffinePointt does not lay on the curve"); } if (n == null) { - throw ArgumentException("Generator point must have order."); + throw const ArgumentException("Generator point must have order."); } if (verify && curve.cofactor() != BigInt.one && !(point * n).isInfinity) { - throw ArgumentException("Generator point order is bad."); + throw const ArgumentException("Generator point order is bad."); } return ECDSAPublicKey._(generator, point); } diff --git a/lib/crypto/crypto/cdsa/ecdsa/signature.dart b/lib/crypto/crypto/cdsa/ecdsa/signature.dart index 53859cb..f85504c 100644 --- a/lib/crypto/crypto/cdsa/ecdsa/signature.dart +++ b/lib/crypto/crypto/cdsa/ecdsa/signature.dart @@ -1,5 +1,8 @@ -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/crypto/crypto/cdsa/ecdsa/public_key.dart'; +import 'package:blockchain_utils/crypto/crypto/cdsa/point/ec_projective_point.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/utils/utils.dart'; +import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// Represents an ECDSA (Elliptic Curve Digital Signature Algorithm) signature /// containing `r` and `s` components. diff --git a/lib/crypto/crypto/cdsa/eddsa/privatekey.dart b/lib/crypto/crypto/cdsa/eddsa/privatekey.dart index b292024..b3f45de 100644 --- a/lib/crypto/crypto/cdsa/eddsa/privatekey.dart +++ b/lib/crypto/crypto/cdsa/eddsa/privatekey.dart @@ -1,12 +1,9 @@ import 'dart:typed_data'; - -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curves.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/eddsa/publickey.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/edwards.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; -import 'package:blockchain_utils/compare/compare.dart'; import 'package:blockchain_utils/exception/exception.dart'; /// Represents an EdDSA private key and provides methods for key operations. @@ -87,7 +84,7 @@ class EDDSAPrivateKey { bool operator ==(Object other) { if (other is EDDSAPrivateKey) { return generator.curve == other.generator.curve && - bytesEqual(_privateKey, other._privateKey); + BytesUtils.bytesEqual(_privateKey, other._privateKey); } return false; } @@ -101,7 +98,8 @@ class EDDSAPrivateKey { } else if (h == BigInt.from(8)) { hLog = 3; } else { - throw ArgumentException('Only cofactor 4 and 8 curves are supported'); + throw const ArgumentException( + 'Only cofactor 4 and 8 curves are supported'); } key[0] &= ~((1 << hLog) - 1); diff --git a/lib/crypto/crypto/cdsa/eddsa/publickey.dart b/lib/crypto/crypto/cdsa/eddsa/publickey.dart index ba63287..c9896cc 100644 --- a/lib/crypto/crypto/cdsa/eddsa/publickey.dart +++ b/lib/crypto/crypto/cdsa/eddsa/publickey.dart @@ -1,11 +1,8 @@ import 'dart:typed_data'; - -import 'package:blockchain_utils/binary/binary.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curves.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/edwards.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; -import 'package:blockchain_utils/compare/compare.dart'; import 'package:blockchain_utils/exception/exception.dart'; /// Represents an EdDSA public key in the Edwards curve format. @@ -98,7 +95,7 @@ class EDDSAPublicKey { bool operator ==(other) { if (other is EDDSAPublicKey) { return generator.curve == other.generator.curve && - bytesEqual(_encoded, other._encoded); + BytesUtils.bytesEqual(_encoded, other._encoded); } return false; } @@ -157,7 +154,7 @@ class EDDSAPublicKey { byteOrder: Endian.little); if (S >= generator.order!) { - throw ArgumentException('Invalid signature'); + throw const ArgumentException('Invalid signature'); } List dom = List.empty(); diff --git a/lib/crypto/crypto/cdsa/point/base.dart b/lib/crypto/crypto/cdsa/point/base.dart index c00ced6..cc67dc6 100644 --- a/lib/crypto/crypto/cdsa/point/base.dart +++ b/lib/crypto/crypto/cdsa/point/base.dart @@ -1,12 +1,9 @@ import 'dart:typed_data'; - -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curve.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/edwards.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; /// An enumeration representing different types of encoding for elliptic curve points. enum EncodeType { comprossed, hybrid, raw, uncompressed } @@ -141,12 +138,12 @@ abstract class AbstractPoint { } else if (prefix == 0x06 || prefix == 0x07) { encodeType = EncodeType.hybrid; } else { - throw ArgumentException("invalid key length"); + throw const ArgumentException("invalid key length"); } } else if (keyLen == rawEncodingLength ~/ 2 + 1) { encodeType = EncodeType.comprossed; } else { - throw ArgumentException("invalid key length"); + throw const ArgumentException("invalid key length"); } } curve as CurveFp; @@ -169,7 +166,8 @@ abstract class AbstractPoint { final expLen = (p.bitLength + 1 + 7) ~/ 8; if (data.length != expLen) { - throw ArgumentException("AffinePointt length doesn't match the curve."); + throw const ArgumentException( + "AffinePointt length doesn't match the curve."); } final x0 = (data[expLen - 1] & 0x80) >> 7; @@ -211,7 +209,7 @@ abstract class AbstractPoint { /// Creates an elliptic curve point from a compressed byte encoding. static Tuple _fromCompressed(List data, CurveFp curve) { if (data[0] != 0x02 && data[0] != 0x03) { - throw ArgumentException('Malformed compressed point encoding'); + throw const ArgumentException('Malformed compressed point encoding'); } final isEven = data[0] == 0x02; @@ -243,7 +241,7 @@ abstract class AbstractPoint { // Validate if it's self-consistent if we're asked to do that if (((prefix == BigInt.one && data[0] != 0x07) || (prefix == BigInt.zero && data[0] != 0x06))) { - throw ArgumentException('Inconsistent hybrid point encoding'); + throw const ArgumentException('Inconsistent hybrid point encoding'); } return Tuple(x, y); diff --git a/lib/crypto/crypto/cdsa/point/ec_projective_point.dart b/lib/crypto/crypto/cdsa/point/ec_projective_point.dart index 4066d4e..357b3fb 100644 --- a/lib/crypto/crypto/cdsa/point/ec_projective_point.dart +++ b/lib/crypto/crypto/cdsa/point/ec_projective_point.dart @@ -23,7 +23,7 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curve.dart'; import 'base.dart'; import 'point.dart'; @@ -364,7 +364,7 @@ class ProjectiveECCPoint extends AbstractPoint { factory ProjectiveECCPoint.fromAffine(AbstractPoint point, {bool generator = false}) { if (point is! ProjectiveECCPoint && point is! AffinePointt) { - throw ArgumentException("invalid Affine point"); + throw const ArgumentException("invalid Affine point"); } return ProjectiveECCPoint._( point.curve as CurveFp, [point.x, point.y, BigInt.one], @@ -643,7 +643,7 @@ class ProjectiveECCPoint extends AbstractPoint { other = ProjectiveECCPoint.fromAffine(other); } if (curve != other.curve) { - throw ArgumentException("The other point is on a different curve"); + throw const ArgumentException("The other point is on a different curve"); } other as ProjectiveECCPoint; diff --git a/lib/crypto/crypto/cdsa/point/edwards.dart b/lib/crypto/crypto/cdsa/point/edwards.dart index 9f5d831..f52016f 100644 --- a/lib/crypto/crypto/cdsa/point/edwards.dart +++ b/lib/crypto/crypto/cdsa/point/edwards.dart @@ -23,7 +23,7 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curve.dart'; import 'base.dart'; import 'package:blockchain_utils/exception/exception.dart'; @@ -400,7 +400,7 @@ class EDPoint extends AbstractPoint { @override EDPoint operator +(AbstractPoint other) { if (other is! EDPoint || curve != other.curve) { - throw ArgumentException("The other point is on a different curve."); + throw const ArgumentException("The other point is on a different curve."); } if (other.isInfinity) { return this; diff --git a/lib/crypto/crypto/cdsa/point/point.dart b/lib/crypto/crypto/cdsa/point/point.dart index 24a562d..e72df88 100644 --- a/lib/crypto/crypto/cdsa/point/point.dart +++ b/lib/crypto/crypto/cdsa/point/point.dart @@ -22,7 +22,7 @@ // 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:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curve.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/ec_projective_point.dart'; import 'package:blockchain_utils/exception/exception.dart'; diff --git a/lib/crypto/crypto/cdsa/point/ristretto_point.dart b/lib/crypto/crypto/cdsa/point/ristretto_point.dart index 40ee767..14a4285 100644 --- a/lib/crypto/crypto/cdsa/point/ristretto_point.dart +++ b/lib/crypto/crypto/cdsa/point/ristretto_point.dart @@ -1,7 +1,7 @@ import 'dart:typed_data'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curve.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curves.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/base.dart'; @@ -93,7 +93,7 @@ class RistrettoPoint extends EDPoint { final P = c.p; final s = BigintUtils.fromBytes(hex, byteOrder: Endian.little); if (ristretto_tools.isOdd(s, P)) { - throw ArgumentException("Invalid RistrettoPoint"); + throw const ArgumentException("Invalid RistrettoPoint"); } final s2 = ristretto_tools.positiveMod(s * s, P); final u1 = ristretto_tools.positiveMod(BigInt.one + a * s2, P); @@ -114,7 +114,7 @@ class RistrettoPoint extends EDPoint { final y = ristretto_tools.positiveMod(u1 * y2, P); final t = ristretto_tools.positiveMod(x * y, P); if (!invSqrt.item1 || ristretto_tools.isOdd(t, P) || y == BigInt.zero) { - throw ArgumentException("Invalid RistrettoPoint"); + throw const ArgumentException("Invalid RistrettoPoint"); } return RistrettoPoint.fromEdwardsPoint( EDPoint(curve: c, x: x, y: y, z: BigInt.one, t: t)); diff --git a/lib/crypto/crypto/cdsa/rfc6979/rfc6979.dart b/lib/crypto/crypto/cdsa/rfc6979/rfc6979.dart index bad2afa..80fd311 100644 --- a/lib/crypto/crypto/cdsa/rfc6979/rfc6979.dart +++ b/lib/crypto/crypto/cdsa/rfc6979/rfc6979.dart @@ -23,7 +23,7 @@ // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:blockchain_utils/crypto/crypto/hmac/hmac.dart'; diff --git a/lib/crypto/crypto/cdsa/utils/ed25519_utils.dart b/lib/crypto/crypto/cdsa/utils/ed25519_utils.dart index cc3f837..9c1b25c 100644 --- a/lib/crypto/crypto/cdsa/utils/ed25519_utils.dart +++ b/lib/crypto/crypto/cdsa/utils/ed25519_utils.dart @@ -1,6 +1,6 @@ import 'dart:typed_data'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curves.dart'; /// Utility class for Ed25519-specific operations. diff --git a/lib/crypto/crypto/cdsa/utils/exp.dart b/lib/crypto/crypto/cdsa/utils/exp.dart index 40aae87..02164b1 100644 --- a/lib/crypto/crypto/cdsa/utils/exp.dart +++ b/lib/crypto/crypto/cdsa/utils/exp.dart @@ -9,7 +9,10 @@ class SquareRootError implements BlockchainUtilsException { @override final String message; - const SquareRootError(this.message); + @override + final Map? details; + + const SquareRootError(this.message, {this.details}); @override String toString() { @@ -26,7 +29,10 @@ class JacobiError implements BlockchainUtilsException { @override final String message; - const JacobiError(this.message); + @override + final Map? details; + + const JacobiError(this.message, {this.details}); @override String toString() { diff --git a/lib/crypto/crypto/cdsa/utils/ristretto_utils.dart b/lib/crypto/crypto/cdsa/utils/ristretto_utils.dart index a5075da..9d8b176 100644 --- a/lib/crypto/crypto/cdsa/utils/ristretto_utils.dart +++ b/lib/crypto/crypto/cdsa/utils/ristretto_utils.dart @@ -1,5 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curves.dart'; diff --git a/lib/crypto/crypto/cdsa/utils/utils.dart b/lib/crypto/crypto/cdsa/utils/utils.dart index f133c77..a222ab9 100644 --- a/lib/crypto/crypto/cdsa/utils/utils.dart +++ b/lib/crypto/crypto/cdsa/utils/utils.dart @@ -91,7 +91,7 @@ class ECDSAUtils { } } - throw MessageException("No suitable 'b' found."); + throw const MessageException("No suitable 'b' found."); } /// Multiply two polynomials represented by lists 'm1' and 'm2', reducing modulo 'polymod' and prime 'p'. diff --git a/lib/crypto/crypto/chacha/chacha.dart b/lib/crypto/crypto/chacha/chacha.dart index 14d7ec5..bdcdd69 100644 --- a/lib/crypto/crypto/chacha/chacha.dart +++ b/lib/crypto/crypto/chacha/chacha.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/binary_operation.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; class ChaCha20 { @@ -96,7 +96,7 @@ class ChaCha20 { len--; } if (carry > 0) { - throw MessageException("ChaCha: counter overflow"); + throw const MessageException("ChaCha: counter overflow"); } } @@ -128,11 +128,12 @@ class ChaCha20 { {int nonceInplaceCounterLength = 0}) { // We only support 256-bit keys. if (key.length != 32) { - throw ArgumentException("ChaCha: key size must be 32 bytes"); + throw const ArgumentException("ChaCha: key size must be 32 bytes"); } if (dst.length < src.length) { - throw ArgumentException("ChaCha: destination is shorter than source"); + throw const ArgumentException( + "ChaCha: destination is shorter than source"); } List nc; @@ -140,14 +141,15 @@ class ChaCha20 { if (nonceInplaceCounterLength == 0) { if (nonce.length != 8 && nonce.length != 12) { - throw ArgumentException("ChaCha nonce must be 8 or 12 bytes"); + throw const ArgumentException("ChaCha nonce must be 8 or 12 bytes"); } nc = List.filled(16, 0); counterLength = nc.length - nonce.length; nc.setAll(counterLength, nonce); } else { if (nonce.length != 16) { - throw ArgumentException("ChaCha nonce with counter must be 16 bytes"); + throw const ArgumentException( + "ChaCha nonce with counter must be 16 bytes"); } nc = nonce; counterLength = nonceInplaceCounterLength; diff --git a/lib/crypto/crypto/chacha20poly1305/chacha20poly1305.dart b/lib/crypto/crypto/chacha20poly1305/chacha20poly1305.dart index a61a943..15d4e7c 100644 --- a/lib/crypto/crypto/chacha20poly1305/chacha20poly1305.dart +++ b/lib/crypto/crypto/chacha20poly1305/chacha20poly1305.dart @@ -1,9 +1,7 @@ -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/compare/compare.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/aead/aead.dart'; import 'package:blockchain_utils/crypto/crypto/chacha/chacha.dart'; import 'package:blockchain_utils/crypto/crypto/poly1305/poly1305.dart'; -import 'package:blockchain_utils/binary/binary_operation.dart'; import 'package:blockchain_utils/exception/exception.dart'; const int _nonceLength = 12; @@ -25,7 +23,7 @@ class ChaCha20Poly1305 implements AEAD { /// Creates a ChaCha20-Poly1305 instance with the given 32-byte encryption key. ChaCha20Poly1305(List key) { if (key.length != _keyLength) { - throw ArgumentException("ChaCha20Poly1305 needs a 32-byte key"); + throw const ArgumentException("ChaCha20Poly1305 needs a 32-byte key"); } _key = BytesUtils.toBytes(key); } @@ -55,7 +53,7 @@ class ChaCha20Poly1305 implements AEAD { List encrypt(List nonce, List plaintext, {List? associatedData, List? dst}) { if (nonce.length > 16) { - throw ArgumentException("ChaCha20Poly1305: incorrect nonce length"); + throw const ArgumentException("ChaCha20Poly1305: incorrect nonce length"); } final counter = List.filled(16, 0); @@ -70,7 +68,8 @@ class ChaCha20Poly1305 implements AEAD { List result = dst ?? List.filled(resultLength, 0); if (result.length != resultLength) { - throw ArgumentException("ChaCha20Poly1305: incorrect destination length"); + throw const ArgumentException( + "ChaCha20Poly1305: incorrect destination length"); } ChaCha20.streamXOR(_key, counter, BytesUtils.toBytes(plaintext), result, @@ -111,7 +110,7 @@ class ChaCha20Poly1305 implements AEAD { List? decrypt(List nonce, List sealed, {List? associatedData, List? dst}) { if (nonce.length > 16) { - throw ArgumentException("ChaCha20Poly1305: incorrect nonce length"); + throw const ArgumentException("ChaCha20Poly1305: incorrect nonce length"); } if (sealed.length < tagLength) { @@ -128,7 +127,8 @@ class ChaCha20Poly1305 implements AEAD { _authenticate(calculatedTag, authKey, sealed.sublist(0, sealed.length - tagLength), associatedData); - if (!bytesEqual(calculatedTag, sealed.sublist(sealed.length - tagLength))) { + if (!BytesUtils.bytesEqual( + calculatedTag, sealed.sublist(sealed.length - tagLength))) { return null; } @@ -136,7 +136,8 @@ class ChaCha20Poly1305 implements AEAD { List result = dst ?? List.filled(resultLength, 0); if (result.length != resultLength) { - throw ArgumentException("ChaCha20Poly1305: incorrect destination length"); + throw const ArgumentException( + "ChaCha20Poly1305: incorrect destination length"); } ChaCha20.streamXOR( diff --git a/lib/crypto/crypto/crc16/crc16.dart b/lib/crypto/crypto/crc16/crc16.dart new file mode 100644 index 0000000..4e909e1 --- /dev/null +++ b/lib/crypto/crypto/crc16/crc16.dart @@ -0,0 +1,27 @@ +import 'package:blockchain_utils/utils/utils.dart'; + +class Crc16 { + static const int _poly = 0x1021; + + static List quickIntDigest(List data) { + int reg = 0; + List message = List.filled(data.length + 2, 0); + message.setAll(0, data); + + for (int byte in message) { + int mask = 0x80; + while (mask > 0) { + reg <<= 1; + if (byte & mask != 0) { + reg += 1; + } + mask >>= 1; + if (reg > mask16) { + reg &= mask16; + reg ^= _poly; + } + } + } + return List.from([reg >> 8, reg & mask8]); + } +} diff --git a/lib/crypto/crypto/crc32/crc32.dart b/lib/crypto/crypto/crc32/crc32.dart index 325023a..64f9844 100644 --- a/lib/crypto/crypto/crc32/crc32.dart +++ b/lib/crypto/crypto/crc32/crc32.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/binary_operation.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// A class for calculating cyclic redundancy check (CRC32) values. /// diff --git a/lib/crypto/crypto/crypto.dart b/lib/crypto/crypto/crypto.dart index 006dae4..c60f9f6 100644 --- a/lib/crypto/crypto/crypto.dart +++ b/lib/crypto/crypto/crypto.dart @@ -61,3 +61,5 @@ export 'scrypt/scrypt.dart'; /// Export statement for the XMODEM CRC (Cyclic Redundancy Check) for error-checking in data transmission. export 'x_modem_crc/x_modem_crc.dart'; + +export 'crc16/crc16.dart'; diff --git a/lib/crypto/crypto/ctr/ctr.dart b/lib/crypto/crypto/ctr/ctr.dart index eeab884..bda1296 100644 --- a/lib/crypto/crypto/ctr/ctr.dart +++ b/lib/crypto/crypto/ctr/ctr.dart @@ -1,5 +1,5 @@ import 'package:blockchain_utils/crypto/crypto/blockcipher/blockcipher.dart'; -import 'package:blockchain_utils/binary/binary_operation.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; /// Counter (CTR) mode for block ciphers. @@ -71,7 +71,7 @@ class CTR { _cipher = null; if (iv != null && iv.length != _counter.length) { - throw ArgumentException( + throw const ArgumentException( "CTR: iv length must be equal to cipher block size"); } _cipher = cipher; @@ -160,6 +160,6 @@ void _incrementCounter(List counter) { carry >>= 8; } if (carry > 0) { - throw ArgumentException("CTR: counter overflow"); + throw const ArgumentException("CTR: counter overflow"); } } diff --git a/lib/crypto/crypto/ecb/ecb.dart b/lib/crypto/crypto/ecb/ecb.dart index e8aa223..4e97f10 100644 --- a/lib/crypto/crypto/ecb/ecb.dart +++ b/lib/crypto/crypto/ecb/ecb.dart @@ -50,7 +50,7 @@ class ECB extends AES { final out = dst ?? List.filled(input.length, 0); if (out.length != input.length) { - throw ArgumentException( + throw const ArgumentException( "The destination size does not match with source size"); } final numBlocks = input.length ~/ blockSize; @@ -106,7 +106,7 @@ class ECB extends AES { } if (dst != null) { if (dst.length < out.length) { - throw ArgumentException("Destination size is small"); + throw const ArgumentException("Destination size is small"); } dst.setAll(0, out); return dst; diff --git a/lib/crypto/crypto/gcm/gcm.dart b/lib/crypto/crypto/gcm/gcm.dart index 1208f1e..6180397 100644 --- a/lib/crypto/crypto/gcm/gcm.dart +++ b/lib/crypto/crypto/gcm/gcm.dart @@ -1,8 +1,7 @@ -import 'package:blockchain_utils/compare/compare.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/aead/aead.dart'; import 'package:blockchain_utils/crypto/crypto/blockcipher/blockcipher.dart'; import 'package:blockchain_utils/crypto/crypto/ctr/ctr.dart'; -import 'package:blockchain_utils/binary/binary_operation.dart'; import 'package:blockchain_utils/exception/exception.dart'; import 'dart:math' as math; @@ -29,7 +28,7 @@ class GCM implements AEAD { /// - `ArgumentException` if the provided block cipher does not have a 16-byte block size. GCM(BlockCipher cipher) { if (cipher.blockSize != 16) { - throw ArgumentException("GCM supports only 16-byte block cipher"); + throw const ArgumentException("GCM supports only 16-byte block cipher"); } _cipher = cipher; @@ -60,7 +59,7 @@ class GCM implements AEAD { List encrypt(List nonce, List plaintext, {List? associatedData, List? dst}) { if (nonce.length != nonceLength) { - throw ArgumentException("GCM: incorrect nonce length"); + throw const ArgumentException("GCM: incorrect nonce length"); } final blockSize = _cipher.blockSize; @@ -68,7 +67,7 @@ class GCM implements AEAD { final resultLength = plaintext.length + tagLength; List result = dst ?? List.filled(resultLength, 0); if (result.length != resultLength) { - throw ArgumentException("GCM: incorrect destination length"); + throw const ArgumentException("GCM: incorrect destination length"); } final counter = List.filled(blockSize, 0); @@ -115,7 +114,7 @@ class GCM implements AEAD { List? decrypt(List nonce, List sealed, {List? associatedData, List? dst}) { if (nonce.length != nonceLength) { - throw ArgumentException("GCM: incorrect nonce length"); + throw const ArgumentException("GCM: incorrect nonce length"); } if (sealed.length < tagLength) { @@ -138,14 +137,15 @@ class GCM implements AEAD { _authenticate(calculatedTag, tagMask, sealed.sublist(0, sealed.length - tagLength), associatedData); - if (!bytesEqual(calculatedTag, sealed.sublist(sealed.length - tagLength))) { + if (!BytesUtils.bytesEqual( + calculatedTag, sealed.sublist(sealed.length - tagLength))) { return null; } final resultLength = sealed.length - tagLength; List result = dst ?? List.filled(resultLength, 0); if (result.length != resultLength) { - throw ArgumentException("GCM: incorrect destination length"); + throw const ArgumentException("GCM: incorrect destination length"); } final ctr = CTR(_cipher, counter); ctr.streamXOR(sealed.sublist(0, sealed.length - tagLength), result); diff --git a/lib/crypto/crypto/hash/black2b/black2b.dart b/lib/crypto/crypto/hash/black2b/black2b.dart index 2fc6956..8113f52 100644 --- a/lib/crypto/crypto/hash/black2b/black2b.dart +++ b/lib/crypto/crypto/hash/black2b/black2b.dart @@ -164,7 +164,7 @@ class BLAKE2b implements SerializableHash { /// - An exception if the provided `digestLength` is out of the valid range. BLAKE2b({int digestLength = 64, Blake2bConfig? config}) { if (digestLength < 1 || digestLength > _digestLength) { - throw ArgumentException("blake2b: wrong digest length"); + throw const ArgumentException("blake2b: wrong digest length"); } getDigestLength = digestLength; @@ -251,28 +251,29 @@ class BLAKE2b implements SerializableHash { void _validateConfig(Blake2bConfig config) { if (config.key != null && config.key!.length > _keyLength) { - throw ArgumentException("blake2b: wrong key length"); + throw const ArgumentException("blake2b: wrong key length"); } if (config.salt != null && config.salt!.length != _saltLength) { - throw ArgumentException("blake2b: wrong salt length"); + throw const ArgumentException("blake2b: wrong salt length"); } if (config.personalization != null && config.personalization!.length != _personalizationLength) { - throw ArgumentException("blake2b: wrong personalization length"); + throw const ArgumentException("blake2b: wrong personalization length"); } if (config.tree != null) { if (config.tree!.fanout < 0 || config.tree!.fanout > _maxFanout) { - throw ArgumentException("blake2b: wrong tree fanout"); + throw const ArgumentException("blake2b: wrong tree fanout"); } if (config.tree!.maxDepth < 0 || config.tree!.maxDepth > _maxMaxDepth) { - throw ArgumentException("blake2b: wrong tree depth"); + throw const ArgumentException("blake2b: wrong tree depth"); } if (config.tree!.leafSize < 0 || config.tree!.leafSize > _maxLeafSize) { - throw ArgumentException("blake2b: wrong leaf size"); + throw const ArgumentException("blake2b: wrong leaf size"); } if (config.tree!.innerDigestLength < 0 || config.tree!.innerDigestLength > _digestLength) { - throw ArgumentException("blake2b: wrong tree inner digest length"); + throw const ArgumentException( + "blake2b: wrong tree inner digest length"); } } } @@ -293,7 +294,7 @@ class BLAKE2b implements SerializableHash { @override BLAKE2b update(List data, {int? length}) { if (_finished) { - throw ArgumentException( + throw const ArgumentException( "blake2b: can't update because hash was finished."); } @@ -702,7 +703,7 @@ class BLAKE2b implements SerializableHash { @override Blake2bState saveState() { if (_finished) { - throw MessageException("blake2b: cannot save finished state"); + throw const MessageException("blake2b: cannot save finished state"); } return Blake2bState( diff --git a/lib/crypto/crypto/hash/hash.dart b/lib/crypto/crypto/hash/hash.dart index 2153362..6113d26 100644 --- a/lib/crypto/crypto/hash/hash.dart +++ b/lib/crypto/crypto/hash/hash.dart @@ -15,8 +15,7 @@ /// -.... library hash; -import 'package:blockchain_utils/binary/binary_operation.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'dart:math' as math; import 'package:blockchain_utils/exception/exception.dart'; diff --git a/lib/crypto/crypto/hash/keccack/sha3.dart b/lib/crypto/crypto/hash/keccack/sha3.dart index c31cb74..da60103 100644 --- a/lib/crypto/crypto/hash/keccack/sha3.dart +++ b/lib/crypto/crypto/hash/keccack/sha3.dart @@ -20,7 +20,7 @@ class _Keccack { late final int blockSize; _Keccack([int capacity = 32]) { if (capacity <= 0 || capacity > 128) { - throw ArgumentException("SHA3: incorrect capacity"); + throw const ArgumentException("SHA3: incorrect capacity"); } blockSize = 200 - capacity; @@ -54,7 +54,8 @@ class _Keccack { /// Returns this [Hash] object for method chaining. _Keccack update(List data) { if (_finished) { - throw MessageException("SHA3: can't update because hash was finished"); + throw const MessageException( + "SHA3: can't update because hash was finished"); } for (var i = 0; i < data.length; i++) { @@ -88,7 +89,7 @@ class _Keccack { void _squeeze(List dst) { if (!_finished) { - throw MessageException("SHA3: squeezing before padAndPermute"); + throw const MessageException("SHA3: squeezing before padAndPermute"); } for (var i = 0; i < dst.length; i++) { @@ -191,7 +192,7 @@ class Keccack extends _Keccack { /// Returns a [HashState] object containing the saved state information. List saveState() { if (_finished) { - throw MessageException("SHA3: cannot save finished state"); + throw const MessageException("SHA3: cannot save finished state"); } return List.from(_state.sublist(0, _pos)); } @@ -310,7 +311,7 @@ class SHA3 extends _Keccack implements SerializableHash { @override HashBytesState saveState() { if (_finished) { - throw MessageException("SHA3: cannot save finished state"); + throw const MessageException("SHA3: cannot save finished state"); } return HashBytesState(data: List.from(_state), pos: _pos); } @@ -557,7 +558,7 @@ class SHAKE extends _Keccack implements SerializableHash { @override HashBytesState saveState() { if (_finished) { - throw MessageException("SHA3: cannot save finished state"); + throw const MessageException("SHA3: cannot save finished state"); } return HashBytesState(data: List.from(_state), pos: _pos); } diff --git a/lib/crypto/crypto/hash/md4/md4.dart b/lib/crypto/crypto/hash/md4/md4.dart index ab5bb0c..572f66c 100644 --- a/lib/crypto/crypto/hash/md4/md4.dart +++ b/lib/crypto/crypto/hash/md4/md4.dart @@ -249,7 +249,8 @@ class MD4 implements SerializableHash { @override Hash update(List data) { if (_finished) { - throw MessageException("SHA512: can't update because hash was finished."); + throw const MessageException( + "SHA512: can't update because hash was finished."); } _lengthInBytes += data.length; _buffer.addAll(BytesUtils.toBytes(data)); diff --git a/lib/crypto/crypto/hash/md5/md5.dart b/lib/crypto/crypto/hash/md5/md5.dart index ad47dc4..9831855 100644 --- a/lib/crypto/crypto/hash/md5/md5.dart +++ b/lib/crypto/crypto/hash/md5/md5.dart @@ -253,7 +253,8 @@ class MD5 implements SerializableHash { @override Hash update(List data) { if (_finished) { - throw MessageException("SHA512: can't update because hash was finished."); + throw const MessageException( + "SHA512: can't update because hash was finished."); } _lengthInBytes += data.length; _buffer.addAll(BytesUtils.toBytes(data)); diff --git a/lib/crypto/crypto/hash/ridemp/ridemp.dart b/lib/crypto/crypto/hash/ridemp/ridemp.dart index 834b73d..ce4861f 100644 --- a/lib/crypto/crypto/hash/ridemp/ridemp.dart +++ b/lib/crypto/crypto/hash/ridemp/ridemp.dart @@ -300,7 +300,8 @@ class _RIPEMD implements SerializableHash { @override Hash update(List data) { if (_finished) { - throw MessageException("SHA512: can't update because hash was finished."); + throw const MessageException( + "SHA512: can't update because hash was finished."); } _lengthInBytes += data.length; _buffer.addAll(BytesUtils.toBytes(data)); diff --git a/lib/crypto/crypto/hash/sha1/sha1.dart b/lib/crypto/crypto/hash/sha1/sha1.dart index 9649603..993a3be 100644 --- a/lib/crypto/crypto/hash/sha1/sha1.dart +++ b/lib/crypto/crypto/hash/sha1/sha1.dart @@ -240,7 +240,8 @@ class SHA1 implements SerializableHash { @override Hash update(List data) { if (_finished) { - throw MessageException("SHA512: can't update because hash was finished."); + throw const MessageException( + "SHA512: can't update because hash was finished."); } _lengthInBytes += data.length; _buffer.addAll(BytesUtils.toBytes(data)); diff --git a/lib/crypto/crypto/hash/sha256/sha256.dart b/lib/crypto/crypto/hash/sha256/sha256.dart index e9b6386..03c8296 100644 --- a/lib/crypto/crypto/hash/sha256/sha256.dart +++ b/lib/crypto/crypto/hash/sha256/sha256.dart @@ -55,7 +55,8 @@ class SHA256 implements SerializableHash { @override SerializableHash update(List data, {int? length}) { if (_finished) { - throw MessageException("SHA256: can't update because hash was finished."); + throw const MessageException( + "SHA256: can't update because hash was finished."); } int dataLength = length ?? data.length; int dataPos = 0; @@ -194,7 +195,7 @@ class SHA256 implements SerializableHash { @override SHA256State saveState() { if (_finished) { - throw MessageException("SHA256: cannot save finished state"); + throw const MessageException("SHA256: cannot save finished state"); } return SHA256State( state: List.from(_state, growable: false), diff --git a/lib/crypto/crypto/hash/sha512/sha512.dart b/lib/crypto/crypto/hash/sha512/sha512.dart index dcb61bd..561bf78 100644 --- a/lib/crypto/crypto/hash/sha512/sha512.dart +++ b/lib/crypto/crypto/hash/sha512/sha512.dart @@ -101,7 +101,8 @@ class SHA512 implements SerializableHash { @override SerializableHash update(List data, {int? length}) { if (_finished) { - throw MessageException("SHA512: can't update because hash was finished."); + throw const MessageException( + "SHA512: can't update because hash was finished."); } int dataPos = 0; int dataLength = length ?? data.length; @@ -198,7 +199,7 @@ class SHA512 implements SerializableHash { @override SHA512State saveState() { if (_finished) { - throw MessageException("SHA256: cannot save finished state"); + throw const MessageException("SHA256: cannot save finished state"); } return SHA512State( stateHi: List.from(_stateHi, growable: false), diff --git a/lib/crypto/crypto/hash/xxhash64/xxhash64.dart b/lib/crypto/crypto/hash/xxhash64/xxhash64.dart index 9735fb1..5af7da9 100644 --- a/lib/crypto/crypto/hash/xxhash64/xxhash64.dart +++ b/lib/crypto/crypto/hash/xxhash64/xxhash64.dart @@ -481,7 +481,7 @@ class XXHash64 extends SerializableHash { @override HashBytesState saveState() { if (_finished) { - throw MessageException( + throw const MessageException( "XXHash64: can't update because hash was finished."); } return HashBytesState(data: _buffer, pos: _buffer.length); @@ -490,7 +490,7 @@ class XXHash64 extends SerializableHash { @override Hash update(List data) { if (_finished) { - throw MessageException( + throw const MessageException( "XXHash64: can't update because hash was finished."); } _buffer.addAll(data); diff --git a/lib/crypto/crypto/hmac/hmac.dart b/lib/crypto/crypto/hmac/hmac.dart index 8ef4d38..a8bfc5b 100644 --- a/lib/crypto/crypto/hmac/hmac.dart +++ b/lib/crypto/crypto/hmac/hmac.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/binary_operation.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; /// The `HMAC` class represents a Hash-based Message Authentication Code. diff --git a/lib/crypto/crypto/pbkdf2/pbkdf2.dart b/lib/crypto/crypto/pbkdf2/pbkdf2.dart index d692ec1..e70e588 100644 --- a/lib/crypto/crypto/pbkdf2/pbkdf2.dart +++ b/lib/crypto/crypto/pbkdf2/pbkdf2.dart @@ -1,5 +1,5 @@ import 'package:blockchain_utils/crypto/crypto/hmac/hmac.dart'; -import 'package:blockchain_utils/binary/binary_operation.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// The `PBKDF2` class is an implementation of the Password-Based Key Derivation Function 2 (PBKDF2) algorithm. /// diff --git a/lib/crypto/crypto/poly1305/poly1305.dart b/lib/crypto/crypto/poly1305/poly1305.dart index 8dd7004..ee20d2c 100644 --- a/lib/crypto/crypto/poly1305/poly1305.dart +++ b/lib/crypto/crypto/poly1305/poly1305.dart @@ -1,5 +1,5 @@ // import 'dart:typed_data'; -import 'package:blockchain_utils/binary/binary_operation.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; const _digestLength = 16; @@ -452,7 +452,7 @@ class Poly1305 { /// after the `Poly1305` instance has been finished. List digest() { if (_finished) { - throw MessageException("Poly1305 was finished"); + throw const MessageException("Poly1305 was finished"); } List mac = List.filled(16, 0); finish(mac); diff --git a/lib/crypto/crypto/prng/fortuna.dart b/lib/crypto/crypto/prng/fortuna.dart index 1ea13af..0189b1b 100644 --- a/lib/crypto/crypto/prng/fortuna.dart +++ b/lib/crypto/crypto/prng/fortuna.dart @@ -68,7 +68,7 @@ class FortunaPRNG { } if (n > 65536) { - throw MessageException('Size is too large!'); + throw const MessageException('Size is too large!'); } final tempBlock = List.filled(32, 0); diff --git a/lib/crypto/crypto/schnorrkel/keys/keys.dart b/lib/crypto/crypto/schnorrkel/keys/keys.dart index bfd7721..334f976 100644 --- a/lib/crypto/crypto/schnorrkel/keys/keys.dart +++ b/lib/crypto/crypto/schnorrkel/keys/keys.dart @@ -1,8 +1,6 @@ import 'dart:typed_data'; +import 'package:blockchain_utils/utils/utils.dart'; -import 'package:blockchain_utils/binary/binary.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/utils/ed25519_utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curves.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/ristretto_point.dart'; @@ -12,7 +10,6 @@ import 'package:blockchain_utils/crypto/crypto/cdsa/utils/ristretto_utils.dart' as ristretto_tools; import 'package:blockchain_utils/crypto/crypto/schnorrkel/merlin/transcript.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/compare/compare.dart'; import 'package:blockchain_utils/exception/exception.dart'; /// The `SchnorrkelKeyCost` class defines various constants related to the sizes and lengths of Schnorrkel keys and components. @@ -108,8 +105,8 @@ class _KeyUtils { final cloneBytes = List.from(bytes); cloneBytes[31] &= 127; bool highBitUnset = (bytes[31] >> 7 & 0) == 0; - bool isCanonical = - bytesEqual(cloneBytes, Ed25519Utils.scalarReduce(cloneBytes)); + bool isCanonical = BytesUtils.bytesEqual( + cloneBytes, Ed25519Utils.scalarReduce(cloneBytes)); if (highBitUnset && isCanonical) { return cloneBytes; } @@ -200,7 +197,7 @@ class VRFProof { final c = _KeyUtils.toCanonical(bytes.sublist(0, 32)); final s = _KeyUtils.toCanonical(bytes.sublist(32)); if (c == null || s == null) { - throw ArgumentException("invalid VRF proof bytes"); + throw const ArgumentException("invalid VRF proof bytes"); } return VRFProof._(c, s); } @@ -357,7 +354,7 @@ class SchnorrkelSecretKey { BytesUtils.toBytes(canonicalKey, unmodifiable: true), BytesUtils.toBytes(nonce, unmodifiable: true)); } - throw ArgumentException("invalid key"); + throw const ArgumentException("invalid key"); } /// Creates a `SchnorrkelSecretKey` instance from a byte representation of a secret key. @@ -533,7 +530,7 @@ class SchnorrkelSecretKey { final derivePub = publicKey()._deriveScalarAndChainCode(chainCode, message); final nonce = nonceGenerator?.call(32) ?? QuickCrypto.generateRandom(32); if (nonce.length != 32) { - throw ArgumentException("invalid random bytes length"); + throw const ArgumentException("invalid random bytes length"); } final newKey = ristretto_tools.add(key(), derivePub.item1); final combine = List.from([...newKey, ...nonce]); @@ -571,7 +568,7 @@ class SchnorrkelSecretKey { final nonceRand = nonceGenerator?.call(64) ?? QuickCrypto.generateRandom(64); if (nonceRand.length != 64) { - throw ArgumentException("invalid random bytes length"); + throw const ArgumentException("invalid random bytes length"); } final nonceBytes = Ed25519Utils.scalarReduce(nonceRand); final nonceBigint = @@ -658,7 +655,7 @@ class SchnorrkelSecretKey { } final nonce = nonceGenerator?.call(64) ?? QuickCrypto.generateRandom(64); if (nonce.length != 64) { - throw ArgumentException("invalid random bytes length"); + throw const ArgumentException("invalid random bytes length"); } final n = Ed25519Utils.scalarReduce(nonce); final scalar = BigintUtils.fromBytes(n, byteOrder: Endian.little); @@ -841,7 +838,7 @@ class SchnorrkelPublicKey { final kBigint = signingContextScript.toBigint("sign:c".codeUnits, 64); final r = ((-toPoint()) * kBigint) + (Curves.generatorED25519 * signature.sBigint); - return bytesEqual(r.toBytes(), signature.r); + return BytesUtils.bytesEqual(r.toBytes(), signature.r); } /// Verifies a Verifiable Random Function (VRF) output and its proof. @@ -917,7 +914,7 @@ class SchnorrkelPublicKey { } script.additionalData("vrf:h^sk".codeUnits, out.output); final c = script.toBytesWithReduceScalar("prove".codeUnits, 64); - return bytesEqual(c, proof.c); + return BytesUtils.bytesEqual(c, proof.c); } /// Computes a VRF (Verifiable Random Function) hash using a transcript. @@ -1034,7 +1031,7 @@ class SchnorrkelSignature { final r = signatureBytes.sublist(0, 32); final s = signatureBytes.sublist(32, SchnorrkelKeyCost.signatureLength); if (s[31] & 128 == 0) { - throw ArgumentException( + throw const ArgumentException( "Signature not marked as schnorrkel, maybe try ed25519 instead."); } final canonicalS = _KeyUtils.toCanonical(s); @@ -1043,7 +1040,7 @@ class SchnorrkelSignature { BytesUtils.toBytes(canonicalS, unmodifiable: true), BytesUtils.toBytes(r, unmodifiable: true)); } - throw ArgumentException("invalid schnorrkel signature"); + throw const ArgumentException("invalid schnorrkel signature"); } /// private constructor diff --git a/lib/crypto/crypto/schnorrkel/merlin/transcript.dart b/lib/crypto/crypto/schnorrkel/merlin/transcript.dart index 5d67434..d8611ff 100644 --- a/lib/crypto/crypto/schnorrkel/merlin/transcript.dart +++ b/lib/crypto/crypto/schnorrkel/merlin/transcript.dart @@ -1,10 +1,7 @@ import 'dart:typed_data'; - -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/utils/ed25519_utils.dart'; import 'package:blockchain_utils/crypto/crypto/schnorrkel/strobe/strobe.dart'; -import 'package:blockchain_utils/binary/binary_operation.dart'; /// A transcript object for the Merlin cryptographic protocol. /// diff --git a/lib/crypto/crypto/schnorrkel/strobe/strobe.dart b/lib/crypto/crypto/schnorrkel/strobe/strobe.dart index c05b184..f92fcfc 100644 --- a/lib/crypto/crypto/schnorrkel/strobe/strobe.dart +++ b/lib/crypto/crypto/schnorrkel/strobe/strobe.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/binary_operation.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:blockchain_utils/exception/exception.dart'; @@ -178,7 +178,7 @@ class Strobe { void _run() { if (_initialized) { if (_buffer.length > strober) { - throw MessageException( + throw const MessageException( "strobe: buffer is never supposed to reach strobeR"); } _buffer.add(_posBegin); @@ -283,19 +283,20 @@ class Strobe { (StrobeFlags.I | StrobeFlags.T)) && ((flags & (StrobeFlags.I | StrobeFlags.A)) != StrobeFlags.A)) { if (length == 0) { - throw MessageException("A length should be set for this operation."); + throw const MessageException( + "A length should be set for this operation."); } data = List.filled(length, 0); } else { if (length != 0) { - throw MessageException( + throw const MessageException( "Output length must be zero except for PRF, send_MAC, and RATCHET operations."); } data = List.from(dataConst); } if (more) { if (flags != _curFlags) { - throw MessageException( + throw const MessageException( "Flag should be the same when streaming operations."); } } else { @@ -318,7 +319,7 @@ class Strobe { } else if ((flags & (StrobeFlags.I | StrobeFlags.A | StrobeFlags.T)) == (StrobeFlags.I | StrobeFlags.T)) { if (more) { - throw MessageException( + throw const MessageException( "Not supposed to check a MAC with the 'more' streaming option"); } int failures = 0; diff --git a/lib/crypto/crypto/scrypt/scrypt.dart b/lib/crypto/crypto/scrypt/scrypt.dart index 1adc546..811c44c 100644 --- a/lib/crypto/crypto/scrypt/scrypt.dart +++ b/lib/crypto/crypto/scrypt/scrypt.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:blockchain_utils/crypto/crypto/hmac/hmac.dart'; import 'package:blockchain_utils/crypto/crypto/pbkdf2/pbkdf2.dart'; -import 'package:blockchain_utils/binary/binary_operation.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; /// A class for performing scrypt key derivation. @@ -35,19 +35,19 @@ class Scrypt { /// Throws an [ArgumentException] if the parameters are out of the valid range or not a power of 2. Scrypt(this.n, this.r, this.p) { if (p <= 0) { - throw ArgumentException("scrypt: incorrect p"); + throw const ArgumentException("scrypt: incorrect p"); } if (r <= 0) { - throw ArgumentException("scrypt: incorrect r"); + throw const ArgumentException("scrypt: incorrect r"); } if (n < 1 || n > 1 << 31) { - throw ArgumentException('scrypt: N must be between 2 and 2^31'); + throw const ArgumentException('scrypt: N must be between 2 and 2^31'); } if (!_isPowerOfTwo(n)) { - throw ArgumentException("scrypt: N must be a power of 2"); + throw const ArgumentException("scrypt: N must be a power of 2"); } const maxInt = (1 << 31) & mask32; @@ -56,7 +56,7 @@ class Scrypt { r > maxInt ~/ 128 ~/ p || r > maxInt ~/ 256 || n > maxInt ~/ 128 ~/ r) { - throw ArgumentException("scrypt: parameters are too large"); + throw const ArgumentException("scrypt: parameters are too large"); } _v = List.filled(32 * (n + 2) * r, 0); diff --git a/lib/crypto/crypto/x_modem_crc/x_modem_crc.dart b/lib/crypto/crypto/x_modem_crc/x_modem_crc.dart index 5f6d9d4..7956a6a 100644 --- a/lib/crypto/crypto/x_modem_crc/x_modem_crc.dart +++ b/lib/crypto/crypto/x_modem_crc/x_modem_crc.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/binary_operation.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// A class for calculating and verifying XModem CRC (Cyclic Redundancy Check). /// diff --git a/lib/crypto/quick_crypto.dart b/lib/crypto/quick_crypto.dart index 8d2cf31..a0a7aa6 100644 --- a/lib/crypto/quick_crypto.dart +++ b/lib/crypto/quick_crypto.dart @@ -1,12 +1,7 @@ import 'package:blockchain_utils/crypto/crypto/aes/padding.dart'; -import 'package:blockchain_utils/crypto/crypto/chacha20poly1305/chacha20poly1305.dart'; -import 'package:blockchain_utils/crypto/crypto/ecb/ecb.dart'; -import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; -import 'package:blockchain_utils/crypto/crypto/hmac/hmac.dart'; -import 'package:blockchain_utils/crypto/crypto/pbkdf2/pbkdf2.dart'; -import 'package:blockchain_utils/crypto/crypto/prng/fortuna.dart'; +import 'package:blockchain_utils/crypto/crypto/crypto.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// QuickCrypto provides a set of utility methods for cryptographic operations. /// @@ -190,7 +185,7 @@ class QuickCrypto { /// returns A tuple containing the first and second halves of the SHA512 hash. static Tuple, List> sha512HashHalves(List data) { final hash = SHA512.hash(data); - final halvesLength = sha512DeigestLength ~/ 2; + const halvesLength = sha512DeigestLength ~/ 2; return Tuple(hash.sublist(0, halvesLength), hash.sublist(halvesLength)); } @@ -264,7 +259,7 @@ class QuickCrypto { if (decrypt != null) { return decrypt; } - throw MessageException("ChaCha20-Poly1305 decryption fail"); + throw const MessageException("ChaCha20-Poly1305 decryption fail"); } /// Encrypt data using the ChaCha20-Poly1305 authenticated encryption algorithm. @@ -305,4 +300,15 @@ class QuickCrypto { /// Return the generated random bytes. return r; } + + static List processCtr( + {required List key, + required List iv, + required List data}) { + final CTR ctr = CTR(AES(key), iv); + final xor = List.filled(data.length, 0); + ctr.streamXOR(data, xor); + ctr.clean(); + return xor; + } } diff --git a/lib/exception/exception.dart b/lib/exception/exception.dart index 2809c30..572085d 100644 --- a/lib/exception/exception.dart +++ b/lib/exception/exception.dart @@ -4,6 +4,10 @@ abstract class BlockchainUtilsException implements Exception { /// Abstract field to hold the exception message. abstract final String message; + abstract final Map? details; + + const BlockchainUtilsException(); + /// Override the 'toString' method to provide a custom string representation of the exception. @override String toString() { @@ -15,7 +19,10 @@ abstract class BlockchainUtilsException implements Exception { /// This exception is used to represent errors related to invalid arguments in blockchain utility operations. class ArgumentException implements BlockchainUtilsException { /// Constructor to initialize the exception with a specific message. - const ArgumentException(this.message); + const ArgumentException(this.message, {this.details}); + + @override + final Map? details; /// Final field to store the exception message. @override @@ -44,5 +51,6 @@ class MessageException implements BlockchainUtilsException { return "$message${details == null ? '' : " $details"}"; } + @override final Map? details; } diff --git a/lib/exception/rpc_error.dart b/lib/exception/rpc_error.dart index 08f4dee..f16d09e 100644 --- a/lib/exception/rpc_error.dart +++ b/lib/exception/rpc_error.dart @@ -12,7 +12,8 @@ class RPCError implements BlockchainUtilsException { {required this.message, required this.errorCode, required this.data, - required this.request}); + required this.request, + this.details}); /// The error code associated with the RPC error. final int errorCode; @@ -27,6 +28,9 @@ class RPCError implements BlockchainUtilsException { /// Details of the RPC request that resulted in the error. final Map request; + @override + final Map? details; + /// Returns a string representation of the RPCError. /// /// The string includes the error code, error message, and the request details if available. diff --git a/lib/hex/hex.dart b/lib/hex/hex.dart index 9371592..db948d6 100644 --- a/lib/hex/hex.dart +++ b/lib/hex/hex.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/binary.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; // ignore: library_private_types_in_public_api diff --git a/lib/layout/byte/byte_handler.dart b/lib/layout/byte/byte_handler.dart index e9a8db9..39fd84c 100644 --- a/lib/layout/byte/byte_handler.dart +++ b/lib/layout/byte/byte_handler.dart @@ -1,7 +1,5 @@ -import 'package:blockchain_utils/binary/binary_operation.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/layout/exception/exception.dart'; import 'package:blockchain_utils/layout/utils/utils.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; - part 'reader.dart'; part 'writer.dart'; diff --git a/lib/layout/constant/constant.dart b/lib/layout/constant/constant.dart index 2d7b658..239a05c 100644 --- a/lib/layout/constant/constant.dart +++ b/lib/layout/constant/constant.dart @@ -1,7 +1,7 @@ import 'dart:typed_data'; import 'package:blockchain_utils/layout/core/core.dart'; import 'package:blockchain_utils/layout/exception/exception.dart'; -import 'package:blockchain_utils/string/string.dart'; +import 'package:blockchain_utils/utils/utils.dart'; class LayoutConst { /// [GreedyCount]. diff --git a/lib/layout/core/types/none.dart b/lib/layout/core/types/none.dart index d8064a0..40e2163 100644 --- a/lib/layout/core/types/none.dart +++ b/lib/layout/core/types/none.dart @@ -15,7 +15,7 @@ class NoneLayout extends Layout { @override decode(LayoutByteReader bytes, {int offset = 0}) { - return LayoutDecodeResult(consumed: 0, value: null); + return const LayoutDecodeResult(consumed: 0, value: null); } @override diff --git a/lib/layout/core/types/numeric.dart b/lib/layout/core/types/numeric.dart index 60ce344..137d4e8 100644 --- a/lib/layout/core/types/numeric.dart +++ b/lib/layout/core/types/numeric.dart @@ -6,7 +6,7 @@ import 'package:blockchain_utils/layout/core/core/core.dart'; import 'package:blockchain_utils/layout/core/types/padding_layout.dart'; import 'package:blockchain_utils/layout/exception/exception.dart'; import 'package:blockchain_utils/layout/utils/utils.dart'; -import 'package:blockchain_utils/numbers/numbers.dart'; +import 'package:blockchain_utils/utils/numbers/numbers.dart'; /// Represents an external layout. abstract class ExternalLayout extends Layout { diff --git a/lib/layout/core/types/string.dart b/lib/layout/core/types/string.dart index 060bdf1..d8e199f 100644 --- a/lib/layout/core/types/string.dart +++ b/lib/layout/core/types/string.dart @@ -1,7 +1,7 @@ // import 'package:blockchain_utils/layout/byte/byte_handler.dart'; // import 'package:blockchain_utils/layout/core/core/core.dart'; // import 'package:blockchain_utils/layout/exception/exception.dart'; -// import 'package:blockchain_utils/string/string.dart'; +// import 'package:blockchain_utils/utils/utils.dart'; // /// A class representing a C-style string layout within a buffer. // class CStringLayout extends Layout { diff --git a/lib/layout/exception/exception.dart b/lib/layout/exception/exception.dart index 06870af..a0c68b4 100644 --- a/lib/layout/exception/exception.dart +++ b/lib/layout/exception/exception.dart @@ -9,6 +9,7 @@ class LayoutException implements BlockchainUtilsException { @override final String message; final StackTrace? trace; + @override final Map? details; @override diff --git a/lib/layout/utils/utils.dart b/lib/layout/utils/utils.dart index ebe3e83..217bdcb 100644 --- a/lib/layout/utils/utils.dart +++ b/lib/layout/utils/utils.dart @@ -1,17 +1,19 @@ import 'dart:typed_data' show Endian; -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/bip/substrate/scale/substrate_scale_enc_cuint.dart'; +import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/utils/utils.dart'; class LayoutSerializationUtils { static List encodeLength(List bytes) { - return SubstrateScaleCUintEncoder().encode(bytes.length.toString()); + return const SubstrateScaleCUintEncoder().encode(bytes.length.toString()); } static List compactToBytes(BigInt value) { - return SubstrateScaleCUintEncoder().encode(value.toString()); + return const SubstrateScaleCUintEncoder().encode(value.toString()); } static List compactIntToBytes(int value) { - return SubstrateScaleCUintEncoder().encode(value.toString()); + return const SubstrateScaleCUintEncoder().encode(value.toString()); } static Tuple decodeLength(List bytes, {bool sign = false}) { @@ -51,7 +53,7 @@ class LayoutSerializationUtils { static Tuple decodeLengthWithDetails(List bytes) { final decode = decodeLength(bytes, sign: false); if (!decode.item2.isValidInt) { - throw MessageException("Invalid variable length. length to large."); + throw const MessageException("Invalid variable length. length to large."); } final bytesLength = decode.item2.toInt(); final dataOffset = decode.item1; diff --git a/lib/numbers/numbers.dart b/lib/numbers/numbers.dart deleted file mode 100644 index bbe3fc4..0000000 --- a/lib/numbers/numbers.dart +++ /dev/null @@ -1,7 +0,0 @@ -export 'int_utils.dart'; - -/// bigint utils -export 'bigint_utils.dart'; - -/// BigintUtils -export 'big_rational.dart'; diff --git a/lib/secret_wallet/exception.dart b/lib/secret_wallet/exception.dart new file mode 100644 index 0000000..e3a11a3 --- /dev/null +++ b/lib/secret_wallet/exception.dart @@ -0,0 +1,13 @@ +import 'package:blockchain_utils/blockchain_utils.dart'; + +class Web3SecretStorageDefinationV3Exception extends BlockchainUtilsException { + /// The error message associated with this exception. + @override + final String message; + + @override + final Map? details; + + /// Creates a new instance of [Web3SecretStorageDefinationV3Exception] with an optional [message]. + const Web3SecretStorageDefinationV3Exception(this.message, {this.details}); +} diff --git a/lib/secret_wallet/secret_wallet.dart b/lib/secret_wallet/secret_wallet.dart deleted file mode 100644 index 53dbcf9..0000000 --- a/lib/secret_wallet/secret_wallet.dart +++ /dev/null @@ -1,419 +0,0 @@ -import 'package:blockchain_utils/blockchain_utils.dart'; - -class _SecretStorageConst { - static const List scryptTag = [180]; - static const List pbdkdf2Tag = [181]; - static const List tag = [200]; - static const int version = 3; -} - -/// Enum representing different encoding formats for secret wallets. -enum SecretWalletEncoding { - base64, // Base64 encoding - json, // JSON encoding - cbor, // cbor encoding -} - -/// Abstract class representing a key derivation strategy. -abstract class _Derivator { - List deriveKey(List password); - - String get name; // The name of the key derivation strategy. - Map encode(); - CborTagValue cborEncode(); - - static _Derivator fromCbor(CborObject cbor) { - if (cbor is! CborTagValue || cbor.value is! CborListValue) { - throw ArgumentException("invalid secret wallet cbor bytes"); - } - if (bytesEqual(cbor.tags, _SecretStorageConst.pbdkdf2Tag)) { - final toObj = _PBDKDF2Derivator.fromCbor(cbor.value); - return toObj; - } else if (bytesEqual(cbor.tags, _SecretStorageConst.scryptTag)) { - return _Scrypt.fromCbor(cbor.value); - } else { - throw ArgumentException("invalid secret wallet cbor bytes"); - } - } -} - -/// A class implementing key derivation using the PBKDF2 algorithm. -class _PBDKDF2Derivator extends _Derivator { - _PBDKDF2Derivator(this.iterations, this.salt, this.dklen); - final int iterations; - final List salt; - final int dklen; - - factory _PBDKDF2Derivator.fromCbor(CborListValue v) { - final int c = v.value[0].value; - final int dklen = v.value[1].value; - final String prf = v.value[2].value; - if (prf != 'hmac-sha256') { - throw ArgumentException('Invalid prf only support hmac-sha256'); - } - final List salt = v.value[3].value; - return _PBDKDF2Derivator(c, salt, dklen); - } - - @override - List deriveKey(List password) { - return PBKDF2.deriveKey( - mac: () => HMAC(() => SHA256(), password), - salt: salt, - iterations: iterations, - length: dklen); - } - - @override - Map encode() { - return { - 'c': iterations, - 'dklen': dklen, - 'prf': 'hmac-sha256', - 'salt': BytesUtils.toHexString(salt) - }; - } - - @override - final String name = 'pbkdf2'; - - @override - CborTagValue cborEncode() { - return CborTagValue( - CborListValue.fixedLength([ - CborIntValue(iterations), - CborIntValue(dklen), - CborStringValue("hmac-sha256"), - CborBytesValue(salt) - ]), - _SecretStorageConst.pbdkdf2Tag); - } -} - -/// A class implementing key derivation using the Scrypt algorithm. -class _Scrypt extends _Derivator { - _Scrypt(this.dklen, this.n, this.r, this.p, this.salt); - factory _Scrypt.fromCbor(CborListValue v) { - final int dklen = v.value[0].value; - final int n = v.value[1].value; - final int r = v.value[2].value; - final int p = v.value[3].value; - final List salt = v.value[4].value; - return _Scrypt(dklen, n, r, p, salt); - } - final int dklen; - final int n; - final int r; - final int p; - final List salt; - - @override - List deriveKey(List password) { - return Scrypt.deriveKey(password, salt, dkLen: dklen, n: n, r: r, p: p); - } - - @override - Map encode() { - return { - 'dklen': dklen, - 'n': n, - 'r': r, - 'p': p, - 'salt': BytesUtils.toHexString(salt), - }; - } - - @override - final String name = 'scrypt'; - - @override - CborTagValue cborEncode() { - return CborTagValue( - CborListValue.fixedLength([ - CborIntValue(dklen), - CborIntValue(n), - CborIntValue(r), - CborIntValue(p), - CborBytesValue(salt) - ]), - _SecretStorageConst.scryptTag); - } // Name of the Scrypt strategy. -} - -/// The `SecretWallet` class represents a secret wallet that stores sensitive credentials -/// using a specified key derivation strategy. -class SecretWallet { - SecretWallet._( - List data, - this._derivator, - this._password, - this._iv, - this._id, - ) : data = List.unmodifiable(data); - - /// Factory method to create a `SecretWallet` with encoded credentials. - /// - /// - `credentials`: The encoded credentials to be stored in the wallet. - /// - `password`: The password used to derive the encryption key. - /// - `scryptN`: Parameter 'n' for the Scrypt key derivation function (default is 8192). - /// - `p`: Parameter 'p' for the Scrypt key derivation function (default is 1). - /// - /// Returns a `SecretWallet` instance with the encoded credentials. - factory SecretWallet.encode( - List data, - String password, { - int scryptN = 8192, - int p = 1, - }) { - final passwordBytes = StringUtils.encode(password); - - final salt = QuickCrypto.generateRandom(32); - - final derivator = _Scrypt(32, scryptN, 8, p, salt); - - final uuid = UUID.toBuffer(UUID.generateUUIDv4()); - - final iv = QuickCrypto.generateRandom(128 ~/ 8); - - return SecretWallet._(data, derivator, passwordBytes, iv, uuid); - } - - static Map _toJsonEcoded(String encoded, - {SecretWalletEncoding encoding = SecretWalletEncoding.json}) { - try { - if (encoding == SecretWalletEncoding.json) { - return StringUtils.toJson(encoded); - } - return StringUtils.toJson(StringUtils.decode( - StringUtils.encode(encoded, StringEncoding.base64))); - } catch (e) { - throw ArgumentException("invalid encoding"); - } - } - - /// Factory method to decode and create a `SecretWallet` from an encoded string and a password. - /// - /// - `encoded`: The encoded string containing wallet data. - /// - `password`: The password used to derive the encryption key. - /// - /// Returns a `SecretWallet` instance decoded from the input data, or throws an error - /// if decoding or password validation fails. - factory SecretWallet.decode(String encoded, String password, - {SecretWalletEncoding encoding = SecretWalletEncoding.json}) { - if (encoding == SecretWalletEncoding.cbor) { - return _decodeCbor(encoded, password); - } - final data = _toJsonEcoded(encoded, encoding: encoding); - - final version = data['version']; - if (version != 3) { - throw ArgumentException("Library only supports version 3"); - } - - final params = data['crypto'] ?? data['Crypto']; - - final String kdf = params['kdf']; - _Derivator derivator; - - switch (kdf) { - case 'pbkdf2': - final derParams = params['kdfparams'] as Map; - - if (derParams['prf'] != 'hmac-sha256') { - throw ArgumentException('Invalid prf only support hmac-sha256'); - } - - derivator = _PBDKDF2Derivator( - derParams['c'] as int, - BytesUtils.fromHexString(derParams['salt']), - derParams['dklen'] as int, - ); - - break; - case 'scrypt': - final derParams = params['kdfparams'] as Map; - derivator = _Scrypt( - derParams['dklen'] as int, - derParams['n'] as int, - derParams['r'] as int, - derParams['p'] as int, - BytesUtils.fromHexString(derParams['salt']), - ); - break; - default: - throw ArgumentException( - '$kdf which is not supported.', - ); - } - - final encodedPassword = List.from(StringUtils.encode(password)); - final derivedKey = derivator.deriveKey(encodedPassword); - final aesKey = List.from(derivedKey.sublist(0, 16)); - final List macBytes = derivedKey.sublist(16, 32); - final encryptedPrivateKey = BytesUtils.fromHexString(params['ciphertext']); - final derivedMac = _mac(macBytes, encryptedPrivateKey); - if (derivedMac != params['mac']) { - throw ArgumentException('wrong password or the file is corrupted'); - } - - if (params['cipher'] != 'aes-128-ctr') { - throw ArgumentException("only cipher aes-128-ctr is supported."); - } - final iv = BytesUtils.fromHexString(params['cipherparams']['iv']); - final encryptText = List.from(encryptedPrivateKey); - final CTR ctr = CTR(AES(aesKey), iv); - final List privateKey = List.filled(encryptText.length, 0); - ctr.streamXOR(encryptText, privateKey); - ctr.clean(); - final id = UUID.toBuffer(data['id'] as String); - return SecretWallet._(privateKey, derivator, encodedPassword, iv, id); - } - - static SecretWallet _decodeCbor(String encoded, String password) { - try { - final cborTag = CborObject.fromCborHex(encoded); - if (cborTag is! CborTagValue || - cborTag.value is! CborListValue || - cborTag.value.value.length != 3) { - throw ArgumentException("Invalid secret wallet cbor bytes"); - } - if (!bytesEqual(cborTag.tags, _SecretStorageConst.tag)) { - throw ArgumentException("invalid secret wallet cbor tag"); - } - final cbor = cborTag.value as CborListValue; - final int version = cbor.value[2].value; - if (version != _SecretStorageConst.version) { - throw ArgumentException( - "Library only supports version ${_SecretStorageConst.version}"); - } - - final List uuid = cbor.value[1].value; - final params = cbor.value[0] as CborListValue; - final String cipher = params.value[0].value; - if (cipher != 'aes-128-ctr') { - throw ArgumentException("only cipher aes-128-ctr is supported."); - } - final List iv = params.value[1].value; - final derivator = _Derivator.fromCbor(params.value[3]); - final List ciphertext = params.value[2].value; - final String mac = params.value[4].value; - final encodedPassword = List.from(StringUtils.encode(password)); - final derivedKey = derivator.deriveKey(encodedPassword); - final List macBytes = - List.unmodifiable(derivedKey.sublist(16, 32)); - final aesKey = List.from(derivedKey.sublist(0, 16)); - final derivedMac = _mac(macBytes, ciphertext); - if (derivedMac != mac) { - throw ArgumentException('wrong password or the file is corrupted'); - } - final CTR ctr = CTR(AES(aesKey), iv); - final List privateKey = List.filled(ciphertext.length, 0); - ctr.streamXOR(ciphertext, privateKey); - ctr.clean(); - return SecretWallet._(privateKey, derivator, encodedPassword, iv, uuid); - } on ArgumentException { - rethrow; - } catch (e) { - throw ArgumentException('invalid secret wallet cbor bytes'); - } - } - - final List data; - - final _Derivator _derivator; - - final List _password; - final List _iv; - - final List _id; - - String get uuid => UUID.fromBuffer(_id); - - /// Encrypts the sensitive wallet data using the specified encoding format and returns - /// the encrypted representation. - /// - /// - `encoding`: The encoding format to use for the encrypted output (default is JSON). - /// - /// Returns the encrypted wallet data as a string in the chosen encoding format. - String encrypt({SecretWalletEncoding encoding = SecretWalletEncoding.json}) { - // Encrypt the wallet data and obtain the ciphertext bytes. - final ciphertextBytes = _encryptPassword(); - // print("cipher ${BytesUtils.toHexString(ciphertextBytes)}"); - if (encoding == SecretWalletEncoding.cbor) { - return _toCbor(ciphertextBytes); - } - - // Prepare the JSON representation of the encrypted data. - final Map toJson = { - 'crypto': { - 'cipher': 'aes-128-ctr', - 'cipherparams': {'iv': BytesUtils.toHexString(_iv)}, - 'ciphertext': BytesUtils.toHexString(ciphertextBytes.item1), - 'kdf': _derivator.name, - 'kdfparams': _derivator.encode(), - 'mac': _mac(ciphertextBytes.item2, ciphertextBytes.item1), - }, - 'id': uuid, - 'version': 3, - }; - - // Convert the JSON to a string. - final toString = StringUtils.fromJson(toJson); - - // Based on the specified encoding format, return the encrypted data as a string. - if (encoding == SecretWalletEncoding.json) { - return toString; - } - return StringUtils.decode( - StringUtils.encode(toString), StringEncoding.base64); - } - - String _toCbor(Tuple, List> ciphertextBytes) { - return CborTagValue( - CborListValue.dynamicLength([ - CborListValue.fixedLength([ - CborStringValue('aes-128-ctr'), - CborBytesValue(_iv), - CborBytesValue(ciphertextBytes.item1), - _derivator.cborEncode(), - CborStringValue( - _mac(ciphertextBytes.item2, ciphertextBytes.item1)), - ]), - CborBytesValue(_id), - CborIntValue(3), - ]), - _SecretStorageConst.tag) - .toCborHex(); - } - - /// Generates a Message Authentication Code (MAC) for the provided derived key and ciphertext. - /// - /// - `dk`: The derived key. - /// - `ciphertext`: The encrypted ciphertext. - /// - /// Returns the MAC as a hexadecimal string. - static String _mac(List dk, List ciphertext) { - // Concatenate the derived key and ciphertext to form the input for the MAC calculation. - final mac = [...dk, ...ciphertext]; - - // Hash the concatenated data using Keccak. - return BytesUtils.toHexString(Keccack.hash(List.from(mac))); - } - - /// Encrypts the wallet's sensitive credentials using AES-128-CTR encryption. - /// - /// Returns the encrypted ciphertext as a list of bytes. - Tuple, List> _encryptPassword() { - // Derive the encryption key from the password. - final derived = List.unmodifiable(_derivator.deriveKey(_password)); - final macBytes = List.unmodifiable(derived.sublist(16, 32)); - final aesKey = List.from(derived.sublist(0, 16)); - // final plainText = List.from(StringUtils.toBytes()); - final CTR ctr = CTR(AES(aesKey), _iv); - final encryptOut = List.filled(data.length, 0); - ctr.streamXOR(data, encryptOut); - ctr.clean(); - - return Tuple(encryptOut, macBytes); - } -} diff --git a/lib/secret_wallet/web3_storage_defination.dart b/lib/secret_wallet/web3_storage_defination.dart new file mode 100644 index 0000000..4f097d6 --- /dev/null +++ b/lib/secret_wallet/web3_storage_defination.dart @@ -0,0 +1,479 @@ +import 'package:blockchain_utils/cbor/cbor.dart'; +import 'package:blockchain_utils/crypto/crypto/crypto.dart'; +import 'package:blockchain_utils/crypto/quick_crypto.dart'; +import 'package:blockchain_utils/utils/utils.dart'; +import 'package:blockchain_utils/uuid/uuid.dart'; + +import 'exception.dart'; + +class _SecretStorageConst { + static const List scryptTag = [180]; + static const List pbdkdf2Tag = [181]; + static const List tag = [200]; + static const int version = 3; + static const int ivLength = 128 ~/ 8; + static const saltLength = 32; +} + +enum KDFMode { scrypt, pbkdf2 } + +/// Enum representing different encoding formats for secret wallets. +enum SecretWalletEncoding { + base64, // Base64 encoding + json, // JSON encoding + cbor, // cbor encoding +} + +/// Abstract class representing a key derivation strategy. +abstract class KDFParam { + const KDFParam(); + List deriveKey(List password); + Map encode(); + CborTagValue cborEncode(); + KDFMode get type; + + factory KDFParam.fromCbor(CborObject cbor) { + if (cbor is! CborTagValue || cbor.value is! CborListValue) { + throw const Web3SecretStorageDefinationV3Exception( + "invalid secret wallet cbor bytes"); + } + if (BytesUtils.bytesEqual(cbor.tags, _SecretStorageConst.pbdkdf2Tag)) { + final toObj = KDF2.fromCbor(cbor.value); + return toObj; + } else if (BytesUtils.bytesEqual( + cbor.tags, _SecretStorageConst.scryptTag)) { + return KDFScrypt.fromCbor(cbor.value); + } else { + throw const Web3SecretStorageDefinationV3Exception( + "invalid secret wallet cbor bytes"); + } + } + + factory KDFParam.fromJson(Map json) { + final kdf = json["kdf"]; + final params = json["kdfparams"]; + switch (kdf) { + case "scrypt": + return KDFScrypt.fromJson(params); + case "pbkdf2": + return KDF2.fromJson(params); + default: + throw Web3SecretStorageDefinationV3Exception("Invalid kdf.", details: { + "excepted": ["scrypt", "pbkdf2"].join(", "), + "kdf": kdf + }); + } + } +} + +/// A class implementing key derivation using the PBKDF2 algorithm. +class KDF2 extends KDFParam { + KDF2._(this.iterations, List salt, this.dklen) + : salt = BytesUtils.toBytes(salt, unmodifiable: true); + factory KDF2( + {required int iterations, required List salt, required int dklen}) { + if (salt.length != _SecretStorageConst.saltLength) { + throw Web3SecretStorageDefinationV3Exception("Invalid salt length.", + details: { + "excepted": _SecretStorageConst.saltLength, + "length": salt.length + }); + } + return KDF2._(iterations, salt, dklen); + } + factory KDF2.fromJson(Map json) { + if (json["prf"] != "hmac-sha256") { + throw Web3SecretStorageDefinationV3Exception("Invalid prf.", + details: {"excepted": "hmac-sha256", "prf": json["prf"]}); + } + return KDF2( + iterations: json["c"], + salt: BytesUtils.fromHexString(json["salt"]), + dklen: json["dklen"], + ); + } + + final int iterations; + final List salt; + final int dklen; + + factory KDF2.fromCbor(CborListValue v) { + final int c = v.value[0].value; + final int dklen = v.value[1].value; + final String prf = v.value[2].value; + if (prf != "hmac-sha256") { + throw Web3SecretStorageDefinationV3Exception("Invalid prf.", + details: {"excepted": "hmac-sha256", "prf": prf}); + } + final List salt = v.value[3].value; + return KDF2(iterations: c, salt: salt, dklen: dklen); + } + + @override + List deriveKey(List password) { + return PBKDF2.deriveKey( + mac: () => HMAC(() => SHA256(), password), + salt: salt, + iterations: iterations, + length: dklen); + } + + @override + Map encode() { + return { + 'c': iterations, + 'dklen': dklen, + 'prf': 'hmac-sha256', + 'salt': BytesUtils.toHexString(salt) + }; + } + + @override + CborTagValue cborEncode() { + return CborTagValue( + CborListValue.fixedLength([ + CborIntValue(iterations), + CborIntValue(dklen), + CborStringValue("hmac-sha256"), + CborBytesValue(salt) + ]), + _SecretStorageConst.pbdkdf2Tag); + } + + @override + KDFMode get type => KDFMode.pbkdf2; +} + +/// A class implementing key derivation using the Scrypt algorithm. +class KDFScrypt extends KDFParam { + KDFScrypt._(this.dklen, this.n, this.r, this.p, List salt) + : salt = BytesUtils.toBytes(salt, unmodifiable: true); + factory KDFScrypt( + {required int dklen, + required int n, + required int r, + required int p, + required List salt}) { + if (salt.length != _SecretStorageConst.saltLength) { + throw Web3SecretStorageDefinationV3Exception("Invalid salt length.", + details: { + "excepted": _SecretStorageConst.saltLength, + "length": salt.length + }); + } + return KDFScrypt._(dklen, n, r, p, salt); + } + + factory KDFScrypt.fromJson(Map json) { + return KDFScrypt( + dklen: json["dklen"], + n: json["n"], + r: json["r"], + p: json["p"], + salt: BytesUtils.fromHexString(json["salt"]), + ); + } + + factory KDFScrypt.fromCbor(CborListValue v) { + final int dklen = v.value[0].value; + final int n = v.value[1].value; + final int r = v.value[2].value; + final int p = v.value[3].value; + final List salt = v.value[4].value; + return KDFScrypt(dklen: dklen, n: n, r: r, p: p, salt: salt); + } + final int dklen; + final int n; + final int r; + final int p; + final List salt; + + @override + List deriveKey(List password) { + return Scrypt.deriveKey(password, salt, dkLen: dklen, n: n, r: r, p: p); + } + + @override + Map encode() { + return { + "dklen": dklen, + "n": n, + "r": r, + "p": p, + "salt": BytesUtils.toHexString(salt), + }; + } + + @override + CborTagValue cborEncode() { + return CborTagValue( + CborListValue.fixedLength([ + CborIntValue(dklen), + CborIntValue(n), + CborIntValue(r), + CborIntValue(p), + CborBytesValue(salt) + ]), + _SecretStorageConst.scryptTag); + } + + @override + KDFMode get type => KDFMode.scrypt; // Name of the Scrypt strategy. +} + +class CryptoParam { + const CryptoParam._({required this.kdf, required this.iv}); + factory CryptoParam({required KDFParam kdf, required List iv}) { + if (iv.length != _SecretStorageConst.ivLength) { + throw Web3SecretStorageDefinationV3Exception("Invalid iv length.", + details: { + "excepted": _SecretStorageConst.ivLength, + "length": iv.length + }); + } + return CryptoParam._(kdf: kdf, iv: iv); + } + final KDFParam kdf; + final List iv; + factory CryptoParam.fromJson(Map json) { + return CryptoParam( + kdf: KDFParam.fromJson(json), + iv: BytesUtils.fromHexString(json["cipherparams"]["iv"])); + } + static String _mac(List dk, List ciphertext) { + // Concatenate the derived key and ciphertext to form the input for the MAC calculation. + final mac = [...dk, ...ciphertext]; + + // Hash the concatenated data using Keccak. + return BytesUtils.toHexString(Keccack.hash(List.from(mac))); + } + + Map encode(List password, List data) { + final derived = List.unmodifiable(kdf.deriveKey(password)); + final macBytes = List.unmodifiable(derived.sublist(16, 32)); + final aesKey = List.from(derived.sublist(0, 16)); + final encryptOut = QuickCrypto.processCtr(key: aesKey, iv: iv, data: data); + return { + "cipher": "aes-128-ctr", + "cipherparams": {'iv': BytesUtils.toHexString(iv)}, + "ciphertext": BytesUtils.toHexString(encryptOut), + "kdf": kdf.type.name, + "kdfparams": kdf.encode(), + "mac": _mac(macBytes, encryptOut), + }; + } + + String encodeCbor(List password, List data, String uuid) { + final derived = List.unmodifiable(kdf.deriveKey(password)); + final macBytes = List.unmodifiable(derived.sublist(16, 32)); + final aesKey = List.from(derived.sublist(0, 16)); + final encryptOut = QuickCrypto.processCtr(key: aesKey, iv: iv, data: data); + return CborTagValue( + CborListValue.dynamicLength([ + CborListValue.fixedLength([ + CborStringValue("aes-128-ctr"), + CborBytesValue(iv), + CborBytesValue(encryptOut), + kdf.cborEncode(), + CborStringValue(_mac(macBytes, encryptOut)), + ]), + CborStringValue(uuid), + const CborIntValue(3), + ]), + _SecretStorageConst.tag) + .toCborHex(); + } +} + +/// +/// The `Web3SecretStorageDefinationV3` class represents a secret wallet that stores sensitive credentials +/// using a specified key derivation strategy. +class Web3SecretStorageDefinationV3 { + final List data; + final List _password; + final String uuid; + final CryptoParam _crypto; + Web3SecretStorageDefinationV3._( + this._crypto, List _password, this.uuid, List data) + : _password = BytesUtils.toBytes(_password, unmodifiable: true), + data = BytesUtils.toBytes(data, unmodifiable: true); + factory Web3SecretStorageDefinationV3( + {required CryptoParam param, + required List password, + required List data, + required String id}) { + return Web3SecretStorageDefinationV3( + param: param, password: password, data: data, id: id); + } + + /// Factory method to create a `Web3SecretStorageDefinationV3` with encoded credentials. + /// + /// - `credentials`: The encoded credentials to be stored in the wallet. + /// - `password`: The password used to derive the encryption key. + /// - `scryptN`: Parameter 'n' for the Scrypt key derivation function (default is 8192). + /// - `p`: Parameter 'p' for the Scrypt key derivation function (default is 1). + /// + /// Returns a `Web3SecretStorageDefinationV3` instance with the encoded credentials. + factory Web3SecretStorageDefinationV3.encode( + List data, + String password, { + int scryptN = 8192, + int p = 1, + }) { + final passwordBytes = StringUtils.encode(password); + final salt = QuickCrypto.generateRandom(_SecretStorageConst.saltLength); + final derivator = KDFScrypt(dklen: 32, n: scryptN, r: 8, p: p, salt: salt); + final uuid = UUID.generateUUIDv4(); + final iv = QuickCrypto.generateRandom(_SecretStorageConst.ivLength); + final CryptoParam crypto = CryptoParam(kdf: derivator, iv: iv); + return Web3SecretStorageDefinationV3._(crypto, passwordBytes, uuid, data); + } + + static Map _toJsonEcoded(String encoded, + {SecretWalletEncoding encoding = SecretWalletEncoding.json}) { + try { + if (encoding == SecretWalletEncoding.json) { + return StringUtils.toJson(encoded); + } + return StringUtils.toJson(StringUtils.decode( + StringUtils.encode(encoded, type: StringEncoding.base64))); + } catch (e) { + throw const Web3SecretStorageDefinationV3Exception("invalid encoding"); + } + } + + /// Factory method to decode and create a `Web3SecretStorageDefinationV3` from an encoded string and a password. + /// + /// - `encoded`: The encoded string containing wallet data. + /// - `password`: The password used to derive the encryption key. + /// + /// Returns a `Web3SecretStorageDefinationV3` instance decoded from the input data, or throws an error + /// if decoding or password validation fails. + factory Web3SecretStorageDefinationV3.decode(String encoded, String password, + {SecretWalletEncoding encoding = SecretWalletEncoding.json}) { + if (encoding == SecretWalletEncoding.cbor) { + return _decodeCbor(encoded, password); + } + final json = _toJsonEcoded(encoded, encoding: encoding); + + if (json['version'] != 3) { + throw const Web3SecretStorageDefinationV3Exception( + "Library only supports version 3"); + } + final crypto = json['crypto'] ?? json['Crypto']; + final KDFParam derivator = KDFParam.fromJson(crypto); + + final encodedPassword = List.from(StringUtils.encode(password)); + final derivedKey = derivator.deriveKey(encodedPassword); + final aesKey = List.from(derivedKey.sublist(0, 16)); + final List macBytes = derivedKey.sublist(16, 32); + final encryptedPrivateKey = BytesUtils.fromHexString(crypto["ciphertext"]); + final derivedMac = CryptoParam._mac(macBytes, encryptedPrivateKey); + if (derivedMac != crypto["mac"]) { + throw const Web3SecretStorageDefinationV3Exception( + "Wrong password or the file is corrupted"); + } + if (crypto["cipher"] != "aes-128-ctr") { + throw Web3SecretStorageDefinationV3Exception("Invalid Cypher.", + details: {"excepted": "aes-128-ctr", "cipher": crypto["cipher"]}); + } + final iv = BytesUtils.fromHexString(crypto['cipherparams']['iv']); + final encryptText = List.from(encryptedPrivateKey); + final List data = + QuickCrypto.processCtr(key: aesKey, iv: iv, data: encryptText); + return Web3SecretStorageDefinationV3._( + CryptoParam.fromJson(json['crypto'] ?? json['Crypto']), + encodedPassword, + json["id"], + data); + } + + static Web3SecretStorageDefinationV3 _decodeCbor( + String encoded, String password) { + try { + final cborTag = CborObject.fromCborHex(encoded); + if (cborTag is! CborTagValue || + cborTag.value is! CborListValue || + cborTag.value.value.length != 3) { + throw const Web3SecretStorageDefinationV3Exception( + "Invalid secret wallet cbor bytes"); + } + if (!BytesUtils.bytesEqual(cborTag.tags, _SecretStorageConst.tag)) { + throw const Web3SecretStorageDefinationV3Exception( + "invalid secret wallet cbor tag"); + } + final cbor = cborTag.value as CborListValue; + final int version = cbor.value[2].value; + if (version != _SecretStorageConst.version) { + throw const Web3SecretStorageDefinationV3Exception( + "Library only supports version ${_SecretStorageConst.version}"); + } + String uuid; + final uuidObj = cbor.value[1]; + if (uuidObj is CborStringValue) { + uuid = uuidObj.value; + } else { + uuid = UUID.fromBuffer(uuidObj.value); + } + final params = cbor.value[0] as CborListValue; + final String cipher = params.value[0].value; + if (cipher != "aes-128-ctr") { + throw Web3SecretStorageDefinationV3Exception("Invalid cypher type.", + details: {"excepted": "aes-128-ctr", "cypher": cipher}); + } + final List iv = params.value[1].value; + final kdf = KDFParam.fromCbor(params.value[3]); + final List ciphertext = params.value[2].value; + final String mac = params.value[4].value; + final encodedPassword = List.from(StringUtils.encode(password)); + final derivedKey = kdf.deriveKey(encodedPassword); + final List macBytes = + List.unmodifiable(derivedKey.sublist(16, 32)); + final aesKey = List.from(derivedKey.sublist(0, 16)); + final derivedMac = CryptoParam._mac(macBytes, ciphertext); + if (derivedMac != mac) { + throw const Web3SecretStorageDefinationV3Exception( + "wrong password or the file is corrupted"); + } + final List data = + QuickCrypto.processCtr(key: aesKey, iv: iv, data: ciphertext); + return Web3SecretStorageDefinationV3._( + CryptoParam(kdf: kdf, iv: iv), encodedPassword, uuid, data); + } on Web3SecretStorageDefinationV3Exception { + rethrow; + } catch (e) { + throw const Web3SecretStorageDefinationV3Exception( + "invalid secret wallet cbor bytes"); + } + } + + /// Encrypts the sensitive wallet data using the specified encoding format and returns + /// the encrypted representation. + /// + /// - `encoding`: The encoding format to use for the encrypted output (default is JSON). + /// + /// Returns the encrypted wallet data as a string in the chosen encoding format. + String encrypt({SecretWalletEncoding encoding = SecretWalletEncoding.json}) { + // print("cipher ${BytesUtils.toHexString(ciphertextBytes)}"); + if (encoding == SecretWalletEncoding.cbor) { + return _crypto.encodeCbor(_password, data, uuid); + } + + // Prepare the JSON representation of the encrypted data. + final Map toJson = { + "crypto": _crypto.encode(_password, data), + "id": uuid, + "version": 3 + }; + + // Convert the JSON to a string. + final toString = StringUtils.fromJson(toJson); + + // Based on the specified encoding format, return the encrypted data as a string. + if (encoding == SecretWalletEncoding.json) { + return toString; + } + return StringUtils.decode(StringUtils.encode(toString), + type: StringEncoding.base64); + } +} diff --git a/lib/signer/bitcoin_signer.dart b/lib/signer/bitcoin_signer.dart index e7aa69c..a9ea4e0 100644 --- a/lib/signer/bitcoin_signer.dart +++ b/lib/signer/bitcoin_signer.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/address/p2tr_addr.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curves.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/ecdsa/private_key.dart'; @@ -9,10 +9,7 @@ import 'package:blockchain_utils/crypto/crypto/cdsa/point/ec_projective_point.da import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; -import 'package:blockchain_utils/numbers/int_utils.dart'; import 'package:blockchain_utils/signer/ecdsa_signing_key.dart'; -import 'package:blockchain_utils/string/string.dart'; /// The [BitcoinSignerUtils] class provides utility methods related to Bitcoin signing operations. class BitcoinSignerUtils { @@ -62,7 +59,7 @@ class BitcoinSignerUtils { static List magicMessage(List message, String messagePrefix) { final prefixBytes = StringUtils.encode(messagePrefix); if (prefixBytes[0] != BitcoinSignerUtils.safeBitcoinMessagePrefix) { - throw ArgumentException( + throw const ArgumentException( "invalid message prefix. message prefix should start with 0x18"); } final magic = _magicPrefix(message, prefixBytes); @@ -177,7 +174,7 @@ class BitcoinSigner { List signSchnorrTransaction(List digest, {required List tapScripts, required bool tweak}) { if (digest.length != 32) { - throw ArgumentException("The message must be a 32-byte array."); + throw const ArgumentException("The message must be a 32-byte array."); } List byteKey = []; if (tweak) { @@ -193,7 +190,7 @@ class BitcoinSigner { final d0 = BigintUtils.fromBytes(byteKey); if (!(BigInt.one <= d0 && d0 <= BitcoinSignerUtils._order - BigInt.one)) { - throw ArgumentException( + throw const ArgumentException( "The secret key must be an integer in the range 1..n-1."); } final P = Curves.generatorSecp256k1 * d0; @@ -292,11 +289,11 @@ class BitcoinVerifier { bool verifySchnorr(List message, List signature, {List? tapleafScripts, required bool isTweak}) { if (message.length != 32) { - throw ArgumentException("The message must be a 32-byte array."); + throw const ArgumentException("The message must be a 32-byte array."); } if (signature.length != 64 && signature.length != 65) { - throw ArgumentException( + throw const ArgumentException( "The signature must be a 64-byte array or 65-bytes with sighash"); } @@ -344,7 +341,7 @@ class BitcoinVerifier { bool verifyMessage( List message, String messagePrefix, List signature) { if (signature.length != 64 && signature.length != 65) { - throw ArgumentException( + throw const ArgumentException( "bitcoin signature must be 64 bytes without recover-id or 65 bytes with recover-id"); } final List messgaeHash = QuickCrypto.sha256Hash( diff --git a/lib/signer/cardano/cardano_signer.dart b/lib/signer/cardano/cardano_signer.dart index 350b679..4e4e43c 100644 --- a/lib/signer/cardano/cardano_signer.dart +++ b/lib/signer/cardano/cardano_signer.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/ecc/bip_ecc.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/cdsa.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/numbers/numbers.dart'; +import 'package:blockchain_utils/utils/numbers/numbers.dart'; /// Constants used by the Solana signer for cryptographic operations. class CardanoSignerConst { diff --git a/lib/signer/ecdsa_signing_key.dart b/lib/signer/ecdsa_signing_key.dart index 4dfdd5b..476aff4 100644 --- a/lib/signer/ecdsa_signing_key.dart +++ b/lib/signer/ecdsa_signing_key.dart @@ -4,7 +4,7 @@ import 'package:blockchain_utils/crypto/crypto/cdsa/ecdsa/signature.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/ec_projective_point.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/rfc6979/rfc6979.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'dart:math' as math; import 'package:blockchain_utils/exception/exception.dart'; @@ -29,7 +29,8 @@ class EcdsaSigningKey { List digestBytes = List.from(digest); if (!truncate) { if (digest.length > generator.curve.baselen) { - throw ArgumentException("this curve is too short for digest length"); + throw const ArgumentException( + "this curve is too short for digest length"); } } else { digestBytes = digest.sublist(0, generator.curve.baselen); diff --git a/lib/signer/eth/eth_signature.dart b/lib/signer/eth/eth_signature.dart index 91514e0..99ed89c 100644 --- a/lib/signer/eth/eth_signature.dart +++ b/lib/signer/eth/eth_signature.dart @@ -1,6 +1,5 @@ -import 'package:blockchain_utils/binary/binary.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; import 'package:blockchain_utils/signer/eth/evm_signer.dart'; /// Utility class for Ethereum signature operations. diff --git a/lib/signer/eth/evm_signer.dart b/lib/signer/eth/evm_signer.dart index e0d723a..d831039 100644 --- a/lib/signer/eth/evm_signer.dart +++ b/lib/signer/eth/evm_signer.dart @@ -3,7 +3,7 @@ import 'package:blockchain_utils/crypto/quick_crypto.dart'; import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/signer/ecdsa_signing_key.dart'; import 'package:blockchain_utils/signer/eth/eth_signature.dart'; -import 'package:blockchain_utils/string/string.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// Constants used by the Ethereum Signer for cryptographic operations. /// @@ -107,7 +107,7 @@ class ETHSigner { List signProsonalMessage(List digest, {int? payloadLength}) { final prefix = ETHSignerConst.ethPersonalSignPrefix + (payloadLength?.toString() ?? digest.length.toString()); - final prefixBytes = StringUtils.encode(prefix, StringEncoding.ascii); + final prefixBytes = StringUtils.encode(prefix, type: StringEncoding.ascii); final sign = _signEcdsa([...prefixBytes, ...digest]); return sign.toBytes(true); } @@ -186,7 +186,8 @@ class ETHVerifier { if (hashMessage) { final prefix = ETHSignerConst.ethPersonalSignPrefix + (payloadLength?.toString() ?? message.length.toString()); - final prefixBytes = StringUtils.encode(prefix, StringEncoding.ascii); + final prefixBytes = + StringUtils.encode(prefix, type: StringEncoding.ascii); return QuickCrypto.keccack256Hash([...prefixBytes, ...message]); } return message; diff --git a/lib/signer/solana/solana_signer.dart b/lib/signer/solana/solana_signer.dart index 4e895f1..61ed91c 100644 --- a/lib/signer/solana/solana_signer.dart +++ b/lib/signer/solana/solana_signer.dart @@ -1,4 +1,7 @@ -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/bip/ecc/keys/ed25519_keys.dart'; +import 'package:blockchain_utils/crypto/crypto/crypto.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// Constants used by the Solana signer for cryptographic operations. class SolanaSignerConst { diff --git a/lib/signer/substrate/core/signer.dart b/lib/signer/substrate/core/signer.dart index ae4f0aa..2d61f04 100644 --- a/lib/signer/substrate/core/signer.dart +++ b/lib/signer/substrate/core/signer.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/bip/substrate/substrate.dart'; import 'package:blockchain_utils/signer/substrate/signers/substrate_ecdsa.dart'; import 'package:blockchain_utils/signer/substrate/signers/substrate_eddsa.dart'; import 'package:blockchain_utils/signer/substrate/signers/substrate_sr25519.dart'; diff --git a/lib/signer/substrate/core/verifier.dart b/lib/signer/substrate/core/verifier.dart index 802bf7b..b1f5306 100644 --- a/lib/signer/substrate/core/verifier.dart +++ b/lib/signer/substrate/core/verifier.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/bip/substrate/substrate.dart'; import 'package:blockchain_utils/signer/substrate/signers/substrate_ecdsa.dart'; import 'package:blockchain_utils/signer/substrate/signers/substrate_eddsa.dart'; import 'package:blockchain_utils/signer/substrate/signers/substrate_sr25519.dart'; diff --git a/lib/signer/substrate/signers/substrate_ecdsa.dart b/lib/signer/substrate/signers/substrate_ecdsa.dart index 69d2d2d..4ad33da 100644 --- a/lib/signer/substrate/signers/substrate_ecdsa.dart +++ b/lib/signer/substrate/signers/substrate_ecdsa.dart @@ -1,5 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/compare/compare.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/crypto.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; import 'package:blockchain_utils/exception/exceptions.dart'; @@ -8,7 +7,6 @@ import 'package:blockchain_utils/signer/eth/eth_signature.dart'; import 'package:blockchain_utils/signer/eth/evm_signer.dart'; import 'package:blockchain_utils/signer/substrate/core/signer.dart'; import 'package:blockchain_utils/signer/substrate/core/verifier.dart'; -import 'package:blockchain_utils/string/string.dart'; class _SubstrateEcdsaSignerCons { static const int vrfLength = ETHSignerConst.ethSignatureLength + @@ -109,7 +107,7 @@ class SubstrateEcdsaSigner implements BaseSubstrateSigner { List signProsonalMessage(List digest, {int? payloadLength}) { final prefix = ETHSignerConst.ethPersonalSignPrefix + (payloadLength?.toString() ?? digest.length.toString()); - final prefixBytes = StringUtils.encode(prefix, StringEncoding.ascii); + final prefixBytes = StringUtils.encode(prefix, type: StringEncoding.ascii); final sign = _signEcdsa([...prefixBytes, ...digest]); return sign.toBytes(true); } @@ -189,7 +187,8 @@ class SubstrateEcdsaVerifier implements BaseSubstrateVerifier { if (hashMessage) { final prefix = ETHSignerConst.ethPersonalSignPrefix + (payloadLength?.toString() ?? message.length.toString()); - final prefixBytes = StringUtils.encode(prefix, StringEncoding.ascii); + final prefixBytes = + StringUtils.encode(prefix, type: StringEncoding.ascii); return QuickCrypto.blake2b256Hash([...prefixBytes, ...message]); } return message; @@ -237,7 +236,7 @@ class SubstrateEcdsaVerifier implements BaseSubstrateVerifier { ...BytesUtils.tryToBytes(extra) ?? [], ...signature, ]); - return bytesEqual(vrf, vrfHash); + return BytesUtils.bytesEqual(vrf, vrfHash); } return false; } diff --git a/lib/signer/substrate/signers/substrate_eddsa.dart b/lib/signer/substrate/signers/substrate_eddsa.dart index 7750bff..b29c7e8 100644 --- a/lib/signer/substrate/signers/substrate_eddsa.dart +++ b/lib/signer/substrate/signers/substrate_eddsa.dart @@ -1,6 +1,9 @@ -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/crypto/quick_crypto.dart'; +import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/signer/solana/solana_signer.dart'; import 'package:blockchain_utils/signer/substrate/core/signer.dart'; import 'package:blockchain_utils/signer/substrate/core/verifier.dart'; +import 'package:blockchain_utils/utils/utils.dart'; class _SubstrateED25519SignerConstant { static final int vrfLength = @@ -97,7 +100,7 @@ class SubstrateED25519Verifier implements BaseSubstrateVerifier { ...BytesUtils.tryToBytes(extra) ?? [], ...signature, ]); - return bytesEqual(vrf, vrfHash); + return BytesUtils.bytesEqual(vrf, vrfHash); } return false; } diff --git a/lib/signer/substrate/signers/substrate_sr25519.dart b/lib/signer/substrate/signers/substrate_sr25519.dart index f876af3..d0b8546 100644 --- a/lib/signer/substrate/signers/substrate_sr25519.dart +++ b/lib/signer/substrate/signers/substrate_sr25519.dart @@ -1,4 +1,5 @@ -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/crypto/crypto/crypto.dart'; +import 'package:blockchain_utils/exception/exception.dart'; import 'package:blockchain_utils/signer/substrate/core/signer.dart'; import 'package:blockchain_utils/signer/substrate/core/verifier.dart'; diff --git a/lib/signer/substrate/substrate.dart b/lib/signer/substrate/substrate.dart index 42fa554..beab244 100644 --- a/lib/signer/substrate/substrate.dart +++ b/lib/signer/substrate/substrate.dart @@ -1,6 +1,8 @@ -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/bip/substrate/substrate_base.dart'; +import 'package:blockchain_utils/bip/substrate/substrate_keys.dart'; import 'package:blockchain_utils/signer/substrate/core/signer.dart'; import 'package:blockchain_utils/signer/substrate/core/verifier.dart'; +import 'package:blockchain_utils/utils/utils.dart'; class SubstrateSigner { final BaseSubstrateSigner _signer; diff --git a/lib/signer/tron/tron_signer.dart b/lib/signer/tron/tron_signer.dart index 7140891..c6ae4ee 100644 --- a/lib/signer/tron/tron_signer.dart +++ b/lib/signer/tron/tron_signer.dart @@ -1,5 +1,10 @@ -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/crypto/crypto/crypto.dart'; +import 'package:blockchain_utils/crypto/quick_crypto.dart'; +import 'package:blockchain_utils/exception/exception.dart'; import 'package:blockchain_utils/signer/ecdsa_signing_key.dart'; +import 'package:blockchain_utils/signer/eth/eth_signature.dart'; +import 'package:blockchain_utils/signer/eth/evm_signer.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// Constants used by the Tron Signer for cryptographic operations. /// @@ -90,7 +95,7 @@ class TronSigner { ? ETHSignerConst.ethPersonalSignPrefix : TronSignerConst.tronPersonalSignPrefix; prefix = prefix + (payloadLength?.toString() ?? digest.length.toString()); - final prefixBytes = StringUtils.encode(prefix, StringEncoding.ascii); + final prefixBytes = StringUtils.encode(prefix, type: StringEncoding.ascii); return _signEcdsa( QuickCrypto.keccack256Hash([...prefixBytes, ...digest]), hashMessage: false); @@ -160,7 +165,8 @@ class TronVerifier { : TronSignerConst.tronPersonalSignPrefix; prefix = prefix + (payloadLength?.toString() ?? message.length.toString()); - final prefixBytes = StringUtils.encode(prefix, StringEncoding.ascii); + final prefixBytes = + StringUtils.encode(prefix, type: StringEncoding.ascii); message = QuickCrypto.keccack256Hash([...prefixBytes, ...message]); } if (signature.length > ETHSignerConst.ethSignatureLength) { @@ -190,7 +196,8 @@ class TronVerifier { : TronSignerConst.tronPersonalSignPrefix; prefix = prefix + (payloadLength?.toString() ?? message.length.toString()); - final prefixBytes = StringUtils.encode(prefix, StringEncoding.ascii); + final prefixBytes = + StringUtils.encode(prefix, type: StringEncoding.ascii); message = QuickCrypto.keccack256Hash([...prefixBytes, ...message]); } diff --git a/lib/signer/xrp_signer.dart b/lib/signer/xrp_signer.dart index 6c50ebe..6f0e7e9 100644 --- a/lib/signer/xrp_signer.dart +++ b/lib/signer/xrp_signer.dart @@ -1,5 +1,9 @@ -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/bip/ecc/bip_ecc.dart'; +import 'package:blockchain_utils/crypto/crypto/crypto.dart'; +import 'package:blockchain_utils/crypto/quick_crypto.dart'; +import 'package:blockchain_utils/exception/exception.dart'; import 'package:blockchain_utils/signer/ecdsa_signing_key.dart'; +import 'package:blockchain_utils/utils/utils.dart'; /// Constants used by the XRP signer for cryptographic operations. class _XrpSignerConst { @@ -10,7 +14,7 @@ class _XrpSignerConst { static final ProjectiveECCPoint secp256 = Curves.generatorSecp256k1; /// The length of the digest in bytes. - static final int digestLength = 32; + static const int digestLength = 32; /// The order of the SECP256k1 elliptic curve. static final curveOrder = secp256.order!; diff --git a/lib/ss58/ss58_base.dart b/lib/ss58/ss58_base.dart index 2fca5c4..035e3c4 100644 --- a/lib/ss58/ss58_base.dart +++ b/lib/ss58/ss58_base.dart @@ -1,12 +1,8 @@ import 'dart:typed_data'; - import 'package:blockchain_utils/base58/base58_base.dart'; -import 'package:blockchain_utils/compare/compare.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/numbers/int_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; import 'ss58_ex.dart'; @@ -142,7 +138,7 @@ class SS58Decoder { final checksumBytesGot = _Ss58Utils.computeChecksum( decBytes.sublist(0, decBytes.length - checkSumLength)); - if (!bytesEqual(checksumBytesGot, checksumBytes)) { + if (!BytesUtils.bytesEqual(checksumBytesGot, checksumBytes)) { throw SS58ChecksumError( 'Invalid checksum (expected ${BytesUtils.toHexString(checksumBytesGot)}, ' 'got ${BytesUtils.toHexString(checksumBytes)})'); diff --git a/lib/ss58/ss58_ex.dart b/lib/ss58/ss58_ex.dart index f72b91f..9f48670 100644 --- a/lib/ss58/ss58_ex.dart +++ b/lib/ss58/ss58_ex.dart @@ -7,8 +7,11 @@ class SS58ChecksumError implements BlockchainUtilsException { @override final String message; + @override + final Map? details; + /// Creates a new [SS58ChecksumError] with an optional [message]. - const SS58ChecksumError(this.message); + const SS58ChecksumError(this.message, {this.details}); @override String toString() { diff --git a/lib/binary/binary_operation.dart b/lib/utils/binary/binary_operation.dart similarity index 96% rename from lib/binary/binary_operation.dart rename to lib/utils/binary/binary_operation.dart index 7a24997..672416d 100644 --- a/lib/binary/binary_operation.dart +++ b/lib/utils/binary/binary_operation.dart @@ -112,3 +112,9 @@ void zero(List array) { } final BigInt maxU64 = BigInt.parse("18446744073709551615"); + +final BigInt maskBig8 = BigInt.from(mask8); + +final BigInt maskBig16 = BigInt.from(mask16); + +final BigInt maskBig32 = BigInt.from(mask32); diff --git a/lib/binary/bit_utils.dart b/lib/utils/binary/bit_utils.dart similarity index 100% rename from lib/binary/bit_utils.dart rename to lib/utils/binary/bit_utils.dart diff --git a/lib/binary/tracker.dart b/lib/utils/binary/bytes_tracker.dart similarity index 87% rename from lib/binary/tracker.dart rename to lib/utils/binary/bytes_tracker.dart index b61b98a..5c4430d 100644 --- a/lib/binary/tracker.dart +++ b/lib/utils/binary/bytes_tracker.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'utils.dart'; /// A utility class for tracking bytes dynamically. class DynamicByteTracker { diff --git a/lib/binary/utils.dart b/lib/utils/binary/utils.dart similarity index 81% rename from lib/binary/utils.dart rename to lib/utils/binary/utils.dart index eb91404..d37a2ca 100644 --- a/lib/binary/utils.dart +++ b/lib/utils/binary/utils.dart @@ -1,9 +1,9 @@ -import 'package:blockchain_utils/binary/binary_operation.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; -import 'package:blockchain_utils/string/string.dart'; - import 'package:blockchain_utils/hex/hex.dart' as hex; +import 'package:blockchain_utils/utils/numbers/utils/bigint_utils.dart'; +import 'package:blockchain_utils/utils/string/string.dart'; + +import 'binary_operation.dart'; /// A utility class for working with binary data represented as lists of integers (bytes). class BytesUtils { @@ -112,7 +112,7 @@ class BytesUtils { } return hex.hex.decode(hexString); } catch (e) { - throw ArgumentException("invalid hex bytes"); + throw const ArgumentException("invalid hex bytes"); } } @@ -189,4 +189,46 @@ class BytesUtils { return 0; } + + /// Compare two lists of bytes for equality. + /// This function compares two lists of bytes 'a' and 'b' for equality. It returns true + /// if the lists are equal (including null check), false if they have different lengths + /// or contain different byte values, and true if the lists reference the same object. + static bool bytesEqual(List? a, List? b) { + /// Check if 'a' is null and handle null comparison. + if (a == null) { + return b == null; + } + + /// Check if 'b' is null or if the lengths of 'a' and 'b' are different. + if (b == null || a.length != b.length) { + return false; + } + + /// Check if 'a' and 'b' reference the same object (identity comparison). + if (identical(a, b)) { + return true; + } + + /// Compare the individual byte values in 'a' and 'b'. + for (int index = 0; index < a.length; index += 1) { + if (a[index] != b[index]) { + return false; + } + } + + /// If no differences were found, the lists are equal. + return true; + } + + static bool isLessThanBytes(List thashedA, List thashedB) { + for (int i = 0; i < thashedA.length && i < thashedB.length; i++) { + if (thashedA[i] < thashedB[i]) { + return true; + } else if (thashedA[i] > thashedB[i]) { + return false; + } + } + return thashedA.length < thashedB.length; + } } diff --git a/lib/utils/compare/compare.dart b/lib/utils/compare/compare.dart new file mode 100644 index 0000000..67d1a3d --- /dev/null +++ b/lib/utils/compare/compare.dart @@ -0,0 +1,32 @@ +class CompareUtils { + /// Compare two lists of bytes for equality. + /// This function compares two lists of bytes 'a' and 'b' for equality. It returns true + /// if the lists are equal (including null check), false if they have different lengths + /// or contain different byte values, and true if the lists reference the same object. + static bool iterableIsEqual(Iterable? a, Iterable? b) { + /// Check if 'a' is null and handle null comparison. + if (a == null) { + return b == null; + } + + /// Check if 'b' is null or if the lengths of 'a' and 'b' are different. + if (b == null || a.length != b.length) { + return false; + } + + /// Check if 'a' and 'b' reference the same object (identity comparison). + if (identical(a, b)) { + return true; + } + + /// Compare the individual byte values in 'a' and 'b'. + for (int index = 0; index < a.length; index += 1) { + if (a.elementAt(index) != b.elementAt(index)) { + return false; + } + } + + /// If no differences were found, the lists are equal. + return true; + } +} diff --git a/lib/utils/numbers/numbers.dart b/lib/utils/numbers/numbers.dart new file mode 100644 index 0000000..3a61a45 --- /dev/null +++ b/lib/utils/numbers/numbers.dart @@ -0,0 +1,7 @@ +export 'utils/bigint_utils.dart'; + +/// bigint utils +export 'utils/int_utils.dart'; + +/// BigintUtils +export 'rational/big_rational.dart'; diff --git a/lib/numbers/big_rational.dart b/lib/utils/numbers/rational/big_rational.dart similarity index 96% rename from lib/numbers/big_rational.dart rename to lib/utils/numbers/rational/big_rational.dart index 3648c67..f6907ed 100644 --- a/lib/numbers/big_rational.dart +++ b/lib/utils/numbers/rational/big_rational.dart @@ -1,4 +1,5 @@ -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/utils/numbers/utils/bigint_utils.dart'; /// Represents a rational number with arbitrary precision using BigInt for the numerator and denominator. class BigRational { @@ -26,12 +27,12 @@ class BigRational { BigRational._(this.numerator, this.denominator); /// Constructs a BigRational instance from the given numerator and optional denominator. - factory BigRational(BigInt numerator, [BigInt? denominator]) { + factory BigRational(BigInt numerator, {BigInt? denominator}) { if (denominator == null) { return BigRational._(numerator, _one); } if (denominator == _zero) { - throw ArgumentException("Denominator cannot be 0."); + throw const ArgumentException("Denominator cannot be 0."); } if (numerator == _zero) { return BigRational._(_zero, _one); @@ -40,8 +41,9 @@ class BigRational { } /// Constructs a BigRational instance from the given numerator and optional denominator as integers. - factory BigRational.from(int numerator, [int? denominator]) { - return BigRational(BigInt.from(numerator), BigInt.from(denominator ?? 1)); + factory BigRational.from(int numerator, {int? denominator}) { + return BigRational(BigInt.from(numerator), + denominator: BigInt.from(denominator ?? 1)); } /// Finds the greatest common divisor of two BigInt numbers a and b. @@ -78,7 +80,7 @@ class BigRational { factory BigRational.parseDecimal(String decimal) { List parts = decimal.split(RegExp(r'e', caseSensitive: false)); if (parts.length > 2) { - throw ArgumentException("Invalid input: too many 'e' tokens"); + throw const ArgumentException("Invalid input: too many 'e' tokens"); } if (parts.length > 1) { @@ -102,7 +104,7 @@ class BigRational { parts = decimal.trim().split("."); if (parts.length > 2) { - throw ArgumentException("Invalid input: too many '.' tokens"); + throw const ArgumentException("Invalid input: too many '.' tokens"); } if (parts.length > 1) { bool isNegative = parts[0][0] == '-'; diff --git a/lib/numbers/bigint_utils.dart b/lib/utils/numbers/utils/bigint_utils.dart similarity index 96% rename from lib/numbers/bigint_utils.dart rename to lib/utils/numbers/utils/bigint_utils.dart index 34159fa..c96722c 100644 --- a/lib/numbers/bigint_utils.dart +++ b/lib/utils/numbers/utils/bigint_utils.dart @@ -1,10 +1,11 @@ import 'dart:typed_data'; -import 'package:blockchain_utils/binary/binary_operation.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/binary/binary_operation.dart'; +import 'package:blockchain_utils/utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/string/string.dart'; +import 'package:blockchain_utils/utils/tuple/tuple.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/string/string.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; -import 'package:blockchain_utils/numbers/int_utils.dart'; + +import 'int_utils.dart'; class BigintUtils { /// Converts a BigInt 'num' into a List of bytes with a specified 'order'. @@ -419,7 +420,7 @@ class BigintUtils { } // ignore: empty_catches } catch (e) {} - throw ArgumentException("invalid input for parse bigint"); + throw const ArgumentException("invalid input for parse bigint"); } /// Tries to parse a dynamic value [v] into a BigInt, returning null if parsing fails. @@ -442,11 +443,11 @@ class BigintUtils { } static List variableNatEncode(BigInt val) { - BigInt num = val & BigInt.from(mask32); - List output = [(num & BigInt.from(0xFF)).toInt() & 0x7F]; + BigInt num = val & maskBig32; + List output = [(num & maskBig8).toInt() & 0x7F]; num ~/= BigInt.from(128); while (num > BigInt.zero) { - output.add(((num & BigInt.from(0xFF)).toInt() & 0x7F) | 0x80); + output.add(((num & maskBig8).toInt() & 0x7F) | 0x80); num ~/= BigInt.from(128); } output = output.reversed.toList(); @@ -459,7 +460,7 @@ class BigintUtils { for (int byte in bytes) { output = (output << 7) | BigInt.from(byte & 0x7F); if (output > maxU64) { - throw MessageException( + throw const MessageException( "The variable size exceeds the limit for Nat Decode"); } bytesRead++; @@ -467,6 +468,6 @@ class BigintUtils { return Tuple(output, bytesRead); } } - throw MessageException("Nat Decode failed."); + throw const MessageException("Nat Decode failed."); } } diff --git a/lib/numbers/int_utils.dart b/lib/utils/numbers/utils/int_utils.dart similarity index 94% rename from lib/numbers/int_utils.dart rename to lib/utils/numbers/utils/int_utils.dart index 0f01337..f8ad3c1 100644 --- a/lib/numbers/int_utils.dart +++ b/lib/utils/numbers/utils/int_utils.dart @@ -1,10 +1,9 @@ import 'dart:typed_data'; - -import 'package:blockchain_utils/binary/binary_operation.dart'; -import 'package:blockchain_utils/string/string.dart'; -import 'package:blockchain_utils/tuple/tuple.dart'; +import 'package:blockchain_utils/utils/binary/binary_operation.dart'; +import 'package:blockchain_utils/utils/numbers/utils/bigint_utils.dart'; +import 'package:blockchain_utils/utils/string/string.dart'; +import 'package:blockchain_utils/utils/tuple/tuple.dart'; import 'package:blockchain_utils/exception/exception.dart'; -import 'package:blockchain_utils/numbers/bigint_utils.dart'; /// Utility class for integer-related operations and conversions. class IntUtils { @@ -38,7 +37,8 @@ class IntUtils { BigInt value = BigintUtils.fromBytes(byteint.sublist(1, 1 + size), byteOrder: Endian.little); if (!value.isValidInt) { - throw MessageException("cannot read variable-length in this environment"); + throw const MessageException( + "cannot read variable-length in this environment"); } return Tuple(value.toInt(), size + 1); } @@ -190,7 +190,7 @@ class IntUtils { } // ignore: empty_catches } catch (e) {} - throw ArgumentException("invalid input for parse int"); + throw const ArgumentException("invalid input for parse int"); } /// Tries to parse a dynamic value [v] into an integer, returning null if parsing fails. diff --git a/lib/string/string.dart b/lib/utils/string/string.dart similarity index 67% rename from lib/string/string.dart rename to lib/utils/string/string.dart index a3e16ae..b637d6e 100644 --- a/lib/string/string.dart +++ b/lib/utils/string/string.dart @@ -1,6 +1,5 @@ import 'dart:convert'; - -import 'package:blockchain_utils/binary/binary.dart'; +import 'package:blockchain_utils/utils/binary/utils.dart'; /// An enumeration representing different string encoding options. enum StringEncoding { @@ -17,6 +16,7 @@ enum StringEncoding { /// The base64 encoding option base64, + base64UrlSafe } /// A utility class for working with strings and common string operations. @@ -57,12 +57,6 @@ class StringUtils { /// If the input [value] starts with '0x', this method returns the /// substring of [value] without those two characters. If [value] /// does not start with '0x', it returns the original [value]. - /// - /// Example: - /// ```dart - /// String stripped = StringUtils.strip0x("0x123abc"); // Returns "123abc" - /// String original = StringUtils.strip0x("abcdef"); // Returns "abcdef" - /// ``` static String strip0x(String value) { if (value.toLowerCase().startsWith("0x")) { return value.substring(2); @@ -74,28 +68,28 @@ class StringUtils { /// /// The [type] parameter determines the encoding type to use, with UTF-8 being the default. /// Returns a list of bytes representing the encoded string. - /// - /// Example: - /// ```dart - /// List encodedBytes = StringUtils.encode("Hello, World!"); - /// ``` static List encode(String value, - [StringEncoding type = StringEncoding.utf8]) { + {StringEncoding type = StringEncoding.utf8}) { switch (type) { case StringEncoding.utf8: return utf8.encode(value); case StringEncoding.base64: + case StringEncoding.base64UrlSafe: return base64Decode(value); default: return ascii.encode(value); } } + /// Encodes the given [value] string into a list of bytes using the specified [type] if possible. + /// + /// The [type] parameter determines the encoding type to use, with UTF-8 being the default. + /// Returns a list of bytes representing the encoded string. static List? tryEncode(String? value, - [StringEncoding type = StringEncoding.utf8]) { + {StringEncoding type = StringEncoding.utf8}) { if (value == null) return null; try { - return encode(value, type); + return encode(value, type: type); } catch (e) { return null; } @@ -105,31 +99,32 @@ class StringUtils { /// /// The [type] parameter determines the decoding type to use, with UTF-8 being the default. /// Returns the decoded string. - /// - /// Example: - /// ```dart - /// String decodedString = StringUtils.decode([72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33]); - /// ``` - static String decode( - List value, [ - StringEncoding type = StringEncoding.utf8, - bool allowInvalidOrMalformed = false, - ]) { + static String decode(List value, + {StringEncoding type = StringEncoding.utf8, + bool allowInvalidOrMalformed = false}) { switch (type) { case StringEncoding.utf8: return utf8.decode(value, allowMalformed: allowInvalidOrMalformed); case StringEncoding.base64: return base64Encode(value); + case StringEncoding.base64UrlSafe: + return base64UrlEncode(value); default: return ascii.decode(value, allowInvalid: allowInvalidOrMalformed); } } + /// Decodes a list of bytes [value] into a string using the specified [type] if possible. + /// + /// The [type] parameter determines the decoding type to use, with UTF-8 being the default. + /// Returns the decoded string. static String? tryDecode(List? value, - [StringEncoding type = StringEncoding.utf8]) { + {StringEncoding type = StringEncoding.utf8, + bool allowInvalidOrMalformed = false}) { if (value == null) return null; try { - return decode(value, type); + return decode(value, + type: type, allowInvalidOrMalformed: allowInvalidOrMalformed); } catch (e) { return null; } @@ -149,4 +144,27 @@ class StringUtils { static dynamic toJson(String data) { return jsonDecode(data); } + + /// Converts a Dart object represented as a Map to a JSON-encoded string if possible. + /// + /// The input [data] is a Map representing the Dart object. + static String? tryFromJson(Object? data) { + try { + return fromJson(data!); + } catch (e) { + return null; + } + } + + /// Converts a JSON-encoded string to a Dart object represented as a Map if possible. + /// + /// The input [data] is a JSON-encoded string. + /// Returns a Map representing the Dart object. + static Object? tryToJson(String data) { + try { + return toJson(data); + } catch (e) { + return null; + } + } } diff --git a/lib/tuple/tuple.dart b/lib/utils/tuple/tuple.dart similarity index 100% rename from lib/tuple/tuple.dart rename to lib/utils/tuple/tuple.dart diff --git a/lib/utils/utils.dart b/lib/utils/utils.dart new file mode 100644 index 0000000..28688e3 --- /dev/null +++ b/lib/utils/utils.dart @@ -0,0 +1,9 @@ +export 'binary/binary_operation.dart'; +export 'binary/bit_utils.dart'; +export 'binary/utils.dart'; +export 'binary/bytes_tracker.dart'; + +export 'compare/compare.dart'; +export 'numbers/numbers.dart'; +export 'string/string.dart'; +export 'tuple/tuple.dart'; diff --git a/lib/uuid/uuid.dart b/lib/uuid/uuid.dart index 912a2f6..c8b1af2 100644 --- a/lib/uuid/uuid.dart +++ b/lib/uuid/uuid.dart @@ -10,7 +10,7 @@ library uuid; import 'dart:math' as math; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; class UUID { @@ -77,9 +77,10 @@ class UUID { /// final buffer = toBuffer(uuid); /// print(buffer); /// Output: [85, 14, 132, 0, 226, 155, 65, 212, 167, 22, 68, 102, 85, 68, 0, 0] /// ``` - static List toBuffer(String uuidString) { - if (!isValidUUIDv4(uuidString)) { - throw ArgumentException("invalid uuid string."); + static List toBuffer(String uuidString, {bool validate = true}) { + if (validate && !isValidUUIDv4(uuidString)) { + throw ArgumentException("invalid uuid string.", + details: {"uuid": uuidString}); } final buffer = List.filled(16, 0); @@ -122,7 +123,7 @@ class UUID { /// This method assumes that the input buffer contains valid UUIDv4 data. static String fromBuffer(List buffer) { if (buffer.length != 16) { - throw ArgumentException( + throw const ArgumentException( 'Invalid buffer length. UUIDv4 buffers must be 16 bytes long.'); } diff --git a/pubspec.yaml b/pubspec.yaml index ee60c55..18a070d 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: blockchain_utils description: Comprehensive Crypto & Blockchain Toolkit, Pure Dart, Cross-Platform, Encoding, Cryptography, Addresses, Mnemonics, & More. -version: 3.0.0 +version: 3.1.0 homepage: "https://github.com/mrtnetwork/blockchain_utils" repository: "https://github.com/mrtnetwork/blockchain_utils" Author: mrhaydari.t@gmail.com @@ -20,8 +20,9 @@ dependencies: dev_dependencies: - lints: ^3.0.0 + lints: ^4.0.0 test: ^1.25.2 + flutter_lints: ^4.0.0 # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/test/address/ada_byron/byron_test.dart b/test/address/ada_byron/byron_test.dart index ddc01b2..311b9fc 100644 --- a/test/address/ada_byron/byron_test.dart +++ b/test/address/ada_byron/byron_test.dart @@ -1,6 +1,5 @@ import 'package:blockchain_utils/bip/address/ada/ada_byron_addr.dart'; -import 'package:blockchain_utils/binary/utils.dart'; -import 'package:blockchain_utils/compare/compare.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'byron_test_vector.dart' as byron; import 'lagacy_test_vector.dart' as lagacy; @@ -15,7 +14,9 @@ void main() { .encodeKey(BytesUtils.fromHexString(i["public"]), params); expect(l, i["address"]); final decode = AdaByronAddrDecoder().decodeAddr(l); - expect(bytesEqual(decode, BytesUtils.fromHexString(i["decode"])), true); + expect( + BytesUtils.bytesEqual(decode, BytesUtils.fromHexString(i["decode"])), + true); } }); @@ -27,7 +28,9 @@ void main() { .encodeKey(BytesUtils.fromHexString(i["public"]), params); expect(l, i["address"]); final decode = AdaByronAddrDecoder().decodeAddr(l); - expect(bytesEqual(decode, BytesUtils.fromHexString(i["decode"])), true); + expect( + BytesUtils.bytesEqual(decode, BytesUtils.fromHexString(i["decode"])), + true); } }); } diff --git a/test/address/ada_shelly/ada_shelly_test.dart b/test/address/ada_shelly/ada_shelly_test.dart index 8b62095..b75fc49 100644 --- a/test/address/ada_shelly/ada_shelly_test.dart +++ b/test/address/ada_shelly/ada_shelly_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/ada/ada_shelley_addr.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/address/encoders.dart'; import 'package:test/test.dart'; import '../../quick_hex.dart'; diff --git a/test/address/algo/algo_test.dart b/test/address/algo/algo_test.dart index 0c97e0c..c898faf 100644 --- a/test/address/algo/algo_test.dart +++ b/test/address/algo/algo_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/algo_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/address/aptos/aptos_test.dart b/test/address/aptos/aptos_test.dart index 181780a..29c9882 100644 --- a/test/address/aptos/aptos_test.dart +++ b/test/address/aptos/aptos_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/aptos_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/address/atom/atom_test.dart b/test/address/atom/atom_test.dart index 44fe643..a366ab8 100644 --- a/test/address/atom/atom_test.dart +++ b/test/address/atom/atom_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/atom_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/address/avax/avax_test.dart b/test/address/avax/avax_test.dart index 3f0d9cc..127a2ee 100644 --- a/test/address/avax/avax_test.dart +++ b/test/address/avax/avax_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/avax_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_p_vector.dart' as p; diff --git a/test/address/bch_p2pkh/bch_p2pkh_test.dart b/test/address/bch_p2pkh/bch_p2pkh_test.dart index 5e4f28c..56bcc94 100644 --- a/test/address/bch_p2pkh/bch_p2pkh_test.dart +++ b/test/address/bch_p2pkh/bch_p2pkh_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/bch_p2sh/bch_p2sh_test.dart b/test/address/bch_p2sh/bch_p2sh_test.dart index 81c5c60..2550891 100644 --- a/test/address/bch_p2sh/bch_p2sh_test.dart +++ b/test/address/bch_p2sh/bch_p2sh_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/p2sh_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/egld/egld_test.dart b/test/address/egld/egld_test.dart index cda242b..2d526e0 100644 --- a/test/address/egld/egld_test.dart +++ b/test/address/egld/egld_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/egld_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/eos/eos_test.dart b/test/address/eos/eos_test.dart index f38a174..84fa0b2 100644 --- a/test/address/eos/eos_test.dart +++ b/test/address/eos/eos_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/eos_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/ergo/ergo_test.dart b/test/address/ergo/ergo_test.dart index 5681032..880ef92 100644 --- a/test/address/ergo/ergo_test.dart +++ b/test/address/ergo/ergo_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/ergo.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/eth/eth_test.dart b/test/address/eth/eth_test.dart index 11db3d7..de058d8 100644 --- a/test/address/eth/eth_test.dart +++ b/test/address/eth/eth_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/eth_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/fil/fil_test.dart b/test/address/fil/fil_test.dart index 752a8fc..6de681e 100644 --- a/test/address/fil/fil_test.dart +++ b/test/address/fil/fil_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/fil_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/icx/icx_test.dart b/test/address/icx/icx_test.dart index 088d0a6..2d1d249 100644 --- a/test/address/icx/icx_test.dart +++ b/test/address/icx/icx_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/icx_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVecotr; diff --git a/test/address/inj/inj_test.dart b/test/address/inj/inj_test.dart index f1843b3..9c90656 100644 --- a/test/address/inj/inj_test.dart +++ b/test/address/inj/inj_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/inj_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/nano/nano_test.dart b/test/address/nano/nano_test.dart index 5689244..f29e281 100644 --- a/test/address/nano/nano_test.dart +++ b/test/address/nano/nano_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/nano_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/near/near_test.dart b/test/address/near/near_test.dart index 704461e..1d12775 100644 --- a/test/address/near/near_test.dart +++ b/test/address/near/near_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/near_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/neo/neo_test.dart b/test/address/neo/neo_test.dart index 1f4db1c..9b7a992 100644 --- a/test/address/neo/neo_test.dart +++ b/test/address/neo/neo_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/neo_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVecotr; diff --git a/test/address/okex/okex_test.dart b/test/address/okex/okex_test.dart index 08e6f4f..6e4ccc1 100644 --- a/test/address/okex/okex_test.dart +++ b/test/address/okex/okex_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/okex_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/one/one_test.dart b/test/address/one/one_test.dart index a092818..aabc691 100644 --- a/test/address/one/one_test.dart +++ b/test/address/one/one_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/one_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/p2pkh/p2pkh_test.dart b/test/address/p2pkh/p2pkh_test.dart index 34da60b..ada6440 100644 --- a/test/address/p2pkh/p2pkh_test.dart +++ b/test/address/p2pkh/p2pkh_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'comperesed_test_vector.dart' show compresedTestVector; diff --git a/test/address/p2sh/p2sh_test.dart b/test/address/p2sh/p2sh_test.dart index d6a79ce..8067060 100644 --- a/test/address/p2sh/p2sh_test.dart +++ b/test/address/p2sh/p2sh_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/p2sh_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/p2tr/p2tr_test.dart b/test/address/p2tr/p2tr_test.dart index 158bf28..8cc6bcb 100644 --- a/test/address/p2tr/p2tr_test.dart +++ b/test/address/p2tr/p2tr_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/p2tr_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/p2wpkh/p2wpkh_test.dart b/test/address/p2wpkh/p2wpkh_test.dart index b24bad4..90a60be 100644 --- a/test/address/p2wpkh/p2wpkh_test.dart +++ b/test/address/p2wpkh/p2wpkh_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/p2wpkh_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/sol/sol_test.dart b/test/address/sol/sol_test.dart index b12d4eb..a7ccddd 100644 --- a/test/address/sol/sol_test.dart +++ b/test/address/sol/sol_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/sol_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/substrate/substrate_test.dart b/test/address/substrate/substrate_test.dart index 87a4002..3b954b4 100644 --- a/test/address/substrate/substrate_test.dart +++ b/test/address/substrate/substrate_test.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/bip/address/substrate_addr.dart'; import '../../quick_hex.dart'; import 'package:test/test.dart'; diff --git a/test/address/ton/address_test.dart b/test/address/ton/address_test.dart new file mode 100644 index 0000000..e5970a9 --- /dev/null +++ b/test/address/ton/address_test.dart @@ -0,0 +1,28 @@ +import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:test/test.dart'; + +import 'test_vector.dart'; + +void main() { + _test(); +} + +void _test() { + test("Ton encode, decode address", () { + final encoder = TonAddrEncoder(); + final decoder = TonAddrDecoder(); + for (final i in tonTestVector) { + final hash = BytesUtils.fromHexString(i["hash"]); + final String bounceable = + encoder.encodeKey(hash, {"workchain": i["workchain"]}); + final String nonBounceable = encoder + .encodeKey(hash, {"workchain": i["workchain"], "bounceable": false}); + expect(bounceable, i["bounceable"]); + expect(nonBounceable, i["nonBounceable"]); + final decodeBounceable = decoder.decodeAddr(bounceable); + final decodeNonBounceable = decoder.decodeAddr(bounceable); + expect(decodeBounceable, hash); + expect(decodeNonBounceable, hash); + } + }); +} diff --git a/test/address/ton/test_vector.dart b/test/address/ton/test_vector.dart new file mode 100644 index 0000000..48dc13a --- /dev/null +++ b/test/address/ton/test_vector.dart @@ -0,0 +1,152 @@ +const List> tonTestVector = [ + { + "hash": "62037b44ae833a2d813b8083240d6215638f89fea962f44539ccc2e133acb4fd", + "workchain": -1, + "raw": + "-1:62037b44ae833a2d813b8083240d6215638f89fea962f44539ccc2e133acb4fd", + "bounceable": "Ef9iA3tEroM6LYE7gIMkDWIVY4-J_qli9EU5zMLhM6y0_ekS", + "nonBounceable": "Uf9iA3tEroM6LYE7gIMkDWIVY4-J_qli9EU5zMLhM6y0_bTX" + }, + { + "hash": "c2a47f25781d3130b53cb5ac9a92fd889a092654bfdb77bfa49dd3d36c8e9935", + "workchain": -1, + "raw": + "-1:c2a47f25781d3130b53cb5ac9a92fd889a092654bfdb77bfa49dd3d36c8e9935", + "bounceable": "Ef_CpH8leB0xMLU8tayakv2ImgkmVL_bd7-kndPTbI6ZNWDs", + "nonBounceable": "Uf_CpH8leB0xMLU8tayakv2ImgkmVL_bd7-kndPTbI6ZNT0p" + }, + { + "hash": "7d8cc8a7b4e78207e010e07189be68d2c6c3e1cea9ef5eab76422e7c80acff99", + "workchain": -1, + "raw": + "-1:7d8cc8a7b4e78207e010e07189be68d2c6c3e1cea9ef5eab76422e7c80acff99", + "bounceable": "Ef99jMintOeCB-AQ4HGJvmjSxsPhzqnvXqt2Qi58gKz_mXwl", + "nonBounceable": "Uf99jMintOeCB-AQ4HGJvmjSxsPhzqnvXqt2Qi58gKz_mSHg" + }, + { + "hash": "fc83332c81eca62b71ef683ed57a989997a3f5fbbd96e6d6408caecc0f1f6432", + "workchain": -1, + "raw": + "-1:fc83332c81eca62b71ef683ed57a989997a3f5fbbd96e6d6408caecc0f1f6432", + "bounceable": "Ef_8gzMsgeymK3HvaD7VepiZl6P1-72W5tZAjK7MDx9kMtQl", + "nonBounceable": "Uf_8gzMsgeymK3HvaD7VepiZl6P1-72W5tZAjK7MDx9kMong" + }, + { + "hash": "9f6442bc7677aacc2f925a1f5cce6cb5a7e70aac81dbc709856920e348a0815f", + "workchain": -1, + "raw": + "-1:9f6442bc7677aacc2f925a1f5cce6cb5a7e70aac81dbc709856920e348a0815f", + "bounceable": "Ef-fZEK8dneqzC-SWh9czmy1p-cKrIHbxwmFaSDjSKCBX-pc", + "nonBounceable": "Uf-fZEK8dneqzC-SWh9czmy1p-cKrIHbxwmFaSDjSKCBX7eZ" + }, + { + "hash": "a522a9316b1e2a9f6ec6de5fbffb8ae90a9d9ea1e2308a0b9e3745b6efcc08ee", + "workchain": -1, + "raw": + "-1:a522a9316b1e2a9f6ec6de5fbffb8ae90a9d9ea1e2308a0b9e3745b6efcc08ee", + "bounceable": "Ef-lIqkxax4qn27G3l-_-4rpCp2eoeIwigueN0W278wI7pyr", + "nonBounceable": "Uf-lIqkxax4qn27G3l-_-4rpCp2eoeIwigueN0W278wI7sFu" + }, + { + "hash": "a277bea903e7227f2cfbe46094b56c1077519253abc5152fc8af7e468480aa13", + "workchain": -1, + "raw": + "-1:a277bea903e7227f2cfbe46094b56c1077519253abc5152fc8af7e468480aa13", + "bounceable": "Ef-id76pA-cifyz75GCUtWwQd1GSU6vFFS_Ir35GhICqE5rk", + "nonBounceable": "Uf-id76pA-cifyz75GCUtWwQd1GSU6vFFS_Ir35GhICqE8ch" + }, + { + "hash": "d40b1ff87599aa745eef58dd47aa34142f85df80fccb6a9325c3485117b94c76", + "workchain": -1, + "raw": + "-1:d40b1ff87599aa745eef58dd47aa34142f85df80fccb6a9325c3485117b94c76", + "bounceable": "Ef_UCx_4dZmqdF7vWN1HqjQUL4XfgPzLapMlw0hRF7lMdoxK", + "nonBounceable": "Uf_UCx_4dZmqdF7vWN1HqjQUL4XfgPzLapMlw0hRF7lMdtGP" + }, + { + "hash": "bee7641a5ab642abb64bda24502ed6fc0f72275c5451b4daa598f271708a0987", + "workchain": -1, + "raw": + "-1:bee7641a5ab642abb64bda24502ed6fc0f72275c5451b4daa598f271708a0987", + "bounceable": "Ef--52QaWrZCq7ZL2iRQLtb8D3InXFRRtNqlmPJxcIoJh6yV", + "nonBounceable": "Uf--52QaWrZCq7ZL2iRQLtb8D3InXFRRtNqlmPJxcIoJh_FQ" + }, + { + "hash": "c5333e6559e786661d0a9afaf6a8c2ba70ee228da05571de08f9d4cef5d85605", + "workchain": -1, + "raw": + "-1:c5333e6559e786661d0a9afaf6a8c2ba70ee228da05571de08f9d4cef5d85605", + "bounceable": "Ef_FMz5lWeeGZh0Kmvr2qMK6cO4ijaBVcd4I-dTO9dhWBS4i", + "nonBounceable": "Uf_FMz5lWeeGZh0Kmvr2qMK6cO4ijaBVcd4I-dTO9dhWBXPn" + }, + { + "hash": "62037b44ae833a2d813b8083240d6215638f89fea962f44539ccc2e133acb4fd", + "workchain": 0, + "raw": "0:62037b44ae833a2d813b8083240d6215638f89fea962f44539ccc2e133acb4fd", + "bounceable": "EQBiA3tEroM6LYE7gIMkDWIVY4-J_qli9EU5zMLhM6y0_RZa", + "nonBounceable": "UQBiA3tEroM6LYE7gIMkDWIVY4-J_qli9EU5zMLhM6y0_Uuf" + }, + { + "hash": "c2a47f25781d3130b53cb5ac9a92fd889a092654bfdb77bfa49dd3d36c8e9935", + "workchain": 0, + "raw": "0:c2a47f25781d3130b53cb5ac9a92fd889a092654bfdb77bfa49dd3d36c8e9935", + "bounceable": "EQDCpH8leB0xMLU8tayakv2ImgkmVL_bd7-kndPTbI6ZNZ-k", + "nonBounceable": "UQDCpH8leB0xMLU8tayakv2ImgkmVL_bd7-kndPTbI6ZNcJh" + }, + { + "hash": "7d8cc8a7b4e78207e010e07189be68d2c6c3e1cea9ef5eab76422e7c80acff99", + "workchain": 0, + "raw": "0:7d8cc8a7b4e78207e010e07189be68d2c6c3e1cea9ef5eab76422e7c80acff99", + "bounceable": "EQB9jMintOeCB-AQ4HGJvmjSxsPhzqnvXqt2Qi58gKz_mYNt", + "nonBounceable": "UQB9jMintOeCB-AQ4HGJvmjSxsPhzqnvXqt2Qi58gKz_md6o" + }, + { + "hash": "fc83332c81eca62b71ef683ed57a989997a3f5fbbd96e6d6408caecc0f1f6432", + "workchain": 0, + "raw": "0:fc83332c81eca62b71ef683ed57a989997a3f5fbbd96e6d6408caecc0f1f6432", + "bounceable": "EQD8gzMsgeymK3HvaD7VepiZl6P1-72W5tZAjK7MDx9kMitt", + "nonBounceable": "UQD8gzMsgeymK3HvaD7VepiZl6P1-72W5tZAjK7MDx9kMnao" + }, + { + "hash": "9f6442bc7677aacc2f925a1f5cce6cb5a7e70aac81dbc709856920e348a0815f", + "workchain": 0, + "raw": "0:9f6442bc7677aacc2f925a1f5cce6cb5a7e70aac81dbc709856920e348a0815f", + "bounceable": "EQCfZEK8dneqzC-SWh9czmy1p-cKrIHbxwmFaSDjSKCBXxUU", + "nonBounceable": "UQCfZEK8dneqzC-SWh9czmy1p-cKrIHbxwmFaSDjSKCBX0jR" + }, + { + "hash": "a522a9316b1e2a9f6ec6de5fbffb8ae90a9d9ea1e2308a0b9e3745b6efcc08ee", + "workchain": 0, + "raw": "0:a522a9316b1e2a9f6ec6de5fbffb8ae90a9d9ea1e2308a0b9e3745b6efcc08ee", + "bounceable": "EQClIqkxax4qn27G3l-_-4rpCp2eoeIwigueN0W278wI7mPj", + "nonBounceable": "UQClIqkxax4qn27G3l-_-4rpCp2eoeIwigueN0W278wI7j4m" + }, + { + "hash": "a277bea903e7227f2cfbe46094b56c1077519253abc5152fc8af7e468480aa13", + "workchain": 0, + "raw": "0:a277bea903e7227f2cfbe46094b56c1077519253abc5152fc8af7e468480aa13", + "bounceable": "EQCid76pA-cifyz75GCUtWwQd1GSU6vFFS_Ir35GhICqE2Ws", + "nonBounceable": "UQCid76pA-cifyz75GCUtWwQd1GSU6vFFS_Ir35GhICqEzhp" + }, + { + "hash": "d40b1ff87599aa745eef58dd47aa34142f85df80fccb6a9325c3485117b94c76", + "workchain": 0, + "raw": "0:d40b1ff87599aa745eef58dd47aa34142f85df80fccb6a9325c3485117b94c76", + "bounceable": "EQDUCx_4dZmqdF7vWN1HqjQUL4XfgPzLapMlw0hRF7lMdnMC", + "nonBounceable": "UQDUCx_4dZmqdF7vWN1HqjQUL4XfgPzLapMlw0hRF7lMdi7H" + }, + { + "hash": "bee7641a5ab642abb64bda24502ed6fc0f72275c5451b4daa598f271708a0987", + "workchain": 0, + "raw": "0:bee7641a5ab642abb64bda24502ed6fc0f72275c5451b4daa598f271708a0987", + "bounceable": "EQC-52QaWrZCq7ZL2iRQLtb8D3InXFRRtNqlmPJxcIoJh1Pd", + "nonBounceable": "UQC-52QaWrZCq7ZL2iRQLtb8D3InXFRRtNqlmPJxcIoJhw4Y" + }, + { + "hash": "c5333e6559e786661d0a9afaf6a8c2ba70ee228da05571de08f9d4cef5d85605", + "workchain": 0, + "raw": "0:c5333e6559e786661d0a9afaf6a8c2ba70ee228da05571de08f9d4cef5d85605", + "bounceable": "EQDFMz5lWeeGZh0Kmvr2qMK6cO4ijaBVcd4I-dTO9dhWBdFq", + "nonBounceable": "UQDFMz5lWeeGZh0Kmvr2qMK6cO4ijaBVcd4I-dTO9dhWBYyv" + } +]; diff --git a/test/address/trx/trx_test.dart b/test/address/trx/trx_test.dart index a26534a..bc2814b 100644 --- a/test/address/trx/trx_test.dart +++ b/test/address/trx/trx_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/trx_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVecotr; diff --git a/test/address/xlm/xml_test.dart b/test/address/xlm/xml_test.dart index 98c3837..9480393 100644 --- a/test/address/xlm/xml_test.dart +++ b/test/address/xlm/xml_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/xlm_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/xmr/xmr_test.dart b/test/address/xmr/xmr_test.dart index a9666eb..7d40d0c 100644 --- a/test/address/xmr/xmr_test.dart +++ b/test/address/xmr/xmr_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/xmr_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/xrp/xrp_test.dart b/test/address/xrp/xrp_test.dart index 70b3e25..b483656 100644 --- a/test/address/xrp/xrp_test.dart +++ b/test/address/xrp/xrp_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/xrp_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/xtz/xtz_test.dart b/test/address/xtz/xtz_test.dart index 1241c07..862ce7d 100644 --- a/test/address/xtz/xtz_test.dart +++ b/test/address/xtz/xtz_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/xtz_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/address/zil/zil_test.dart b/test/address/zil/zil_test.dart index 33d7068..49b070f 100644 --- a/test/address/zil/zil_test.dart +++ b/test/address/zil/zil_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/zil_addr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart' show testVector; diff --git a/test/algorand/mnemonic_test.dart b/test/algorand/mnemonic_test.dart index 7d46c56..29d37e9 100644 --- a/test/algorand/mnemonic_test.dart +++ b/test/algorand/mnemonic_test.dart @@ -4,7 +4,7 @@ import 'package:blockchain_utils/bip/algorand/mnemonic/algorand_mnemonic_validat import 'package:blockchain_utils/bip/algorand/mnemonic/algorand_seed_generator.dart'; import 'package:blockchain_utils/bip/bip/bip44/bip44_base.dart'; import 'package:blockchain_utils/bip/bip/conf/bip44/bip44_coins.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import '../quick_hex.dart'; import 'test_vector.dart'; diff --git a/test/base58/base58_test.dart b/test/base58/base58_test.dart index 0980965..74e3b75 100644 --- a/test/base58/base58_test.dart +++ b/test/base58/base58_test.dart @@ -1,5 +1,5 @@ import 'package:blockchain_utils/base58/base58_base.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; final List> testVectBtc = [ diff --git a/test/base58/base58_xmr_test.dart b/test/base58/base58_xmr_test.dart index 21d0eba..3a77268 100644 --- a/test/base58/base58_xmr_test.dart +++ b/test/base58/base58_xmr_test.dart @@ -1,7 +1,7 @@ // ignore_for_file: depend_on_referenced_packages import 'package:blockchain_utils/base58/base58_xmr.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; import 'package:test/test.dart'; diff --git a/test/bech32/bch_bech32_test.dart b/test/bech32/bch_bech32_test.dart index 66a494b..11f9a8a 100644 --- a/test/bech32/bch_bech32_test.dart +++ b/test/bech32/bch_bech32_test.dart @@ -36,7 +36,7 @@ void main() { final decode = BchBech32Decoder.decode(hrp, i["encode"]!); expect(BytesUtils.toHexString(decode.item2), i["raw"]); expect( - bytesEqual( + BytesUtils.bytesEqual( decode.item1, CoinsConf.bitcoinCashMainNet.params.p2pkhStdNetVer), true); } diff --git a/test/bech32/bech32_test.dart b/test/bech32/bech32_test.dart index 2918b2e..203171d 100644 --- a/test/bech32/bech32_test.dart +++ b/test/bech32/bech32_test.dart @@ -1,5 +1,5 @@ import 'package:blockchain_utils/bech32/bech32_base.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; import 'package:test/test.dart'; diff --git a/test/bech32/segwit_bech32_test.dart b/test/bech32/segwit_bech32_test.dart index f4c8cc6..4b46b4a 100644 --- a/test/bech32/segwit_bech32_test.dart +++ b/test/bech32/segwit_bech32_test.dart @@ -1,7 +1,7 @@ // ignore_for_file: depend_on_referenced_packages import 'package:blockchain_utils/bech32/segwit_bech32.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; final List> _testVectors = [ diff --git a/test/bip/bip32/ed25519/ed25519_test.dart b/test/bip/bip32/ed25519/ed25519_test.dart index cb7ae06..4afd2c1 100644 --- a/test/bip/bip32/ed25519/ed25519_test.dart +++ b/test/bip/bip32/ed25519/ed25519_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip32/slip10/bip32_slip10_ed25519.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/bip/bip32/ed25519_blake2b/ed25519_blake2b_test.dart b/test/bip/bip32/ed25519_blake2b/ed25519_blake2b_test.dart index 5fa2802..ef7e547 100644 --- a/test/bip/bip32/ed25519_blake2b/ed25519_blake2b_test.dart +++ b/test/bip/bip32/ed25519_blake2b/ed25519_blake2b_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip32/slip10/bip32_slip10_ed25519_blake2b.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/bip/bip32/ed25519_khalow/ed25519_khalow_test.dart b/test/bip/bip32/ed25519_khalow/ed25519_khalow_test.dart index 8d14e40..d058611 100644 --- a/test/bip/bip32/ed25519_khalow/ed25519_khalow_test.dart +++ b/test/bip/bip32/ed25519_khalow/ed25519_khalow_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip32/khalow/bip32_kholaw_ed25519.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/bip/bip32/nist256p1/nist256p1_test.dart b/test/bip/bip32/nist256p1/nist256p1_test.dart index 6e6ab81..b973058 100644 --- a/test/bip/bip32/nist256p1/nist256p1_test.dart +++ b/test/bip/bip32/nist256p1/nist256p1_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip32/slip10/bip32_slip10_nist256p1.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/bip/bip38/bip38_addr_test.dart b/test/bip/bip38/bip38_addr_test.dart index f45d469..337149e 100644 --- a/test/bip/bip38/bip38_addr_test.dart +++ b/test/bip/bip38/bip38_addr_test.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:blockchain_utils/bip/bip/bip38/bip38_addr.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; List> _testVector = [ diff --git a/test/bip/bip38/bip38_no_ec_test.dart b/test/bip/bip38/bip38_no_ec_test.dart index 54cae42..dfd8105 100644 --- a/test/bip/bip38/bip38_no_ec_test.dart +++ b/test/bip/bip38/bip38_no_ec_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:blockchain_utils/bip/bip/bip38/bip38_base.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; List> _testVector = [ diff --git a/test/bip/bip39/bip39_test.dart b/test/bip/bip39/bip39_test.dart index d98315d..15f93ac 100644 --- a/test/bip/bip39/bip39_test.dart +++ b/test/bip/bip39/bip39_test.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic.dart'; import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic_decoder.dart'; import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic_generator.dart'; import 'package:blockchain_utils/bip/bip/bip39/bip39_seed_generator.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import '../../quick_hex.dart'; import 'test_vector.dart' show testVector; diff --git a/test/bip/bip44/bip44_test.dart b/test/bip/bip44/bip44_test.dart index 40a0692..43f3c99 100644 --- a/test/bip/bip44/bip44_test.dart +++ b/test/bip/bip44/bip44_test.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/bip/bip/bip44/bip44_base.dart'; import 'package:blockchain_utils/bip/bip/conf/bip44/bip44_coins.dart'; import 'package:blockchain_utils/bip/monero/monero_base.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/bip/bip49/bip49_test.dart b/test/bip/bip49/bip49_test.dart index c070166..bb81bb0 100644 --- a/test/bip/bip49/bip49_test.dart +++ b/test/bip/bip49/bip49_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/bip/bip49/bip49_base.dart'; import 'package:blockchain_utils/bip/bip/conf/bip49/bip49_coins.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/bip/bip84/bip84_test.dart b/test/bip/bip84/bip84_test.dart index 59f21c5..b85c4f6 100644 --- a/test/bip/bip84/bip84_test.dart +++ b/test/bip/bip84/bip84_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/bip/bip84/bip84_base.dart'; import 'package:blockchain_utils/bip/bip/conf/bip84/bip84_coins.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/bip/bip86/bip86_test.dart b/test/bip/bip86/bip86_test.dart index 33515a9..8ab951c 100644 --- a/test/bip/bip86/bip86_test.dart +++ b/test/bip/bip86/bip86_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/bip/bip86/bip86_base.dart'; import 'package:blockchain_utils/bip/bip/conf/bip86/bip86_coins.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/cardano/bip32/icarus_test.dart b/test/cardano/bip32/icarus_test.dart index 22d8e51..3b490e3 100644 --- a/test/cardano/bip32/icarus_test.dart +++ b/test/cardano/bip32/icarus_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/cardano/bip32/cardano_icarus_bip32.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'icarus_test_vector.dart'; diff --git a/test/cardano/bip32/legacy_test.dart b/test/cardano/bip32/legacy_test.dart index 01e1f24..0f608d1 100644 --- a/test/cardano/bip32/legacy_test.dart +++ b/test/cardano/bip32/legacy_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/cardano/bip32/cardano_byron_legacy_bip32.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/cardano/byron/byron_lagacy_test.dart b/test/cardano/byron/byron_lagacy_test.dart index 721f508..89008d7 100644 --- a/test/cardano/byron/byron_lagacy_test.dart +++ b/test/cardano/byron/byron_lagacy_test.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/cardano/byron/cardano_byron_legacy.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import '../../quick_hex.dart'; import 'test_vector.dart'; diff --git a/test/cardano/cip1852/cip1852_test.dart b/test/cardano/cip1852/cip1852_test.dart index 47ca3be..a722184 100644 --- a/test/cardano/cip1852/cip1852_test.dart +++ b/test/cardano/cip1852/cip1852_test.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/bip/bip44/base/bip44_base.dart'; import 'package:blockchain_utils/bip/cardano/cip1852/cip1852.dart'; import 'package:blockchain_utils/bip/cardano/cip1852/conf/cip1852_coins.dart'; import 'package:blockchain_utils/bip/cardano/shelley/cardano_shelley.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/cbor_test.dart b/test/cbor_test.dart index 03a76c0..1972854 100644 --- a/test/cbor_test.dart +++ b/test/cbor_test.dart @@ -36,7 +36,7 @@ void _decodeStringIndefinite() { final dec = CborObject.fromCbor(cb.encode()); expect(dec.runtimeType, CborIndefiniteStringValue); dec as CborIndefiniteStringValue; - expect(iterableIsEqual(dec.value, cb.value), true); + expect(CompareUtils.iterableIsEqual(dec.value, cb.value), true); } void _decodeMap() { @@ -48,10 +48,10 @@ void _decodeMap() { dec as CborMapValue; final keys = cb.value.keys.map((e) => e).toList(); final keysDec = dec.value.keys.map((e) => e.value).toList(); - expect(iterableIsEqual(keys, keysDec), true); + expect(CompareUtils.iterableIsEqual(keys, keysDec), true); final values = cb.value.values.map((e) => e).toList(); final valuesDec = dec.value.values.map((e) => e.value).toList(); - expect(iterableIsEqual(values, valuesDec), true); + expect(CompareUtils.iterableIsEqual(values, valuesDec), true); } void _decodeMapDynamic() { @@ -66,10 +66,10 @@ void _decodeMapDynamic() { dec as CborMapValue; final keys = cb.value.keys.map((e) => e).toList(); final keysDec = dec.value.keys.map((e) => e.value).toList(); - expect(iterableIsEqual(keys, keysDec), true); + expect(CompareUtils.iterableIsEqual(keys, keysDec), true); final values = cb.value.values.map((e) => e).toList(); final valuesDec = dec.value.values.map((e) => e.value).toList(); - expect(iterableIsEqual(values, valuesDec), true); + expect(CompareUtils.iterableIsEqual(values, valuesDec), true); } void _decodeList() { @@ -86,7 +86,7 @@ void _decodeList() { dec as CborListValue; final valuesDec = dec.value.map((e) => e.value).toList(); - expect(iterableIsEqual(cb.value, valuesDec), true); + expect(CompareUtils.iterableIsEqual(cb.value, valuesDec), true); } void _decodeDateTime() { diff --git a/test/crypto/aes/aes_ctr_test.dart b/test/crypto/aes/aes_ctr_test.dart index b0b70ab..2ed03d1 100644 --- a/test/crypto/aes/aes_ctr_test.dart +++ b/test/crypto/aes/aes_ctr_test.dart @@ -3,7 +3,7 @@ import 'dart:typed_data'; import 'package:blockchain_utils/crypto/crypto/aes/aes.dart'; import 'package:blockchain_utils/crypto/crypto/ctr/ctr.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/crypto/blake2b/blake2b_test.dart b/test/crypto/blake2b/blake2b_test.dart index a5002a1..bdb35a4 100644 --- a/test/crypto/blake2b/blake2b_test.dart +++ b/test/crypto/blake2b/blake2b_test.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/crypto/chacha20_poly1305/chacha20_poly1305_test.dart b/test/crypto/chacha20_poly1305/chacha20_poly1305_test.dart index 899d640..1d784af 100644 --- a/test/crypto/chacha20_poly1305/chacha20_poly1305_test.dart +++ b/test/crypto/chacha20_poly1305/chacha20_poly1305_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/chacha20poly1305/chacha20poly1305.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/crypto/crc32/crc32_test.dart b/test/crypto/crc32/crc32_test.dart index 6e382a0..e720273 100644 --- a/test/crypto/crc32/crc32_test.dart +++ b/test/crypto/crc32/crc32_test.dart @@ -1,5 +1,5 @@ import 'package:blockchain_utils/crypto/crypto/crc32/crc32.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/crypto/hmac/hmac_test.dart b/test/crypto/hmac/hmac_test.dart index 9e4faa6..772d81d 100644 --- a/test/crypto/hmac/hmac_test.dart +++ b/test/crypto/hmac/hmac_test.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:blockchain_utils/crypto/crypto/hmac/hmac.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/crypto/keccack/keccack_test.dart b/test/crypto/keccack/keccack_test.dart index 10d1aa7..c8bbfe5 100644 --- a/test/crypto/keccack/keccack_test.dart +++ b/test/crypto/keccack/keccack_test.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:test/test.dart'; diff --git a/test/crypto/md4/md4_test.dart b/test/crypto/md4/md4_test.dart index 9235fd5..81f9418 100644 --- a/test/crypto/md4/md4_test.dart +++ b/test/crypto/md4/md4_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/crypto/md5/md5_test.dart b/test/crypto/md5/md5_test.dart index aeb99fd..5a6fd1e 100644 --- a/test/crypto/md5/md5_test.dart +++ b/test/crypto/md5/md5_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/crypto/pbkdf2/pbkdf2_test.dart b/test/crypto/pbkdf2/pbkdf2_test.dart index cdb7338..4c4fee8 100644 --- a/test/crypto/pbkdf2/pbkdf2_test.dart +++ b/test/crypto/pbkdf2/pbkdf2_test.dart @@ -3,7 +3,7 @@ import 'package:blockchain_utils/crypto/crypto/hmac/hmac.dart'; import 'package:blockchain_utils/crypto/crypto/pbkdf2/pbkdf2.dart'; import 'package:test/test.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/test/crypto/ripemd/ripemd_test.dart b/test/crypto/ripemd/ripemd_test.dart index 84f9408..54bd4c2 100644 --- a/test/crypto/ripemd/ripemd_test.dart +++ b/test/crypto/ripemd/ripemd_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/crypto/scrypt/scrypt_test.dart b/test/crypto/scrypt/scrypt_test.dart index c07e060..f94e846 100644 --- a/test/crypto/scrypt/scrypt_test.dart +++ b/test/crypto/scrypt/scrypt_test.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/crypto/crypto/scrypt/scrypt.dart'; import 'package:test/test.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'test_vector.dart'; diff --git a/test/crypto/sha1/sha1_test.dart b/test/crypto/sha1/sha1_test.dart index 96ba678..d20dcab 100644 --- a/test/crypto/sha1/sha1_test.dart +++ b/test/crypto/sha1/sha1_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/crypto/sha256/sha256_test.dart b/test/crypto/sha256/sha256_test.dart index 50bfd94..f6837a8 100644 --- a/test/crypto/sha256/sha256_test.dart +++ b/test/crypto/sha256/sha256_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/crypto/sha3/sha3_test.dart b/test/crypto/sha3/sha3_test.dart index e0572af..a18d94a 100644 --- a/test/crypto/sha3/sha3_test.dart +++ b/test/crypto/sha3/sha3_test.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:test/test.dart'; diff --git a/test/crypto/sha512/sha512_test.dart b/test/crypto/sha512/sha512_test.dart index de396dc..7732043 100644 --- a/test/crypto/sha512/sha512_test.dart +++ b/test/crypto/sha512/sha512_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/crypto/sha512_256/sha512_256_test.dart b/test/crypto/sha512_256/sha512_256_test.dart index e4158d9..dd35026 100644 --- a/test/crypto/sha512_256/sha512_256_test.dart +++ b/test/crypto/sha512_256/sha512_256_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/crypto/shake/shake_test.dart b/test/crypto/shake/shake_test.dart index 58e136c..bb587e0 100644 --- a/test/crypto/shake/shake_test.dart +++ b/test/crypto/shake/shake_test.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector_256.dart'; diff --git a/test/crypto/x_modem_crc/x_modem_crc_test.dart b/test/crypto/x_modem_crc/x_modem_crc_test.dart index aeeb735..86ae1a9 100644 --- a/test/crypto/x_modem_crc/x_modem_crc_test.dart +++ b/test/crypto/x_modem_crc/x_modem_crc_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/x_modem_crc/x_modem_crc.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'test_vector.dart'; diff --git a/test/crypto/xxhash64/xxhash64_test.dart b/test/crypto/xxhash64/xxhash64_test.dart index 4949b14..7a3f067 100644 --- a/test/crypto/xxhash64/xxhash64_test.dart +++ b/test/crypto/xxhash64/xxhash64_test.dart @@ -1,8 +1,6 @@ -import 'package:blockchain_utils/binary/binary.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:test/test.dart'; - import 'test_vector.dart'; void main() { diff --git a/test/ecdsa/ed_test.dart b/test/ecdsa/ed_test.dart index 4dd0e9b..cb1e94b 100644 --- a/test/ecdsa/ed_test.dart +++ b/test/ecdsa/ed_test.dart @@ -4,7 +4,7 @@ import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curves.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/eddsa/privatekey.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/edwards.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import '../quick_hex.dart'; diff --git a/test/ecdsa/projective_test.dart b/test/ecdsa/projective_test.dart index 050dbbf..7343794 100644 --- a/test/ecdsa/projective_test.dart +++ b/test/ecdsa/projective_test.dart @@ -1,12 +1,10 @@ import 'dart:typed_data'; - -import 'package:blockchain_utils/numbers/bigint_utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curves.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/ecdsa/private_key.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/ec_projective_point.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/rfc6979/rfc6979.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; -import 'package:blockchain_utils/binary/utils.dart'; import 'package:test/test.dart'; void _testEqualWithAffinePoint() { diff --git a/test/elctrum/mnemonic/mnemonic_test.dart b/test/elctrum/mnemonic/mnemonic_test.dart index a706046..3cb32ca 100644 --- a/test/elctrum/mnemonic/mnemonic_test.dart +++ b/test/elctrum/mnemonic/mnemonic_test.dart @@ -7,8 +7,7 @@ import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic.d import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_decoder.dart'; import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_generator.dart'; import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_seed_generator.dart'; -import 'package:blockchain_utils/compare/compare.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import '../../quick_hex.dart'; import 'test_vector_v1.dart'; @@ -30,9 +29,10 @@ void main() { final decode = ElectrumV2MnemonicDecoder(mnemonicType: type, language: lang) .decode(mn.toStr()); - expect(bytesEqual(decode, entropy), true); + expect(BytesUtils.bytesEqual(decode, entropy), true); final seed = ElectrumV2SeedGenerator(mn, lang).generate("MRT"); - expect(bytesEqual(seed, BytesUtils.fromHexString(i["seed"])), true); + expect(BytesUtils.bytesEqual(seed, BytesUtils.fromHexString(i["seed"])), + true); if (i["address"] != null) { String addr; if (type.name.startsWith("segwit")) { @@ -52,7 +52,7 @@ void main() { final seed = ElectrumV1SeedGenerator(toMnemonic.toStr()).generate(); expect(seed.toHex(), i["seed"]); final en = ElectrumV1MnemonicDecoder().decode(toMnemonic.toStr()); - expect(bytesEqual(en, entropy), true); + expect(BytesUtils.bytesEqual(en, entropy), true); final addr = ElectrumV1.fromSeed(seed).getAddress(0, 0); expect(addr, i["address"]); } diff --git a/test/elctrum/v1/v1_test.dart b/test/elctrum/v1/v1_test.dart index 3589d80..8ca0c6b 100644 --- a/test/elctrum/v1/v1_test.dart +++ b/test/elctrum/v1/v1_test.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; import 'package:blockchain_utils/bip/electrum/electrum_v1.dart'; import 'package:blockchain_utils/bip/wif/wif.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import '../../quick_hex.dart'; diff --git a/test/elctrum/v2/v2_test.dart b/test/elctrum/v2/v2_test.dart index dff7bbd..d18c8c7 100644 --- a/test/elctrum/v2/v2_test.dart +++ b/test/elctrum/v2/v2_test.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; import 'package:blockchain_utils/bip/electrum/electrum_v2.dart'; import 'package:blockchain_utils/bip/wif/wif.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import '../../quick_hex.dart'; diff --git a/test/monero/mnemonic/monero_mnemonic_test.dart b/test/monero/mnemonic/monero_mnemonic_test.dart index a3b8387..e6d421d 100644 --- a/test/monero/mnemonic/monero_mnemonic_test.dart +++ b/test/monero/mnemonic/monero_mnemonic_test.dart @@ -2,8 +2,7 @@ import 'package:blockchain_utils/bip/monero/mnemonic/monero_mnemonic.dart'; import 'package:blockchain_utils/bip/monero/mnemonic/monero_mnemonic_decoder.dart'; import 'package:blockchain_utils/bip/monero/mnemonic/monero_mnemonic_generator.dart'; import 'package:blockchain_utils/bip/monero/mnemonic/monero_seed_generator.dart'; -import 'package:blockchain_utils/compare/compare.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import "test_vector.dart"; @@ -19,9 +18,9 @@ void main() { final mnNc = MoneroMnemonicGenerator(lang).fromEntropyNoChecksum(entropy); expect(mnNc.toStr(), i["no_checksum"]); final entropyResult = MoneroMnemonicDecoder(lang).decode(mn.toStr()); - expect(bytesEqual(entropyResult, entropy), true); + expect(BytesUtils.bytesEqual(entropyResult, entropy), true); final seed = MoneroSeedGenerator(mn).generate(); - expect(bytesEqual(seed, entropy), true); + expect(BytesUtils.bytesEqual(seed, entropy), true); } }); } diff --git a/test/monero/monero_test.dart b/test/monero/monero_test.dart index 7e3dbd4..d70951f 100644 --- a/test/monero/monero_test.dart +++ b/test/monero/monero_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/monero/conf/monero_coins.dart'; import 'package:blockchain_utils/bip/monero/monero_base.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import '../quick_hex.dart'; import 'test_vector.dart'; diff --git a/test/quick_hex.dart b/test/quick_hex.dart index affa46f..c6cd963 100644 --- a/test/quick_hex.dart +++ b/test/quick_hex.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; extension HEX on List { String toHex() => BytesUtils.toHexString(this); diff --git a/test/schnorrkel/derive_test.dart b/test/schnorrkel/derive_test.dart index 50b3a35..b37c1d1 100644 --- a/test/schnorrkel/derive_test.dart +++ b/test/schnorrkel/derive_test.dart @@ -1,5 +1,5 @@ import 'package:blockchain_utils/crypto/crypto/schnorrkel/keys/keys.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import '../quick_hex.dart'; diff --git a/test/schnorrkel/schnorrkel_key_test.dart b/test/schnorrkel/schnorrkel_key_test.dart index 4ea826d..33b9edb 100644 --- a/test/schnorrkel/schnorrkel_key_test.dart +++ b/test/schnorrkel/schnorrkel_key_test.dart @@ -1,7 +1,7 @@ // all keys generated from https://github.com/noot/schnorrkel/blob/f7551a43845ba65e8782a2c7d80439111eeda687/src/keys.rs#L983 import 'package:blockchain_utils/crypto/crypto/schnorrkel/keys/keys.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import '../quick_hex.dart'; diff --git a/test/schnorrkel/sign_test.dart b/test/schnorrkel/sign_test.dart index a7198c4..4760165 100644 --- a/test/schnorrkel/sign_test.dart +++ b/test/schnorrkel/sign_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/schnorrkel/keys/keys.dart'; import 'package:blockchain_utils/crypto/crypto/schnorrkel/merlin/transcript.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import '../quick_hex.dart'; diff --git a/test/schnorrkel/vrf_test.dart b/test/schnorrkel/vrf_test.dart index 3019f2d..bd14730 100644 --- a/test/schnorrkel/vrf_test.dart +++ b/test/schnorrkel/vrf_test.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/crypto/crypto/schnorrkel/keys/keys.dart'; import 'package:blockchain_utils/crypto/crypto/schnorrkel/merlin/transcript.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import '../quick_hex.dart'; import 'vrf_test_vector.dart' as vrf_test; diff --git a/test/secure_storage_test.dart b/test/secure_storage_test.dart index f1d3ecf..21f0a79 100644 --- a/test/secure_storage_test.dart +++ b/test/secure_storage_test.dart @@ -1,49 +1,133 @@ import 'package:blockchain_utils/blockchain_utils.dart'; - import 'package:test/test.dart'; - import 'quick_hex.dart'; void main() { + /// https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition#pbkdf2-sha-256 + test("PBKDF2-SHA-256", () { + final js = { + "crypto": { + "cipher": "aes-128-ctr", + "cipherparams": {"iv": "6087dab2f9fdbbfaddc31a909735c1e6"}, + "ciphertext": + "5318b4d5bcd28de64ee5559e671353e16f075ecae9f99c7a79a38af5f869aa46", + "kdf": "pbkdf2", + "kdfparams": { + "c": 262144, + "dklen": 32, + "prf": "hmac-sha256", + "salt": + "ae3cd4e7013836a3df6bd7241b12db061dbe2c6785853cce422d148a624ce0bd" + }, + "mac": + "517ead924a9d0dc3124507e3393d175ce3ff7c1e96529c6c555ce9e51205e9b2" + }, + "id": "3198bc9c-6672-5ab3-d995-4942343ae5b6", + "version": 3 + }; + final decode = Web3SecretStorageDefinationV3.decode( + StringUtils.fromJson(js), "testpassword"); + expect(BytesUtils.toHexString(decode.data), + "7a28b5ba57c53603b0b07b56bba752f7784bf506fa95edc395f5cf6c7514fe9d"); + expect(decode.uuid, "3198bc9c-6672-5ab3-d995-4942343ae5b6"); + final encode = decode.encrypt(); + expect(StringUtils.toJson(encode), js); + }); + + /// https://github.com/ethereum/wiki/wiki/Web3-Secret-Storage-Definition#scrypt + test("Scrypt", () { + final js = { + "crypto": { + "cipher": "aes-128-ctr", + "cipherparams": {"iv": "83dbcc02d8ccb40e466191a123791e0e"}, + "ciphertext": + "d172bf743a674da9cdad04534d56926ef8358534d458fffccd4e6ad2fbde479c", + "kdf": "scrypt", + "kdfparams": { + "dklen": 32, + "n": 262144, + "p": 8, + "r": 1, + "salt": + "ab0c7876052600dd703518d6fc3fe8984592145b591fc8fb5c6d43190334ba19" + }, + "mac": + "2103ac29920d71da29f15d75b4a16dbe95cfd7ff8faea1056c33131d846e3097" + }, + "id": "3198bc9c-6672-5ab3-d995-4942343ae5b6", + "version": 3 + }; + final decode = Web3SecretStorageDefinationV3.decode( + StringUtils.fromJson(js), "testpassword"); + expect(BytesUtils.toHexString(decode.data), + "7a28b5ba57c53603b0b07b56bba752f7784bf506fa95edc395f5cf6c7514fe9d"); + expect(decode.uuid, "3198bc9c-6672-5ab3-d995-4942343ae5b6"); + final encode = decode.encrypt(); + expect(StringUtils.toJson(encode), js); + }); + test("secret storage", () { // Repeat the following test 100 times - for (int i = 0; i < 5; i++) { + for (int i = 0; i < 2; i++) { // Generate a random password of length 32 final password = QuickCrypto.generateRandom(32).toHex(); final message = QuickCrypto.generateRandom(64); // Encode the mnemonic with the password and additional parameters - final secureStorage = - SecretWallet.encode(message, password, p: 1, scryptN: 8192); + final secureStorage = Web3SecretStorageDefinationV3.encode( + message, password, + p: 1, scryptN: 8192); // Decode the encoded secure storage using the password - final decodeWallet = SecretWallet.decode( + final decodeWallet = Web3SecretStorageDefinationV3.decode( secureStorage.encrypt(encoding: SecretWalletEncoding.base64), password, encoding: SecretWalletEncoding.base64); - // Verify that the credentials in the secure storage match the decoded credentials - expect(bytesEqual(secureStorage.data, decodeWallet.data), true); - expect(bytesEqual(decodeWallet.data, message), true); + expect( + BytesUtils.bytesEqual(secureStorage.data, decodeWallet.data), true); + expect(BytesUtils.bytesEqual(decodeWallet.data, message), true); } // Repeat the following test 100 times - for (int i = 0; i < 5; i++) { + for (int i = 0; i < 2; i++) { // Generate a random password of length 32 final password = QuickCrypto.generateRandom(32).toHex(); final message = QuickCrypto.generateRandom(64); // Encode the mnemonic with the password and additional parameters - final secureStorage = - SecretWallet.encode(message, password, p: 1, scryptN: 8192); + final secureStorage = Web3SecretStorageDefinationV3.encode( + message, password, + p: 1, scryptN: 8192); // Decode the encoded secure storage using the password - final decodeWallet = SecretWallet.decode( + final decodeWallet = Web3SecretStorageDefinationV3.decode( secureStorage.encrypt(encoding: SecretWalletEncoding.json), password, encoding: SecretWalletEncoding.json); // Verify that the credentials in the secure storage match the decoded credentials - expect(bytesEqual(secureStorage.data, decodeWallet.data), true); - expect(bytesEqual(decodeWallet.data, message), true); + expect( + BytesUtils.bytesEqual(secureStorage.data, decodeWallet.data), true); + expect(BytesUtils.bytesEqual(decodeWallet.data, message), true); + } + for (int i = 0; i < 2; i++) { + // Generate a random password of length 32 + final password = QuickCrypto.generateRandom(32).toHex(); + final message = QuickCrypto.generateRandom(64); + + // Encode the mnemonic with the password and additional parameters + final secureStorage = Web3SecretStorageDefinationV3.encode( + message, password, + p: 1, scryptN: 8192); + + // Decode the encoded secure storage using the password + final decodeWallet = Web3SecretStorageDefinationV3.decode( + secureStorage.encrypt(encoding: SecretWalletEncoding.cbor), password, + encoding: SecretWalletEncoding.cbor); + + // Verify that the credentials in the secure storage match the decoded credentials + expect( + BytesUtils.bytesEqual(secureStorage.data, decodeWallet.data), true); + expect(BytesUtils.bytesEqual(decodeWallet.data, message), true); } }); } diff --git a/test/signer/ethereum_test.dart b/test/signer/ethereum_test.dart index 48a3ed5..3710715 100644 --- a/test/signer/ethereum_test.dart +++ b/test/signer/ethereum_test.dart @@ -14,7 +14,7 @@ void main() { expect(verify, true); final publicKey = ETHVerifier.getPublicKey(message, sign); expect( - bytesEqual(publicKey?.toBytes(), + BytesUtils.bytesEqual(publicKey?.toBytes(), signer.toVerifyKey().edsaVerifyKey.publicKey.toBytes()), true); }); diff --git a/test/signer/tron_test.dart b/test/signer/tron_test.dart index 584b12a..d7ed79c 100644 --- a/test/signer/tron_test.dart +++ b/test/signer/tron_test.dart @@ -15,7 +15,7 @@ void main() { expect(verify, true); final publicKey = TronVerifier.getPublicKey(message, sign); expect( - bytesEqual(publicKey?.toBytes(), + BytesUtils.bytesEqual(publicKey?.toBytes(), signer.toVerifyKey().edsaVerifyKey.publicKey.toBytes()), true); }); diff --git a/test/ss58/ss58_test.dart b/test/ss58/ss58_test.dart index c18fcc0..82b7d9a 100644 --- a/test/ss58/ss58_test.dart +++ b/test/ss58/ss58_test.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/ss58/ss58_base.dart'; import 'package:test/test.dart'; diff --git a/test/substrate/substrate_test.dart b/test/substrate/substrate_test.dart index 32baf55..f759249 100644 --- a/test/substrate/substrate_test.dart +++ b/test/substrate/substrate_test.dart @@ -2,8 +2,7 @@ import 'package:blockchain_utils/bip/ecc/keys/sr25519_keys.dart'; import 'package:blockchain_utils/bip/substrate/conf/substrate_coins.dart'; import 'package:blockchain_utils/bip/substrate/substrate_base.dart'; import 'package:blockchain_utils/bip/substrate/substrate_path.dart'; -import 'package:blockchain_utils/compare/compare.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import '../quick_hex.dart'; @@ -36,7 +35,7 @@ void main() { final secret = (w.priveKey.privKey as Sr25519PrivateKey).secretKey; final testPrive = BytesUtils.fromHexString(childInfo["private_key"]).sublist(0, 32); - expect(bytesEqual(testPrive, secret.key()), true); + expect(BytesUtils.bytesEqual(testPrive, secret.key()), true); } } } @@ -69,7 +68,7 @@ void main() { final secret = (w.priveKey.privKey as Sr25519PrivateKey).secretKey; final testPrive = BytesUtils.fromHexString(childInfo["private_key"]).sublist(0, 32); - expect(bytesEqual(testPrive, secret.key()), true); + expect(BytesUtils.bytesEqual(testPrive, secret.key()), true); } } } diff --git a/test/ton/mnemonic_test.dart b/test/ton/mnemonic_test.dart new file mode 100644 index 0000000..614c363 --- /dev/null +++ b/test/ton/mnemonic_test.dart @@ -0,0 +1,122 @@ +import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:test/test.dart'; + +void main() { + group("Ton Mnemonic", _test); +} + +void _test() { + test("mnemonic seed generator", () { + final mnemonic = [ + "current", + "phrase", + "now", + "sea", + "verify", + "chapter", + "rain", + "below", + "office", + "voice", + "trade", + "share", + "inject", + "impulse", + "empower", + "bitter", + "fee", + "half", + "excess", + "oval", + "genuine", + "happy", + "wrong", + "trust" + ]; + final seed = + TonSeedGenerator(Mnemonic.fromList(mnemonic)).generate(password: ""); + final privateKey = Ed25519PrivateKey.fromBytes( + seed.sublist(0, Ed25519KeysConst.privKeyByteLen)); + expect(privateKey.publicKey.toHex(withPrefix: false), + "cd1fea46e4a59115211ed483161bb315a8e0028ae190b24c1838351dc0bdf040"); + }); + + test("mnemonic seed generator_2", () { + final mnemonic = [ + "smoke", + "area", + "audit", + "artist", + "tennis", + "owner", + "salute", + "donate", + "hole", + "victory", + "such", + "boost", + "ahead", + "jeans", + "protect", + "decade", + "report", + "float", + "rather", + "sheriff", + "salad", + "supreme", + "acquire", + "bulb" + ]; + final seed = + TonSeedGenerator(Mnemonic.fromList(mnemonic)).generate(password: ""); + final privateKey = Ed25519PrivateKey.fromBytes( + seed.sublist(0, Ed25519KeysConst.privKeyByteLen)); + expect(privateKey.toHex(), + "ab460eb3462747a1e57e75e2c6a3afab420a7a297f53d5258b9b7fe25113cebe"); + }); + + test("mnemonic with password", () { + final mnemonic = [ + "woman", + "harvest", + "crawl", + "blind", + "piece", + "portion", + "draft", + "write", + "win", + "coil", + "lawsuit", + "illegal" + ]; + final seed = TonSeedGenerator(Mnemonic.fromList(mnemonic)) + .generate(password: "MRTNETWORK"); + final privateKey = Ed25519PrivateKey.fromBytes( + seed.sublist(0, Ed25519KeysConst.privKeyByteLen)); + expect(privateKey.toHex(), + "b91ad008bdf851289acaa77401612674ea3906eba0ca044374ff38f2a170ba85"); + }); + test("validate mnemonic", () { + final mnemonic = [ + "woman", + "harvest", + "crawl", + "blind", + "piece", + "portion", + "draft", + "write", + "win", + "coil", + "lawsuit", + "illegal" + ]; + final validator = TomMnemonicValidator(); + expect(validator.isValid(Mnemonic.fromList(mnemonic)), false); + expect( + validator.isValid(Mnemonic.fromList(mnemonic), password: "MRTNETWORK"), + true); + }); +} diff --git a/test/wasam.dart b/test/wasam.dart new file mode 100644 index 0000000..ea35703 --- /dev/null +++ b/test/wasam.dart @@ -0,0 +1,3 @@ +void test() {} + +void main(List args) {} diff --git a/test/wasam.mjs b/test/wasam.mjs new file mode 100644 index 0000000..6c70e55 --- /dev/null +++ b/test/wasam.mjs @@ -0,0 +1,229 @@ +let buildArgsList; + +// `modulePromise` is a promise to the `WebAssembly.module` object to be +// instantiated. +// `importObjectPromise` is a promise to an object that contains any additional +// imports needed by the module that aren't provided by the standard runtime. +// The fields on this object will be merged into the importObject with which +// the module will be instantiated. +// This function returns a promise to the instantiated module. +export const instantiate = async (modulePromise, importObjectPromise) => { + let dartInstance; + + function stringFromDartString(string) { + const totalLength = dartInstance.exports.$stringLength(string); + let result = ''; + let index = 0; + while (index < totalLength) { + let chunkLength = Math.min(totalLength - index, 0xFFFF); + const array = new Array(chunkLength); + for (let i = 0; i < chunkLength; i++) { + array[i] = dartInstance.exports.$stringRead(string, index++); + } + result += String.fromCharCode(...array); + } + return result; + } + + function stringToDartString(string) { + const length = string.length; + let range = 0; + for (let i = 0; i < length; i++) { + range |= string.codePointAt(i); + } + if (range < 256) { + const dartString = dartInstance.exports.$stringAllocate1(length); + for (let i = 0; i < length; i++) { + dartInstance.exports.$stringWrite1(dartString, i, string.codePointAt(i)); + } + return dartString; + } else { + const dartString = dartInstance.exports.$stringAllocate2(length); + for (let i = 0; i < length; i++) { + dartInstance.exports.$stringWrite2(dartString, i, string.charCodeAt(i)); + } + return dartString; + } + } + + // Prints to the console + function printToConsole(value) { + if (typeof dartPrint == "function") { + dartPrint(value); + return; + } + if (typeof console == "object" && typeof console.log != "undefined") { + console.log(value); + return; + } + if (typeof print == "function") { + print(value); + return; + } + + throw "Unable to print message: " + js; + } + + // Converts a Dart List to a JS array. Any Dart objects will be converted, but + // this will be cheap for JSValues. + function arrayFromDartList(constructor, list) { + const length = dartInstance.exports.$listLength(list); + const array = new constructor(length); + for (let i = 0; i < length; i++) { + array[i] = dartInstance.exports.$listRead(list, i); + } + return array; + } + + buildArgsList = function(list) { + const dartList = dartInstance.exports.$makeStringList(); + for (let i = 0; i < list.length; i++) { + dartInstance.exports.$listAdd(dartList, stringToDartString(list[i])); + } + return dartList; + } + + // A special symbol attached to functions that wrap Dart functions. + const jsWrappedDartFunctionSymbol = Symbol("JSWrappedDartFunction"); + + function finalizeWrapper(dartFunction, wrapped) { + wrapped.dartFunction = dartFunction; + wrapped[jsWrappedDartFunctionSymbol] = true; + return wrapped; + } + + // Imports + const dart2wasm = { + +_48: v => stringToDartString(v.toString()), +_63: () => { + let stackString = new Error().stack.toString(); + let frames = stackString.split('\n'); + let drop = 2; + if (frames[0] === 'Error') { + drop += 1; + } + return frames.slice(drop).join('\n'); + }, +_72: s => stringToDartString(JSON.stringify(stringFromDartString(s))), +_73: s => printToConsole(stringFromDartString(s)), +_91: (c) => + queueMicrotask(() => dartInstance.exports.$invokeCallback(c)), +_93: (a, i) => a.push(i), +_104: a => a.length, +_106: (a, i) => a[i], +_107: (a, i, v) => a[i] = v, +_109: a => a.join(''), +_119: (s, p, i) => s.indexOf(p, i), +_122: (o, start, length) => new Uint8Array(o.buffer, o.byteOffset + start, length), +_123: (o, start, length) => new Int8Array(o.buffer, o.byteOffset + start, length), +_124: (o, start, length) => new Uint8ClampedArray(o.buffer, o.byteOffset + start, length), +_125: (o, start, length) => new Uint16Array(o.buffer, o.byteOffset + start, length), +_126: (o, start, length) => new Int16Array(o.buffer, o.byteOffset + start, length), +_127: (o, start, length) => new Uint32Array(o.buffer, o.byteOffset + start, length), +_128: (o, start, length) => new Int32Array(o.buffer, o.byteOffset + start, length), +_131: (o, start, length) => new Float32Array(o.buffer, o.byteOffset + start, length), +_132: (o, start, length) => new Float64Array(o.buffer, o.byteOffset + start, length), +_136: (o) => new DataView(o.buffer, o.byteOffset, o.byteLength), +_140: Function.prototype.call.bind(Object.getOwnPropertyDescriptor(DataView.prototype, 'byteLength').get), +_141: (b, o) => new DataView(b, o), +_143: Function.prototype.call.bind(DataView.prototype.getUint8), +_145: Function.prototype.call.bind(DataView.prototype.getInt8), +_147: Function.prototype.call.bind(DataView.prototype.getUint16), +_149: Function.prototype.call.bind(DataView.prototype.getInt16), +_151: Function.prototype.call.bind(DataView.prototype.getUint32), +_153: Function.prototype.call.bind(DataView.prototype.getInt32), +_159: Function.prototype.call.bind(DataView.prototype.getFloat32), +_161: Function.prototype.call.bind(DataView.prototype.getFloat64), +_182: o => o === undefined, +_183: o => typeof o === 'boolean', +_184: o => typeof o === 'number', +_186: o => typeof o === 'string', +_189: o => o instanceof Int8Array, +_190: o => o instanceof Uint8Array, +_191: o => o instanceof Uint8ClampedArray, +_192: o => o instanceof Int16Array, +_193: o => o instanceof Uint16Array, +_194: o => o instanceof Int32Array, +_195: o => o instanceof Uint32Array, +_196: o => o instanceof Float32Array, +_197: o => o instanceof Float64Array, +_198: o => o instanceof ArrayBuffer, +_199: o => o instanceof DataView, +_200: o => o instanceof Array, +_201: o => typeof o === 'function' && o[jsWrappedDartFunctionSymbol] === true, +_205: (l, r) => l === r, +_206: o => o, +_207: o => o, +_208: o => o, +_209: b => !!b, +_210: o => o.length, +_213: (o, i) => o[i], +_214: f => f.dartFunction, +_215: l => arrayFromDartList(Int8Array, l), +_216: l => arrayFromDartList(Uint8Array, l), +_217: l => arrayFromDartList(Uint8ClampedArray, l), +_218: l => arrayFromDartList(Int16Array, l), +_219: l => arrayFromDartList(Uint16Array, l), +_220: l => arrayFromDartList(Int32Array, l), +_221: l => arrayFromDartList(Uint32Array, l), +_222: l => arrayFromDartList(Float32Array, l), +_223: l => arrayFromDartList(Float64Array, l), +_224: (data, length) => { + const view = new DataView(new ArrayBuffer(length)); + for (let i = 0; i < length; i++) { + view.setUint8(i, dartInstance.exports.$byteDataGetUint8(data, i)); + } + return view; + }, +_225: l => arrayFromDartList(Array, l), +_226: stringFromDartString, +_227: stringToDartString, +_230: l => new Array(l), +_234: (o, p) => o[p], +_238: o => String(o) + }; + + const baseImports = { + dart2wasm: dart2wasm, + + + Math: Math, + Date: Date, + Object: Object, + Array: Array, + Reflect: Reflect, + }; + + const jsStringPolyfill = { + "charCodeAt": (s, i) => s.charCodeAt(i), + "compare": (s1, s2) => { + if (s1 < s2) return -1; + if (s1 > s2) return 1; + return 0; + }, + "concat": (s1, s2) => s1 + s2, + "equals": (s1, s2) => s1 === s2, + "fromCharCode": (i) => String.fromCharCode(i), + "length": (s) => s.length, + "substring": (s, a, b) => s.substring(a, b), + }; + + dartInstance = await WebAssembly.instantiate(await modulePromise, { + ...baseImports, + ...(await importObjectPromise), + "wasm:js-string": jsStringPolyfill, + }); + + return dartInstance; +} + +// Call the main function for the instantiated module +// `moduleInstance` is the instantiated dart2wasm module +// `args` are any arguments that should be passed into the main function. +export const invoke = (moduleInstance, ...args) => { + const dartMain = moduleInstance.exports.$getMain(); + const dartArgs = buildArgsList(args); + moduleInstance.exports.$invokeMain(dartMain, dartArgs); +} + diff --git a/test/wasam.unopt.wasm b/test/wasam.unopt.wasm new file mode 100644 index 0000000..3d031e2 Binary files /dev/null and b/test/wasam.unopt.wasm differ diff --git a/test/wasam.wasm b/test/wasam.wasm new file mode 100644 index 0000000..3b1b110 Binary files /dev/null and b/test/wasam.wasm differ diff --git a/test/wif/wif_test.dart b/test/wif/wif_test.dart index 4957432..2014f68 100644 --- a/test/wif/wif_test.dart +++ b/test/wif/wif_test.dart @@ -3,7 +3,7 @@ import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:blockchain_utils/bip/coin_conf/coins_conf.dart'; import 'package:blockchain_utils/bip/wif/wif.dart'; -import 'package:blockchain_utils/binary/utils.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/exception/exception.dart'; import 'package:test/test.dart';