diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ac5a7b..0f3fe1f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,8 @@ +## 4.0.0 + +- Minimum required Dart SDK version updated to 3.3. +- Ensure compatibility with the latest Dart features and improvements. + ## 3.5.0 - Implemented Monero cryptographic operations. diff --git a/example/lib/main.dart b/example/lib/main.dart index ab73b3a..82d9d4f 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -1 +1,43 @@ -void main() {} +// ignore_for_file: unused_local_variable + +import 'package:blockchain_utils/blockchain_utils.dart'; + +void main() { + const String passphrase = 'MRTNETWORK'; + final mnemonic = Bip39MnemonicGenerator(Bip39Languages.japanese) + .fromWordsNumber(Bip39WordsNum.wordsNum24); + final seed = Bip39SeedGenerator(mnemonic).generate(passphrase); + final ethereumWallet = Bip44.fromSeed(seed, Bip44Coins.ethereum); + final defaultEthereumWallet = ethereumWallet.deriveDefaultPath; + final ethereumaddress = defaultEthereumWallet.publicKey.toAddress; + + final tronmWallet = Bip44.fromSeed(seed, Bip44Coins.tron); + final defaultTronWallet = ethereumWallet.deriveDefaultPath; + final tronaddress = defaultEthereumWallet.publicKey.toAddress; + + Bip49.fromSeed(seed, Bip49Coins.litecoin); + Bip84.fromSeed(seed, Bip84Coins.bitcoin); + Bip86.fromSeed(seed, Bip86Coins.bitcoin); + + final bitconWallet = Bip44.fromSeed(seed, Bip44Coins.tron); + final defaultBitcoinWallet = ethereumWallet.deriveDefaultPath; + final bitconP2pkh = defaultEthereumWallet.publicKey.toAddress; + + final cardano = CardanoIcarusSeedGenerator(mnemonic.toStr()); + + final substrate = Substrate.fromSeed( + List.filled(32, 1), SubstrateCoins.polkadotSr25519); + final substrateAddress = substrate.publicKey.toAddress; + + final moneromnemonic = + MoneroMnemonicGenerator().fromWordsNumber(MoneroWordsNum.wordsNum25); + final moneroSeed = MoneroSeedGenerator(moneromnemonic).generate(); + final monero = MoneroAccount.fromSeed(moneroSeed); + final moneroAddress = monero.primaryAddress; + final subAddress = monero.subaddress(1, majorIndex: 0); + + final slip10Ed = Bip32Slip10Ed25519.fromSeed(List.filled(32, 1)); + final edWallet = slip10Ed.derivePath("44'/0'/0'"); + final slipScp = Bip32Slip10Secp256k1.fromSeed(List.filled(32, 1)); + final ecWallet = slipScp.derivePath("44'/0'/0'/1/2"); +} diff --git a/example/pubspec.lock b/example/pubspec.lock index f366471..0373eac 100644 --- a/example/pubspec.lock +++ b/example/pubspec.lock @@ -5,23 +5,23 @@ packages: dependency: transitive description: name: _fe_analyzer_shared - sha256: f256b0c0ba6c7577c15e2e4e114755640a875e885099367bf6e012b19314c834 + sha256: "16e298750b6d0af7ce8a3ba7c18c69c3785d11b15ec83f6dcd0ad2a0009b3cab" url: "https://pub.dev" source: hosted - version: "72.0.0" + version: "76.0.0" _macros: dependency: transitive description: dart source: sdk - version: "0.3.2" + version: "0.3.3" analyzer: dependency: transitive description: name: analyzer - sha256: b652861553cd3990d8ed361f7979dc6d7053a9ac8843fa73820ab68ce5410139 + sha256: "1f14db053a8c23e260789e9b0980fa27f2680dd640932cae5e1137cce0e46e1e" url: "https://pub.dev" source: hosted - version: "6.7.0" + version: "6.11.0" args: dependency: transitive description: @@ -44,7 +44,7 @@ packages: path: ".." relative: true source: path - version: "3.5.0" + version: "4.0.0" boolean_selector: dependency: transitive description: @@ -65,10 +65,10 @@ packages: dependency: transitive description: name: collection - sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a + sha256: a1ace0a119f20aabc852d165077c036cd864315bd99b7eaa10a60100341941bf url: "https://pub.dev" source: hosted - version: "1.18.0" + version: "1.19.0" convert: dependency: transitive description: @@ -190,10 +190,10 @@ packages: dependency: transitive description: name: macros - sha256: "0acaed5d6b7eab89f63350bccd82119e6c602df0f391260d0e32b5e23db79536" + sha256: "1d9e801cd66f7ea3663c45fc708450db1fa57f988142c64289142c9b7ee80656" url: "https://pub.dev" source: hosted - version: "0.1.2-main.4" + version: "0.1.3-main.0" matcher: dependency: transitive description: @@ -302,7 +302,7 @@ packages: dependency: transitive description: flutter source: sdk - version: "0.0.99" + version: "0.0.0" source_map_stack_trace: dependency: transitive description: diff --git a/example/test/test_test.dart b/example/test/test_test.dart index 77c27fe..0f518a2 100644 --- a/example/test/test_test.dart +++ b/example/test/test_test.dart @@ -1,221 +1,46 @@ -// // // ignore_for_file: avoid_print +// ignore_for_file: unused_local_variable -// import 'package:example/test/address/ada_shelly/ada_shelly.dart'; -// import 'package:example/test/address/algo/algo.dart'; -// import 'package:example/test/address/aptos/aptos.dart'; -// import 'package:example/test/address/atom/atom.dart'; -// import 'package:example/test/address/avax/avax.dart'; -// import 'package:example/test/address/bch_p2pkh/bch_p2pkh.dart'; -// import 'package:example/test/address/bch_p2sh/bch_p2sh.dart'; -// import 'package:example/test/address/egld/egld.dart'; -// import 'package:example/test/address/eos/eos.dart'; -// import 'package:example/test/address/ergo/ergo.dart'; -// import 'package:example/test/address/eth/eth.dart'; -// import 'package:example/test/address/fil/fil.dart'; -// import 'package:example/test/address/icx/icx.dart'; -// import 'package:example/test/address/inj/inj.dart'; -// import 'package:example/test/address/nano/nano.dart'; -// import 'package:example/test/address/near/near.dart'; -// import 'package:example/test/address/neo/neo.dart'; -// import 'package:example/test/address/okex/okex.dart'; -// import 'package:example/test/address/one/one.dart'; -// import 'package:example/test/address/p2pkh/p2pkh.dart'; -// import 'package:example/test/address/p2sh/p2sh.dart'; -// import 'package:example/test/address/p2tr/p2tr.dart'; -// import 'package:example/test/address/p2wpkh/p2wpkh.dart'; -// import 'package:example/test/address/sol/sol.dart'; -// import 'package:example/test/address/substrate/substrate.dart'; -// import 'package:example/test/address/trx/trx.dart'; -// import 'package:example/test/address/xlm/xml.dart'; -// import 'package:example/test/address/xmr/xmr.dart'; -// import 'package:example/test/address/xrp/xrp.dart'; -// import 'package:example/test/address/xtz/xtz.dart'; -// import 'package:example/test/address/zil/zil.dart'; -// import 'package:example/test/algorand/mnemonic.dart'; -// import 'package:example/test/base58/base58.dart'; -// import 'package:example/test/base58/base58_xmr.dart'; -// import 'package:example/test/bech32/bch_bech32.dart'; -// import 'package:example/test/bech32/bech32.dart'; -// import 'package:example/test/bech32/segwit_bech32.dart'; -// import 'package:example/test/bip/bip32/ed25519/ed25519.dart'; -// import 'package:example/test/bip/bip32/ed25519_blake2b/ed25519_blake2b.dart'; -// import 'package:example/test/bip/bip32/ed25519_khalow/ed25519_khalow.dart'; -// import 'package:example/test/bip/bip32/nist256p1/nist256p1.dart'; -// import 'package:example/test/bip/bip32/secp256k1/secp256k1.dart'; -// import 'package:example/test/bip/bip38/bip38_addr.dart'; -// import 'package:example/test/bip/bip38/bip38_ec.dart'; -// import 'package:example/test/bip/bip38/bip38_no_ec.dart'; -// import 'package:example/test/bip/bip39/bip39.dart'; -// import 'package:example/test/bip/bip44/bip44.dart'; -// import 'package:example/test/bip/bip49/bip49.dart'; -// import 'package:example/test/bip/bip84/bip84.dart'; -// import 'package:example/test/bip/bip86/bip86.dart'; -// import 'package:example/test/cardano/bip32/icarus.dart'; -// import 'package:example/test/cardano/bip32/legacy.dart'; -// import 'package:example/test/cardano/byron/byron_lagacy.dart'; -// import 'package:example/test/cardano/cip1852/cip1852.dart'; -// import 'package:example/test/cardano/mnemonic/mnemonic.dart'; -// import 'package:example/test/cardano/shelly/shelly.dart'; -// import 'package:example/test/cbor.dart'; -// import 'package:example/test/crypto/aes/aes_ctr.dart'; -// import 'package:example/test/crypto/blake2b/blake2b.dart'; -// import 'package:example/test/crypto/chacha20_poly1305/chacha20_poly1305.dart'; -// import 'package:example/test/crypto/crc32/crc32.dart'; -// import 'package:example/test/crypto/hmac/hmac.dart'; -// import 'package:example/test/crypto/keccack/keccack.dart'; -// import 'package:example/test/crypto/md4/md4.dart'; -// import 'package:example/test/crypto/md5/md5.dart'; -// import 'package:example/test/crypto/pbkdf2/pbkdf2.dart'; -// import 'package:example/test/crypto/ripemd/ripemd.dart'; -// import 'package:example/test/crypto/scrypt/scrypt.dart'; -// import 'package:example/test/crypto/sha1/sha1.dart'; -// import 'package:example/test/crypto/sha256/sha256.dart'; -// import 'package:example/test/crypto/sha3/sha3.dart'; -// import 'package:example/test/crypto/sha512/sha512.dart'; -// import 'package:example/test/crypto/sha512_256/sha512_256.dart'; -// import 'package:example/test/crypto/shake/shake.dart'; -// import 'package:example/test/crypto/x_modem_crc/x_modem_crc.dart'; -// import 'package:example/test/ecdsa/ed.dart'; -// import 'package:example/test/ecdsa/projective.dart'; -// import 'package:example/test/elctrum/mnemonic/mnemonic.dart'; -// import 'package:example/test/elctrum/v1/v1.dart'; -// import 'package:example/test/elctrum/v2/v2.dart'; -// import 'package:example/test/monero/mnemonic/monero_mnemonic.dart'; -// import 'package:example/test/monero/monero.dart'; -// import 'package:example/test/schnorrkel/derive.dart'; -// import 'package:example/test/schnorrkel/schnorrkel_key.dart'; -// import 'package:example/test/schnorrkel/sign.dart'; -// import 'package:example/test/schnorrkel/vrf.dart'; -// import 'package:example/test/secure_storage.dart'; -// import 'package:example/test/ss58/ss58.dart'; -// import 'package:example/test/substrate/scale.dart'; -// import 'package:example/test/substrate/substrate.dart'; -// import 'package:example/test/uuid.dart'; -// import 'package:example/test/wif/wif.dart'; -// import 'package:flutter/foundation.dart'; +import 'package:blockchain_utils/blockchain_utils.dart'; -// void main() { -// _testAll(); -// } +void main() { + const String passphrase = 'MRTNETWORK'; + final mnemonic = Bip39MnemonicGenerator(Bip39Languages.japanese) + .fromWordsNumber(Bip39WordsNum.wordsNum24); + final seed = Bip39SeedGenerator(mnemonic).generate(passphrase); + final ethereumWallet = Bip44.fromSeed(seed, Bip44Coins.ethereum); + final defaultEthereumWallet = ethereumWallet.deriveDefaultPath; + final ethereumaddress = defaultEthereumWallet.publicKey.toAddress; -// typedef TestMethod = void Function(); + final tronmWallet = Bip44.fromSeed(seed, Bip44Coins.tron); + final defaultTronWallet = ethereumWallet.deriveDefaultPath; + final tronaddress = defaultEthereumWallet.publicKey.toAddress; -// /// its very slow in web debugging -// /// if you want to test this method on the web should remove the condition -// void _web() { -// if (kIsWeb) return; -// _test("bip38 No Ecdsa", bip38NoEcdsaTest); -// _test("bip38 ECDSA", bip38ECDSATest); -// _test("scrypt", testScrypt); -// _test("pbkdf2", pbkdf2Test); -// _test("secure storage", testSecureStorage); -// } + Bip49.fromSeed(seed, Bip49Coins.litecoin); + Bip84.fromSeed(seed, Bip84Coins.bitcoin); + Bip86.fromSeed(seed, Bip86Coins.bitcoin); -// void _test(String name, TestMethod process) { -// try { -// process(); -// print("success $name"); -// } catch (e) { -// print("failed $name $e"); -// throw Exception(); -// } -// } + final bitconWallet = Bip44.fromSeed(seed, Bip44Coins.tron); + final defaultBitcoinWallet = ethereumWallet.deriveDefaultPath; + final bitconP2pkh = defaultEthereumWallet.publicKey.toAddress; -// void _testAll() async { -// final DateTime start = DateTime.now(); -// _encodeDecodeAddrTest(); -// _test("UUID", testUUID); -// _test("bech32", bech32Test); -// _test("wif", wifTest); -// _test("substrate scale", substrateScaleTest); -// _test("ss58", ss58Test); -// _test("bip38 ", bip38Test); -// _test("segwit Bech32 ", segwitBech32Test); -// _test("bch bech32", bchBech32Test); -// _test("base58 xmr", testBase58XMR); -// _test("base58", testBase58); -// _test("bip49", bip49Test); -// _test("bip44", bip44Test); -// _test("algorandMnemonic and derive address", algorandMnemonicAndAddressTest); -// _test("substrate derive", substrateDeriveTest); -// _test("monero mnemonic", moneroMnemonucTest); -// _test("monero", moneroTest); -// _test("electrum v2", electrumV2Test); -// _test("electrum v1", electrumV1Test); -// _test("electrum mnemonic", electrumMnemonicTest); -// _test("cardano shelly", cardanoShellyTest); -// _test("cardano mnemonic", cardanoMnemonicTest); -// _test("cardano cip1852", cip1852Test); -// _test("byron legacy", byronLegacyTest); -// _test("cardano icarus", cardanoIcarusTest); -// _test("cardano legacy", cardanoLegacyTest); -// _test("bip86", bip86Test); -// _test("bip84", bip84Test); -// _test("bip39", testBip39); -// _test("secp256k1", secpTest); -// _test("nist", nistTest); -// _test("ed25519-blake2b", edBlake2bTest); -// _test("ed25519-khalow", edKhalowTest); -// _test("ed25519", edTest); -// _test("schnorr", schnoorTestDerive); -// _test("vrf sigh", vrfSignTest); -// _test("schnorrkel keys", schnoorKeyTest); -// _test("schnorrkel-sign", testSchnoor); -// _test("ecdsa", testECDSA); -// _test("eddsa", testEDDSa); -// _test("sha1", testSha1); -// _test("ripemd", testRipemd); -// _test("md5", md5Test); -// _test("md4", md4Test); -// _test("keccack", testKecc); -// _test("hmac", testHmac); -// _test("crc", crcTest); -// _test("chacha-poly1305", chachaTest); -// _test("aes", testAes); -// _test("blake2b", blake2bTest); -// _test("sha256", testSha256); -// _test("sha512", testSha512); -// _test("sha3", testSha3); -// _test("sha512/256", testSha512256); -// _test("modemCrc", testModemCrc); -// _test("shake digest", testShakeDigest); -// _test("cbor test", cborTest); -// _web(); -// final DateTime end = DateTime.now(); -// print("end: ${end.difference(start).inMilliseconds}"); -// } + final cardano = CardanoIcarusSeedGenerator(mnemonic.toStr()); -// void _encodeDecodeAddrTest() { -// _test("zil Address", zilAddressTest); -// _test("xtz Address", xtzAddressTest); -// _test("xrp Address", xrpAddressTest); -// _test("xmr Address", xmrAddressTest); -// _test("xlm Address", xlmAddressTest); -// _test("trx Address", trxAddressTest); -// _test("substrate Address", substrateAddressTest); -// _test("sol Address", solAddressTest); -// _test("p2wpkh Address", p2wpkhAddressTest); -// _test("p2tr Address", p2trAddressTest); -// _test("p2sh Address", p2shAddressTest); -// _test("p2pkh Address", p2pkhAddressTest); -// _test("one Address", oneAddressTest); -// _test("okex Address", okexAddressTest); -// _test("neo Address", neoAddressTest); -// _test("near Address", nearAddressTest); -// _test("nano Address", nanoAddressTest); -// _test("injAddressTest", injAddressTest); -// _test("icx Address", icxAddressTest); -// _test("fil Address", filAddressTest); -// _test("ethereum Address", ethereumAddressTest); -// _test("ergo Address", ergoAddressTest); -// _test("eos Address", eosAddrTest); -// _test("egld Address", egldAddrTest); -// _test("bchP2sh Address", bchP2shAddressTest); -// _test("bchP2pkh Address", bchP2pkhTest); -// _test("avax Address", avaxAddrTest); -// _test("atom Address", atomAddressTest); -// _test("aptos Address", aptosAddressTest); -// _test("algo Address", algoAddressTest); -// _test("ada Shelly Address", adaShellyAddrTest); -// } -void main() {} + // final cardano = CardanoShelley.fromCip1852Object(seed, Bip44Coins.tron); + // final defaultBitcoinWallet = ethereumWallet.deriveDefaultPath; + // final bitconP2pkh = defaultEthereumWallet.publicKey.toAddress; + final substrate = Substrate.fromSeed( + List.filled(32, 1), SubstrateCoins.polkadotSr25519); + final substrateAddress = substrate.publicKey.toAddress; + + final moneromnemonic = + MoneroMnemonicGenerator().fromWordsNumber(MoneroWordsNum.wordsNum25); + final moneroSeed = MoneroSeedGenerator(moneromnemonic).generate(); + final monero = MoneroAccount.fromSeed(moneroSeed); + final moneroAddress = monero.primaryAddress; + final subAddress = monero.subaddress(1, majorIndex: 0); + + final slip10Ed = Bip32Slip10Ed25519.fromSeed(List.filled(32, 1)); + final edWallet = slip10Ed.derivePath("44'/0'/0'"); + final slipScp = Bip32Slip10Secp256k1.fromSeed(List.filled(32, 1)); + final ecWallet = slipScp.derivePath("44'/0'/0'"); +} diff --git a/lib/base32/base32.dart b/lib/base32/base32.dart index d8756ee..587b969 100644 --- a/lib/base32/base32.dart +++ b/lib/base32/base32.dart @@ -54,7 +54,7 @@ import 'package:blockchain_utils/helper/helper.dart'; import 'package:blockchain_utils/utils/utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Constants and data structures used for Base32 encoding and decoding. class _Base32Const { @@ -113,7 +113,7 @@ class _Base32Utils { } int shift = 8; int carry = 0; - List decoded = []; + final List decoded = []; base32.split('').forEach((char) { if (char == '=') { return; @@ -182,7 +182,7 @@ class _Base32Utils { /// A utility class for decoding Base32 encoded strings into bytes. class Base32Decoder { - /// Decode the provided Base32 string into a List of bytes. + /// Decode the provided Base32 string into a List of bytes. /// Optionally, you can specify a custom alphabet for decoding. static List decode(String data, [String? customAlphabet]) { try { @@ -198,7 +198,7 @@ class Base32Decoder { /// Decode the Base32 string and obtain the decoded bytes. final decodedBytes = _Base32Utils._b32decode(_Base32Const.alphabet, data); - /// Return the decoded bytes as a List. + /// Return the decoded bytes as a List. return List.from(decodedBytes); } catch (ex) { /// Handle exceptions by throwing an error for invalid Base32 strings. @@ -226,7 +226,7 @@ class Base32Encoder { return encoded; } - /// Encode the provided List of bytes into a Base32 encoded string. + /// Encode the provided List of bytes into a Base32 encoded string. /// Optionally, you can specify a custom alphabet for encoding. static String encodeBytes(List data, [String? customAlphabet]) { data = data.asImmutableBytes; @@ -253,7 +253,7 @@ class Base32Encoder { .replaceAll(_Base32Const.paddingChar, ''); } - /// Encode the provided List of bytes into a Base32 encoded string without padding characters. + /// Encode the provided List of bytes into a Base32 encoded string without padding characters. /// Optionally, you can specify a custom alphabet for encoding. static String encodeNoPaddingBytes(List data, [String? customAlphabet]) { /// Encode the input bytes and then remove any padding characters. diff --git a/lib/base58/base58.dart b/lib/base58/base58.dart index de89119..ec93301 100644 --- a/lib/base58/base58.dart +++ b/lib/base58/base58.dart @@ -1,5 +1,5 @@ /// Library for working with Base58 encoding. -library base58; +library; /// Export statement for the core functionality of Base58 encoding. export 'base58_base.dart'; diff --git a/lib/base58/base58_base.dart b/lib/base58/base58_base.dart index 9a22ebd..1881934 100644 --- a/lib/base58/base58_base.dart +++ b/lib/base58/base58_base.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/base58/base58_ex.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/helper/helper.dart'; import 'package:blockchain_utils/utils/utils.dart'; @@ -27,27 +27,27 @@ class Base58Const { } class Base58Utils { - /// Compute and return the checksum for the provided List [dataBytes]. + /// Compute and return the checksum for the provided List [dataBytes]. /// The checksum is obtained by performing a double SHA-256 hash and extracting /// the first [Base58Const.checksumByteLen] bytes. /// /// Parameters: - /// - dataBytes: The List of data bytes for which the checksum is computed. + /// - dataBytes: The List of data bytes for which the checksum is computed. /// /// Returns: - /// A List containing the computed checksum. + /// A List containing the computed checksum. static List computeChecksum(List dataBytes) { final doubleSha256Digest = QuickCrypto.sha256DoubleHash(dataBytes); return doubleSha256Digest.sublist(0, Base58Const.checksumByteLen); } } -/// A utility class for encoding List data into a Base58 format using a specified alphabet. +/// A utility class for encoding List data into a Base58 format using a specified alphabet. class Base58Encoder { - /// Encodes the provided List [dataBytes] into a Base58 encoded string using the specified [base58alphabets]. + /// Encodes the provided List [dataBytes] into a Base58 encoded string using the specified [base58alphabets]. /// /// Parameters: - /// - dataBytes: The List of data bytes to be encoded. + /// - dataBytes: The List of data bytes to be encoded. /// - base58alphabets: Optional Base58Alphabets enum to choose the alphabet (default is Base58Alphabets.bitcoin). /// /// Returns: @@ -69,7 +69,7 @@ class Base58Encoder { /// Count leading zero bytes in the dataBytes for leading zero characters in the encoded string. int zero = 0; - for (int byte in dataBytes) { + for (final int byte in dataBytes) { if (byte == 0) { zero++; } else { @@ -82,12 +82,12 @@ class Base58Encoder { return (alphabet[0] * leadingZeros) + enc; } - /// Encodes the provided List [dataBytes] with a checksum using a specified Base58 alphabet. + /// Encodes the provided List [dataBytes] with a checksum using a specified Base58 alphabet. /// /// This method appends a checksum to the data and then encodes the result into a Base58 encoded string. /// /// Parameters: - /// - dataBytes: The List of data bytes to be encoded with a checksum. + /// - dataBytes: The List of data bytes to be encoded with a checksum. /// - base58alphabets: Optional Base58Alphabets enum to choose the alphabet (default is Base58Alphabets.bitcoin). /// /// Returns: @@ -101,16 +101,16 @@ class Base58Encoder { } } -/// A utility class for decoding Base58 encoded strings into List data using a specified alphabet. +/// A utility class for decoding Base58 encoded strings into List data using a specified alphabet. class Base58Decoder { - /// Decode the provided Base58 encoded [data] into a List of data bytes using the specified [base58alphabets]. + /// Decode the provided Base58 encoded [data] into a List of data bytes using the specified [base58alphabets]. /// /// Parameters: /// - data: The Base58 encoded string to be decoded. /// - base58alphabets: Optional Base58Alphabets enum to choose the alphabet (default is Base58Alphabets.bitcoin). /// /// Returns: - /// A List containing the decoded data bytes. + /// A List containing the decoded data bytes. static List decode(String data, [Base58Alphabets base58alphabets = Base58Alphabets.bitcoin]) { final alphabet = Base58Const.alphabets[base58alphabets]!; @@ -141,7 +141,7 @@ class Base58Decoder { return List.from([...List.filled(padLen, 0), ...bytes]); } - /// Decode and verify the provided Base58 encoded [data] into a List of data bytes using a specified Base58 alphabet. + /// Decode and verify the provided Base58 encoded [data] into a List of data bytes using a specified Base58 alphabet. /// /// This method verifies the checksum of the decoded data to ensure its integrity. /// @@ -150,7 +150,7 @@ class Base58Decoder { /// - base58alphabets: Optional Base58Alphabets enum to choose the alphabet (default is Base58Alphabets.bitcoin). /// /// Returns: - /// A List containing the decoded data bytes if the checksum is valid. + /// A List containing the decoded data bytes if the checksum is valid. /// /// Throws: /// - Base58ChecksumError: If the checksum verification fails. diff --git a/lib/base58/base58_ex.dart b/lib/base58/base58_ex.dart index 1e4231f..8405725 100644 --- a/lib/base58/base58_ex.dart +++ b/lib/base58/base58_ex.dart @@ -1,8 +1,7 @@ -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// An exception class representing an error related to Base58 checksum validation. class Base58ChecksumError extends BlockchainUtilsException { /// Constructor for creating a Base58ChecksumError with an optional error message. - const Base58ChecksumError(String message, {Map? details}) - : super(message, details: details); + const Base58ChecksumError(super.message, {super.details}); } diff --git a/lib/bech32/bch_bech32.dart b/lib/bech32/bch_bech32.dart index ad8a9a0..c6f2695 100644 --- a/lib/bech32/bch_bech32.dart +++ b/lib/bech32/bch_bech32.dart @@ -58,7 +58,7 @@ import 'package:blockchain_utils/helper/helper.dart'; import 'package:blockchain_utils/utils/utils.dart'; import 'bech32_utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// A utility class containing constants used for Bitcoin Cash (BCH) Bech32 encoding and decoding. class BchBech32Const { @@ -82,12 +82,12 @@ class _BchBech32Utils { // Compute modulus BigInt chk = BigInt.one; - for (int value in values) { - BigInt top = chk >> 35; + for (final int value in values) { + final BigInt top = chk >> 35; final BigInt valueBig = BigInt.from(value); chk = ((chk & BigInt.from(0x07ffffffff)) << 5) ^ valueBig; - for (List i in generator) { + for (final List i in generator) { if ((top & i[0]) != BigInt.zero) { chk ^= i[1]; } @@ -98,7 +98,7 @@ class _BchBech32Utils { } static List hrpExpand(String hrp) { - List expandedHrp = hrp.runes.map((int rune) { + final List expandedHrp = hrp.runes.map((int rune) { return rune & 0x1f; }).toList(); expandedHrp.add(0); @@ -106,8 +106,8 @@ class _BchBech32Utils { } static List computeChecksum(String hrp, List data) { - List values = hrpExpand(hrp) + data; - BigInt polymod = polyMod(values + [0, 0, 0, 0, 0, 0, 0, 0]); + final List values = hrpExpand(hrp) + data; + final BigInt polymod = polyMod(values + [0, 0, 0, 0, 0, 0, 0, 0]); return List.generate( BchBech32Const.checksumStrLen, (i) => ((polymod >> (5 * (7 - i))) & _mask5).toInt(), @@ -124,8 +124,8 @@ class _BchBech32Utils { /// /// Parameters: /// - hrp: The Human-Readable Part (HRP) of the BCH address. -/// - netVar: A List representing the network version bytes. -/// - data: A List containing the data to be encoded. +/// - netVar: A List representing the network version bytes. +/// - data: A List containing the data to be encoded. /// /// Returns: /// A Bech32 encoded BCH address string. diff --git a/lib/bech32/bech32.dart b/lib/bech32/bech32.dart index b745c42..10751cc 100644 --- a/lib/bech32/bech32.dart +++ b/lib/bech32/bech32.dart @@ -1,5 +1,5 @@ /// Library for working with Bech32 encoding. -library bech32; +library; /// Export statement for the core Bech32 functionality. export 'bech32_base.dart'; diff --git a/lib/bech32/bech32_base.dart b/lib/bech32/bech32_base.dart index 4eec23a..d4913b9 100644 --- a/lib/bech32/bech32_base.dart +++ b/lib/bech32/bech32_base.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/utils/utils.dart'; import 'bech32_utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// An enumeration representing different Bech32 encodings. enum Bech32Encodings { @@ -141,7 +141,9 @@ class Bech32Decoder extends Bech32DecoderBase { Bech32Const.separator, Bech32Const.checksumStrLen, Bech32Utils.verifyChecksum); + final result = Bech32BaseUtils.convertFromBase32(decode.item2); + return Tuple(decode.item1, result); } } diff --git a/lib/bech32/bech32_ex.dart b/lib/bech32/bech32_ex.dart index 766f0fc..06e2578 100644 --- a/lib/bech32/bech32_ex.dart +++ b/lib/bech32/bech32_ex.dart @@ -1,8 +1,7 @@ -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// An exception class representing errors related to Bech32 checksum validation. class Bech32ChecksumError extends BlockchainUtilsException { /// The error message associated with this checksum error. - const Bech32ChecksumError(String message, {Map? details}) - : super(message, details: details); + const Bech32ChecksumError(super.message, {super.details}); } diff --git a/lib/bech32/bech32_utils.dart b/lib/bech32/bech32_utils.dart index a7df342..a008fd2 100644 --- a/lib/bech32/bech32_utils.dart +++ b/lib/bech32/bech32_utils.dart @@ -53,7 +53,7 @@ */ import 'package:blockchain_utils/bech32/bech32_ex.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/utils/utils.dart'; /// A utility class containing constants for Bech32 encoding and decoding. @@ -70,12 +70,12 @@ class Bech32BaseUtils { /// - data: The input data to be converted to base32. /// /// Returns: - /// A List containing the data in base32 encoding. + /// A List containing the data in base32 encoding. /// /// Throws: /// - ArgumentException: If the data cannot be converted to base32. static List convertToBase32(List data) { - List? convData = _convertBits(data, 8, 5); + final List? convData = _convertBits(data, 8, 5); if (convData == null) { throw const ArgumentException( 'Invalid data, cannot perform conversion to base32'); @@ -90,12 +90,12 @@ class Bech32BaseUtils { /// - data: A List of integers representing the data in base32 encoding. /// /// Returns: - /// A List containing the data converted from base32 encoding. + /// A List containing the data converted from base32 encoding. /// /// Throws: /// - ArgumentException: If the data cannot be converted from base32. static List convertFromBase32(List data) { - List? convData = _convertBits(data, 5, 8, pad: false); + final List? convData = _convertBits(data, 5, 8, pad: false); if (convData == null) { throw const ArgumentException( 'Invalid data, cannot perform conversion from base32'); @@ -152,7 +152,7 @@ abstract class Bech32EncoderBase { /// /// Parameters: /// - hrp: The Human-Readable Part (prefix) of the Bech32 string. - /// - data: The data to be encoded as a List. + /// - data: The data to be encoded as a List. /// - sep: The separator character used in the Bech32 string. /// - computeChecksum: A function that computes the checksum for the Bech32 string. /// diff --git a/lib/bech32/segwit_bech32.dart b/lib/bech32/segwit_bech32.dart index 1b65136..0ba12a5 100644 --- a/lib/bech32/segwit_bech32.dart +++ b/lib/bech32/segwit_bech32.dart @@ -78,7 +78,7 @@ class SegwitBech32Decoder extends Bech32DecoderBase { /// - [addr]: The Bech32-encoded SegWit address to decode. /// /// Returns a tuple containing the SegWit version (witness version) and the - /// decoded witness program as a List. + /// decoded witness program as a List. static Tuple> decode(String? hrp, String addr) { final decoded = Bech32DecoderBase.decodeBech32( addr, diff --git a/lib/bip/address/ada/ada_byron_addr.dart b/lib/bip/address/ada/ada_byron_addr.dart index 7a2663e..9479cc7 100644 --- a/lib/bip/address/ada/ada_byron_addr.dart +++ b/lib/bip/address/ada/ada_byron_addr.dart @@ -124,13 +124,13 @@ class ADAByronAddrTypes { /// Constants related to Ada Byron era addresses in Cardano. /// /// The ADAByronAddrConst class contains various constants used for Ada Byron era addresses: -/// - `chacha20Poly1305AssocData`: An empty List used as associated data for encryption. +/// - `chacha20Poly1305AssocData`: An empty List used as associated data for encryption. /// - `chacha20Poly1305Nonce`: A predefined nonce used for encryption purposes. /// - `payloadTag`: An integer representing the payload tag for Ada Byron era addresses. /// /// These constants are essential for handling and processing Ada Byron era addresses. class ADAByronAddrConst { - /// An empty List used as associated data for encryption. + /// An empty List used as associated data for encryption. static final List chacha20Poly1305AssocData = List.empty(); /// A predefined nonce used for encryption purposes. diff --git a/lib/bip/address/ada/ada_shelley_addr.dart b/lib/bip/address/ada/ada_shelley_addr.dart index 4382054..bdc5ac8 100644 --- a/lib/bip/address/ada/ada_shelley_addr.dart +++ b/lib/bip/address/ada/ada_shelley_addr.dart @@ -154,9 +154,9 @@ class AdaShelleyAddrUtils { } static String encodeBytes(List addrBytes) { - int header = addrBytes[0]; + final int header = addrBytes[0]; final netTag = ADANetwork.fromTag(decodeNetworkTag(header)); - ADAAddressType addressType = ADAAddressType.decodeAddressType(header); + final ADAAddressType addressType = ADAAddressType.decodeAddressType(header); if (addressType == ADAAddressType.reward) { return Bech32Encoder.encode( AdaShelleyAddrConst.networkTagToRewardAddrHrp[netTag]!, addrBytes); diff --git a/lib/bip/address/ada/gneric_addr_decoder.dart b/lib/bip/address/ada/gneric_addr_decoder.dart index 2a13222..26b3934 100644 --- a/lib/bip/address/ada/gneric_addr_decoder.dart +++ b/lib/bip/address/ada/gneric_addr_decoder.dart @@ -64,9 +64,9 @@ class AdaGenericAddrDecoder { if (addressBytes.length < QuickCrypto.blake2b224DigestSize + 1) { throw const AddressConverterException("Invalid address length."); } - int header = addressBytes[0]; - int networkTag = AdaShelleyAddrUtils.decodeNetworkTag(header); - ADAAddressType addressType = ADAAddressType.decodeAddressType(header); + final int header = addressBytes[0]; + final int networkTag = AdaShelleyAddrUtils.decodeNetworkTag(header); + final ADAAddressType addressType = ADAAddressType.decodeAddressType(header); if (network == null) { if (addressType == ADAAddressType.byron) { diff --git a/lib/bip/address/algo_addr.dart b/lib/bip/address/algo_addr.dart index b95e827..091511b 100644 --- a/lib/bip/address/algo_addr.dart +++ b/lib/bip/address/algo_addr.dart @@ -79,7 +79,7 @@ class _AlgoAddrUtils { /// - `pubKeyBytes`: The bytes of the public key for which to compute the checksum. /// /// Returns: - /// - A List containing the computed checksum bytes. + /// - A List containing the computed checksum bytes. /// /// This method is used to generate the checksum for an Algorand blockchain address. static List computeChecksum(List pubKeyBytes) { @@ -104,7 +104,7 @@ class AlgoAddrDecoder implements BlockchainAddressDecoder { /// - `addr`: The Algorand blockchain address to decode. /// /// Returns: - /// - A List containing the public key bytes extracted from the address. + /// - A List containing the public key bytes extracted from the address. /// /// This method is used to convert an Algorand blockchain address back to its public key bytes. @override @@ -138,7 +138,7 @@ class AlgoAddrEncoder implements BlockchainAddressEncoder { /// 4. Concatenate the public key bytes and the checksum, then encode them using Base32 without padding. /// /// Parameters: - /// - `pubKey`: A List representing the public key. + /// - `pubKey`: A List representing the public key. /// /// Returns: /// - The Algorand blockchain address obtained by encoding the public key. diff --git a/lib/bip/address/aptos_addr.dart b/lib/bip/address/aptos_addr.dart index ab1cd62..59231a9 100644 --- a/lib/bip/address/aptos_addr.dart +++ b/lib/bip/address/aptos_addr.dart @@ -26,7 +26,7 @@ class AptosAddrDecoder implements BlockchainAddressDecoder { /// - `kwargs` (optional): Additional arguments, though none are used in this method. /// /// Returns: - /// - A List containing the decoded address bytes. + /// - A List containing the decoded address bytes. /// /// Throws: /// - ArgumentException if the provided string is not a valid hex encoding. diff --git a/lib/bip/address/atom_addr.dart b/lib/bip/address/atom_addr.dart index 3c58e00..dacede1 100644 --- a/lib/bip/address/atom_addr.dart +++ b/lib/bip/address/atom_addr.dart @@ -3,15 +3,104 @@ 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/helper/extensions/extensions.dart'; +import 'package:blockchain_utils/utils/string/string.dart'; import 'decoder.dart'; +import 'exception/exception.dart'; -class _AtomAddressUtils { +class AtomAddressUtils { static List hash(List typ, List key) { return QuickCrypto.sha256Hash([...QuickCrypto.sha256Hash(typ), ...key]); } static final List nist566p1KeyType = List.unmodifiable("cosmos.crypto.secp256r1.PubKey".codeUnits); + + static List secp256r1PubKeyToAddress(List pubkeyBytes) { + final pubkey = AddrKeyValidator.validateAndGetNist256p1Key(pubkeyBytes); + return hash(nist566p1KeyType, pubkey.compressed); + } + + static List ed25519PubkeyToAddress(List pubkeyBytes) { + final pubkey = AddrKeyValidator.validateAndGetEd25519Key(pubkeyBytes); + return QuickCrypto.sha256Hash(pubkey.compressed).sublist(0, 20); + } + + static List ethSecp256k1PubKeyToAddress(List pubkeyBytes) { + final pubkey = AddrKeyValidator.validateAndGetSecp256k1Key(pubkeyBytes); + return QuickCrypto.keccack256Hash(pubkey.uncompressed.sublist(1)) + .sublist(12); + } + + static List secp256k1PubKeyToAddress(List pubkeyBytes) { + final pubkey = AddrKeyValidator.validateAndGetSecp256k1Key(pubkeyBytes); + return QuickCrypto.hash160(pubkey.compressed); + } + + /// Module is a specialized version of a composed address for modules. Each module account + /// is constructed from a module name and a sequence of derivation keys (at least one + /// derivation key must be provided). The derivation keys must be unique + /// in the module scope, and is usually constructed from some object id. Example, let's + /// a x/dao module, and a new DAO object, it's address would be: + /// + /// address.Module(dao.ModuleName, newDAO.ID) + static List module(String moduleName, + {List> derivationKeys = const []}) { + List keyBytes = StringUtils.encode(moduleName); + if (derivationKeys.isEmpty) { + return QuickCrypto.sha256Hash(keyBytes).sublist(0, 20); + } + keyBytes = [...keyBytes, 0]; + List addr = AtomAddressUtils.hash( + "module".codeUnits, [...keyBytes, ...derivationKeys[0]]); + for (int i = 1; i < derivationKeys.length; i++) { + addr = AtomAddressUtils.hash(addr, derivationKeys[i]); + } + return addr; + } + + static void validateAddressBytes(List addrBytes) { + if (addrBytes.length != QuickCrypto.hash160DigestSize && + addrBytes.length != QuickCrypto.sha256DigestSize) { + throw AddressConverterException("Invalid address bytes length.", + details: { + "length": addrBytes.length, + "Excepted": + "${QuickCrypto.hash160DigestSize} or ${QuickCrypto.sha256DigestSize}" + }); + } + } + + static String encodeAddressBytes( + {required List addressBytes, required String hrp}) { + validateAddressBytes(addressBytes); + return Bech32Encoder.encode(hrp, addressBytes); + } + + static AtomAddressDecodeResult decode(String address, {String? hrp}) { + try { + final decode = Bech32Decoder.decodeWithoutHRP(address); + if (hrp != null && hrp != decode.item1) { + throw AddressConverterException( + "Invalid format (HRP not valid, expected {$hrp}, got {${decode.item1}})"); + } + final addressBytes = decode.item2; + validateAddressBytes(addressBytes); + return AtomAddressDecodeResult(hrp: decode.item1, bytes: addressBytes); + } on AddressConverterException { + rethrow; + } catch (e) { + throw AddressConverterException("Invalid atom address.", + details: {"address": address, "error": e.toString()}); + } + } +} + +class AtomAddressDecodeResult { + final String hrp; + final List bytes; + AtomAddressDecodeResult({required this.hrp, required List bytes}) + : bytes = bytes.immutable; } /// Implementation of the [BlockchainAddressDecoder] for Atom (ATOM) address. @@ -25,13 +114,38 @@ class AtomAddrDecoder implements BlockchainAddressDecoder { /// - [addr]: The encoded address to decode. /// - [kwargs]: Optional keyword arguments, with 'hrp' specifying the human-readable part. /// - /// Returns a List containing the decoded address bytes. + /// Returns a List containing the decoded address bytes. /// Throws an error if the address format is invalid or if a checksum error occurs. @override List decodeAddr(String addr, [Map kwargs = const {}]) { final String hrp = AddrKeyValidator.validateAddressArgs(kwargs, "hrp"); - List addrDecBytes = Bech32Decoder.decode(hrp, addr); + final List addrDecBytes = Bech32Decoder.decode(hrp, addr); + + AddrDecUtils.validateBytesLength( + addrDecBytes, QuickCrypto.hash160DigestSize); + return addrDecBytes; + } +} + +/// Implementation of the [BlockchainAddressDecoder] for Atom (ATOM) address. +class AtomEthSecp256k1AddrDecoder implements BlockchainAddressDecoder { + /// Decode an address using the Bech32 encoding format with the specified human-readable part (HRP). + /// + /// This method takes an encoded address, along with a map of optional keyword arguments, + /// and decodes it using the Bech32 encoding format. The HRP (human-readable part) is used to + /// determine the address format. + /// + /// - [addr]: The encoded address to decode. + /// - [kwargs]: Optional keyword arguments, with 'hrp' specifying the human-readable part. + /// + /// Returns a List containing the decoded address bytes. + /// Throws an error if the address format is invalid or if a checksum error occurs. + @override + List decodeAddr(String addr, [Map kwargs = const {}]) { + final String hrp = + AddrKeyValidator.validateAddressArgs(kwargs, "hrp"); + final List addrDecBytes = Bech32Decoder.decode(hrp, addr); AddrDecUtils.validateBytesLength( addrDecBytes, QuickCrypto.hash160DigestSize); @@ -57,8 +171,31 @@ class AtomAddrEncoder implements BlockchainAddressEncoder { String encodeKey(List pubKey, [Map kwargs = const {}]) { final String hrp = AddrKeyValidator.validateAddressArgs(kwargs, "hrp"); - final public = AddrKeyValidator.validateAndGetSecp256k1Key(pubKey); - return Bech32Encoder.encode(hrp, QuickCrypto.hash160(public.compressed)); + return Bech32Encoder.encode( + hrp, AtomAddressUtils.secp256k1PubKeyToAddress(pubKey)); + } +} + +/// Implementation of the [BlockchainAddressEncoder] for Atom (ATOM) address. +class AtomEthSecp256k1AddrEncoder implements BlockchainAddressEncoder { + /// Encodes a public key as an Atom (ATOM) cryptocurrency address. + /// + /// This method takes a public key as input and encodes it as an Atom address + /// using Bech32 encoding with a specific Human-Readable Part (HRP). + /// + /// The `hrp` parameter specifies the Human-Readable Part (HRP) used in the + /// Bech32 encoding for Atom addresses. + /// + /// Returns the Atom address as a string. + /// + /// Throws an error if the `hrp` parameter is missing or invalid, or if the + /// public key cannot be validated. + @override + String encodeKey(List pubKey, [Map kwargs = const {}]) { + final String hrp = + AddrKeyValidator.validateAddressArgs(kwargs, "hrp"); + return Bech32Encoder.encode( + hrp, AtomAddressUtils.ethSecp256k1PubKeyToAddress(pubKey)); } } @@ -80,11 +217,8 @@ class AtomNist256P1AddrEncoder implements BlockchainAddressEncoder { String encodeKey(List pubKey, [Map kwargs = const {}]) { final String hrp = AddrKeyValidator.validateAddressArgs(kwargs, "hrp"); - final public = AddrKeyValidator.validateAndGetNist256p1Key(pubKey); return Bech32Encoder.encode( - hrp, - _AtomAddressUtils.hash( - _AtomAddressUtils.nist566p1KeyType, public.compressed)); + hrp, AtomAddressUtils.secp256r1PubKeyToAddress(pubKey)); } } @@ -99,16 +233,64 @@ class AtomNist256P1AddrDecoder implements BlockchainAddressDecoder { /// - [addr]: The encoded address to decode. /// - [kwargs]: Optional keyword arguments, with 'hrp' specifying the human-readable part. /// - /// Returns a List containing the decoded address bytes. + /// Returns a List containing the decoded address bytes. /// Throws an error if the address format is invalid or if a checksum error occurs. @override List decodeAddr(String addr, [Map kwargs = const {}]) { final String hrp = AddrKeyValidator.validateAddressArgs(kwargs, "hrp"); - List addrDecBytes = Bech32Decoder.decode(hrp, addr); + final List addrDecBytes = Bech32Decoder.decode(hrp, addr); AddrDecUtils.validateBytesLength( addrDecBytes, QuickCrypto.sha256DigestSize); return addrDecBytes; } } + +/// Implementation of the [BlockchainAddressEncoder] for Atom (ATOM) address. +class AtomEd25519AddrEncoder implements BlockchainAddressEncoder { + /// Encodes a public key as an Atom (ATOM) cryptocurrency address. + /// + /// This method takes a public key as input and encodes it as an Atom address + /// using Bech32 encoding with a specific Human-Readable Part (HRP). + /// + /// The `hrp` parameter specifies the Human-Readable Part (HRP) used in the + /// Bech32 encoding for Atom addresses. + /// + /// Returns the Atom address as a string. + /// + /// Throws an error if the `hrp` parameter is missing or invalid, or if the + /// public key cannot be validated. + @override + String encodeKey(List pubKey, [Map kwargs = const {}]) { + final String hrp = + AddrKeyValidator.validateAddressArgs(kwargs, "hrp"); + return Bech32Encoder.encode( + hrp, AtomAddressUtils.ed25519PubkeyToAddress(pubKey)); + } +} + +/// Implementation of the [BlockchainAddressDecoder] for Atom (ATOM) address. +class AtomEd25519AddrDecoder implements BlockchainAddressDecoder { + /// Decode an address using the Bech32 encoding format with the specified human-readable part (HRP). + /// + /// This method takes an encoded address, along with a map of optional keyword arguments, + /// and decodes it using the Bech32 encoding format. The HRP (human-readable part) is used to + /// determine the address format. + /// + /// - [addr]: The encoded address to decode. + /// - [kwargs]: Optional keyword arguments, with 'hrp' specifying the human-readable part. + /// + /// Returns a List containing the decoded address bytes. + /// Throws an error if the address format is invalid or if a checksum error occurs. + @override + List decodeAddr(String addr, [Map kwargs = const {}]) { + final String hrp = + AddrKeyValidator.validateAddressArgs(kwargs, "hrp"); + final List addrDecBytes = Bech32Decoder.decode(hrp, addr); + + AddrDecUtils.validateBytesLength( + addrDecBytes, QuickCrypto.hash160DigestSize); + return addrDecBytes; + } +} diff --git a/lib/bip/address/avax_addr.dart b/lib/bip/address/avax_addr.dart index 6ff7932..6900aa8 100644 --- a/lib/bip/address/avax_addr.dart +++ b/lib/bip/address/avax_addr.dart @@ -70,7 +70,7 @@ class _AvaxAddrUtils { /// This method validates and removes the address prefix, then delegates /// the decoding process to the [AtomAddrDecoder], providing the [hrp] as a parameter. /// - /// Returns the decoded address as a List. + /// Returns the decoded address as a List. static List decodeAddr(String addr, String prefix, String hrp) { final addrNoPrefix = AddrDecUtils.validateAndRemovePrefix(addr, prefix); return AtomAddrDecoder().decodeAddr(addrNoPrefix, {"hrp": hrp}); @@ -88,7 +88,7 @@ class AvaxPChainAddrDecoder implements BlockchainAddressDecoder { /// [_AvaxAddrUtils.decodeAddr] method, providing the address prefix and Human-Readable Part (HRP) /// from the Avax P-Chain configuration. /// - /// Returns the decoded address as a List. + /// Returns the decoded address as a List. @override List decodeAddr(String addr, [Map kwargs = const {}]) { return _AvaxAddrUtils.decodeAddr( @@ -113,7 +113,7 @@ class AvaxPChainAddrEncoder implements BlockchainAddressEncoder { /// Returns the encoded Avax P-Chain address as a String. @override String encodeKey(List pubKey, [Map kwargs = const {}]) { - String prefix = CoinsConf.avaxPChain.params.addrPrefix!; + final String prefix = CoinsConf.avaxPChain.params.addrPrefix!; return prefix + AtomAddrEncoder().encodeKey( pubKey, @@ -133,7 +133,7 @@ class AvaxXChainAddrDecoder implements BlockchainAddressDecoder { /// [_AvaxAddrUtils.decodeAddr] method, providing the address prefix and Human-Readable Part (HRP) /// from the Avax P-Chain configuration. /// - /// Returns the decoded address as a List. + /// Returns the decoded address as a List. @override List decodeAddr(String addr, [Map kwargs = const {}]) { return _AvaxAddrUtils.decodeAddr( @@ -158,7 +158,7 @@ class AvaxXChainAddrEncoder implements BlockchainAddressEncoder { /// Returns the encoded Avax X-Chain address as a String. @override String encodeKey(List pubKey, [Map kwargs = const {}]) { - String prefix = CoinsConf.avaxXChain.params.addrPrefix!; + final String prefix = CoinsConf.avaxXChain.params.addrPrefix!; return prefix + AtomAddrEncoder().encodeKey( pubKey, diff --git a/lib/bip/address/decoder.dart b/lib/bip/address/decoder.dart index 2f0d831..0109fa5 100644 --- a/lib/bip/address/decoder.dart +++ b/lib/bip/address/decoder.dart @@ -3,11 +3,11 @@ abstract class BlockchainAddressDecoder { /// Decodes a given blockchain address string. /// /// This method takes an address string and optional keyword arguments (kwargs) - /// and decodes it into a List representing the decoded address. + /// and decodes it into a List representing the decoded address. /// /// - [addr]: The blockchain address string to be decoded. /// - [kwargs]: Optional keyword arguments that can be used for configuration. /// - /// Returns a List containing the decoded blockchain address. + /// Returns a List containing the decoded blockchain address. List decodeAddr(String addr, [Map kwargs = const {}]); } diff --git a/lib/bip/address/decoders.dart b/lib/bip/address/decoders.dart index 4ea2ed3..ec8b18c 100644 --- a/lib/bip/address/decoders.dart +++ b/lib/bip/address/decoders.dart @@ -1,5 +1,5 @@ /// AN address_decoder library for decoding blockchain addresses -library address_decoder; +library; /// Export statement for Ada Byron address decoder. export 'ada/ada_byron_addr.dart' show AdaByronAddrDecoder; @@ -25,7 +25,14 @@ export 'algo_addr.dart' show AlgoAddrDecoder; export 'aptos_addr.dart' show AptosAddrDecoder; /// Export statement for Atom address decoder. -export 'atom_addr.dart' show AtomAddrDecoder; +export 'atom_addr.dart' + show + AtomAddrDecoder, + AtomAddressUtils, + AtomNist256P1AddrDecoder, + AtomEd25519AddrDecoder, + AtomAddressDecodeResult, + AtomEthSecp256k1AddrDecoder; /// Export statements for Avalanche (AVAX) address decoders. export 'avax_addr.dart' show AvaxPChainAddrDecoder, AvaxXChainAddrDecoder; @@ -40,7 +47,7 @@ export 'eos_addr.dart' show EosAddrDecoder; export 'ergo.dart' show ErgoP2PKHAddrDecoder; /// Export statement for Ethereum address decoder. -export 'eth_addr.dart' show EthAddrDecoder; +export 'eth_addr.dart' show EthAddrDecoder, EthAddrUtils; /// Export statement for Filecoin (FIL) address decoder. export 'fil_addr.dart' show FilSecp256k1AddrDecoder; @@ -96,7 +103,8 @@ export 'trx_addr.dart' show TrxAddrDecoder; export 'xlm_addr.dart' show XlmAddrDecoder; /// Export statements for Monero (XMR) address decoders. -export 'xmr_addr.dart' show XmrAddrDecoder, XmrIntegratedAddrDecoder; +export 'xmr_addr.dart' + show XmrAddrDecoder, XmrIntegratedAddrDecoder, XmrAddressType; /// Export statement for Ripple (XRP) address decoder. export 'xrp_addr.dart' show XrpAddrDecoder, XrpXAddrDecoder, XRPAddressUtils; diff --git a/lib/bip/address/egld_addr.dart b/lib/bip/address/egld_addr.dart index ab35ca2..278ccda 100644 --- a/lib/bip/address/egld_addr.dart +++ b/lib/bip/address/egld_addr.dart @@ -16,7 +16,7 @@ class EgldAddrDecoder implements BlockchainAddressDecoder { /// This method decodes the Egld address by validating and removing the prefix and verifying /// the Bech32 checksum. /// - /// Returns a List containing the decoded Egld address. + /// Returns a List containing the decoded Egld address. @override List decodeAddr(String addr, [Map kwargs = const {}]) { /// Decode the Bech32 address with the specified Human-Readable Part (HRP) @@ -37,7 +37,7 @@ class EgldAddrDecoder implements BlockchainAddressDecoder { class EgldAddrEncoder implements BlockchainAddressEncoder { /// Overrides the method to encode an Egld (Elrond) address based on the provided [pubKey]. /// - /// [pubKey]: The List representing the public key to be encoded. + /// [pubKey]: The List representing the public key to be encoded. /// [kwargs]: A map of optional keyword arguments. /// /// This method encodes the Egld address by using the specified Human-Readable Part (HRP) diff --git a/lib/bip/address/encoder.dart b/lib/bip/address/encoder.dart index 2e057cd..c8d6313 100644 --- a/lib/bip/address/encoder.dart +++ b/lib/bip/address/encoder.dart @@ -6,7 +6,7 @@ abstract class BlockchainAddressEncoder { /// Encodes a public key into a blockchain address. /// - /// This method takes a public key in the form of a List and optional keyword + /// This method takes a public key in the form of a List and optional keyword /// arguments (kwargs) for additional configuration if required. It encodes the /// public key into a blockchain-specific address. /// diff --git a/lib/bip/address/encoders.dart b/lib/bip/address/encoders.dart index 6671721..3606b1b 100644 --- a/lib/bip/address/encoders.dart +++ b/lib/bip/address/encoders.dart @@ -1,5 +1,5 @@ /// A address_encoder liberary for encoding blockchain addresses from public keys. -library address_encoder; +library; /// Export statements for Ada Byron address encoders. export 'ada/ada_byron_addr.dart' @@ -27,7 +27,13 @@ export 'algo_addr.dart' show AlgoAddrEncoder; export 'aptos_addr.dart' show AptosAddrEncoder; /// Export statement for Atom address encoder. -export 'atom_addr.dart' show AtomAddrEncoder, AtomNist256P1AddrEncoder; +export 'atom_addr.dart' + show + AtomAddrEncoder, + AtomNist256P1AddrEncoder, + AtomAddressUtils, + AtomEd25519AddrEncoder, + AtomEthSecp256k1AddrDecoder; /// Export statements for Avalanche (AVAX) address encoders. export 'avax_addr.dart' show AvaxXChainAddrEncoder, AvaxPChainAddrEncoder; @@ -45,7 +51,7 @@ export 'eos_addr.dart' show EosAddrEncoder; export 'ergo.dart' show ErgoP2PKHAddrEncoder, ErgoNetworkTypes; /// Export statement for Ethereum address encoder. -export 'eth_addr.dart' show EthAddrEncoder; +export 'eth_addr.dart' show EthAddrEncoder, EthAddrUtils; /// Export statement for Filecoin (FIL) address encoder. export 'fil_addr.dart' show FilSecp256k1AddrEncoder; @@ -101,7 +107,8 @@ export 'trx_addr.dart' show TrxAddrEncoder; export 'xlm_addr.dart' show XlmAddrEncoder, XlmAddrTypes; /// Export statements for Monero (XMR) address encoders. -export 'xmr_addr.dart' show XmrAddrEncoder, XmrIntegratedAddrEncoder; +export 'xmr_addr.dart' + show XmrAddrEncoder, XmrIntegratedAddrEncoder, XmrAddressType; /// Export statement for Ripple (XRP) address encoder. export 'xrp_addr.dart' show XrpAddrEncoder, XrpXAddrEncoder, XRPAddressUtils; diff --git a/lib/bip/address/eos_addr.dart b/lib/bip/address/eos_addr.dart index 5a8c0e8..c79f9cb 100644 --- a/lib/bip/address/eos_addr.dart +++ b/lib/bip/address/eos_addr.dart @@ -19,7 +19,7 @@ class _EosAddrUtils { /// /// [pubKeyBytes]: The public key bytes used to compute the checksum. /// - /// Returns the computed checksum as a List. + /// Returns the computed checksum as a `List`. static List computeChecksum(List pubKeyBytes) { return QuickCrypto.ripemd160Hash(pubKeyBytes) .sublist(0, EosAddrConst.checksumByteLen); @@ -36,7 +36,7 @@ class EosAddrDecoder implements BlockchainAddressDecoder { /// This method removes the address prefix, decodes the address bytes, and validates the checksum. /// It returns the decoded public key bytes of the EOS address. /// - /// Returns a List containing the public key bytes. + /// Returns a `List` containing the public key bytes. @override List decodeAddr(String addr, [Map kwargs = const {}]) { /// Remove the address prefix from the given address diff --git a/lib/bip/address/ergo.dart b/lib/bip/address/ergo.dart index 7e5be8e..9175968 100644 --- a/lib/bip/address/ergo.dart +++ b/lib/bip/address/ergo.dart @@ -52,7 +52,7 @@ class _ErgoAddrUtils { /// Computes the checksum for an Ergo address. /// /// [pubKeyBytes]: The public key bytes to generate the checksum from. - /// Returns a List representing the computed checksum. + /// Returns a `List` representing the computed checksum. static List computeChecksum(List pubKeyBytes) { final checksum = QuickCrypto.blake2b256Hash(pubKeyBytes); return checksum.sublist(0, ErgoAddrConst.checksumByteLen); @@ -62,7 +62,7 @@ class _ErgoAddrUtils { /// /// [addrType]: The address type (e.g., p2pkh or p2sh). /// [netType]: The network type (e.g., mainnet or testnet). - /// Returns a List representing the encoded prefix. + /// Returns a `List` representing the encoded prefix. static List encodePrefix( ErgoAddressTypes addrType, ErgoNetworkTypes netType) { final prefixInt = addrType.value + netType.value; @@ -80,7 +80,7 @@ class ErgoP2PKHAddrDecoder implements BlockchainAddressDecoder { /// [kwargs]: Optional parameters. /// - [net_type]: The network type for the Ergo address (mainnet or testnet). /// - /// Returns a List representing the public key bytes decoded from the address. + /// Returns a `List` representing the public key bytes decoded from the address. /// Throws an ArgumentException if the address type is not of ErgoNetworkTypes. @override List decodeAddr(String addr, [Map kwargs = const {}]) { diff --git a/lib/bip/address/eth_addr.dart b/lib/bip/address/eth_addr.dart index 0a1c727..3a53d03 100644 --- a/lib/bip/address/eth_addr.dart +++ b/lib/bip/address/eth_addr.dart @@ -33,12 +33,12 @@ class EthAddrUtils { /// Returns: /// A string representing the Ethereum address with checksum. static String _checksumEncode(String addr) { - String addrHexDigest = BytesUtils.toHexString( + final String addrHexDigest = BytesUtils.toHexString( QuickCrypto.keccack256Hash(StringUtils.encode(addr.toLowerCase()))); - List encAddr = addr.split("").asMap().entries.map((entry) { - int i = entry.key; - String c = entry.value; - int charValue = int.parse(addrHexDigest[i], radix: 16); + final List encAddr = addr.split("").asMap().entries.map((entry) { + final int i = entry.key; + final String c = entry.value; + final int charValue = int.parse(addrHexDigest[i], radix: 16); return charValue >= 8 ? c.toUpperCase() : c.toLowerCase(); }).toList(); @@ -47,10 +47,19 @@ class EthAddrUtils { static String toChecksumAddress(String addr) { final String wihtoutPrefix = StringUtils.strip0x(addr); + if (!StringUtils.isHexBytes(wihtoutPrefix)) { + throw AddressConverterException("Invalid Ethereum address.", + details: {"address": addr}); + } AddrDecUtils.validateLength(wihtoutPrefix, EthAddrConst.addrLen); return CoinsConf.ethereum.params.addrPrefix! + _checksumEncode(wihtoutPrefix); } + + static String addressBytesToChecksumAddress(List bytes) { + final String addr = BytesUtils.toHexString(bytes); + return toChecksumAddress(addr); + } } /// Implementation of the [BlockchainAddressDecoder] for Ethereum addresses. @@ -67,7 +76,7 @@ class EthAddrDecoder implements BlockchainAddressDecoder { /// configuration. /// /// Returns: - /// A List representing the byte-encoded Ethereum address. + /// A `List` representing the byte-encoded Ethereum address. /// /// Throws: /// - ArgumentException: If the address is not of the correct length or if checksum @@ -76,7 +85,7 @@ class EthAddrDecoder implements BlockchainAddressDecoder { List decodeAddr(String addr, [Map kwargs = const {}]) { final skipChecksum = kwargs["skip_chksum_enc"] ?? false; - String addrNoPrefix = AddrDecUtils.validateAndRemovePrefix( + final String addrNoPrefix = AddrDecUtils.validateAndRemovePrefix( addr, CoinsConf.ethereum.params.addrPrefix!); AddrDecUtils.validateLength(addrNoPrefix, EthAddrConst.addrLen); if (!skipChecksum && @@ -104,11 +113,12 @@ class EthAddrEncoder implements BlockchainAddressEncoder { /// A string representing the Ethereum address. @override String encodeKey(List pubKey, [Map kwargs = const {}]) { - IPublicKey pubKeyObj = AddrKeyValidator.validateAndGetSecp256k1Key(pubKey); + final IPublicKey pubKeyObj = + AddrKeyValidator.validateAndGetSecp256k1Key(pubKey); final skipChecksum = kwargs["skip_chksum_enc"] ?? false; - String kekkakHex = BytesUtils.toHexString( + final String kekkakHex = BytesUtils.toHexString( QuickCrypto.keccack256Hash(pubKeyObj.uncompressed.sublist(1))); - String addr = kekkakHex.substring(EthAddrConst.startByte); + final String addr = kekkakHex.substring(EthAddrConst.startByte); if (skipChecksum) { return addr; } diff --git a/lib/bip/address/exception/exception.dart b/lib/bip/address/exception/exception.dart index fe44b11..1ab8684 100644 --- a/lib/bip/address/exception/exception.dart +++ b/lib/bip/address/exception/exception.dart @@ -1,7 +1,5 @@ import 'package:blockchain_utils/exception/exceptions.dart'; class AddressConverterException extends BlockchainUtilsException { - const AddressConverterException(String message, - {Map? details}) - : super(message, details: details); + const AddressConverterException(super.message, {super.details}); } diff --git a/lib/bip/address/fil_addr.dart b/lib/bip/address/fil_addr.dart index ec203b0..6c4e133 100644 --- a/lib/bip/address/fil_addr.dart +++ b/lib/bip/address/fil_addr.dart @@ -37,14 +37,14 @@ class _FilAddrUtils { /// Blake2b-32 hashing algorithm. /// /// Parameters: - /// - pubKeyHash: The public key hash of the address as a List. + /// - pubKeyHash: The public key hash of the address as a `List`. /// - addrType: The address type (e.g., secp256k1 or bls). /// /// Returns: - /// A List representing the computed checksum. + /// A `List` representing the computed checksum. static List computeChecksum( List pubKeyHash, FillAddrTypes addrType) { - List addrTypeByte = List.from([addrType.value]); + final List addrTypeByte = List.from([addrType.value]); return QuickCrypto.blake2b32Hash( List.from([...addrTypeByte, ...pubKeyHash])); } @@ -60,20 +60,21 @@ class _FilAddrUtils { /// - addrType: The expected address type (e.g., secp256k1 or bls). /// /// Returns: - /// A List representing the decoded public key hash. + /// A `List` representing the decoded public key hash. /// /// Throws: /// - ArgumentException if the address type doesn't match the expected type. /// - ArgumentException if the address format, length, or checksum is invalid. static List decodeAddr(String addr, FillAddrTypes addrType) { - String addrNoPrefix = AddrDecUtils.validateAndRemovePrefix( + final String addrNoPrefix = AddrDecUtils.validateAndRemovePrefix( addr, CoinsConf.filecoin.params.addrPrefix!); - int addrTypeGot = addrNoPrefix[0].codeUnits.first - "0".codeUnits.first; + final int addrTypeGot = + addrNoPrefix[0].codeUnits.first - "0".codeUnits.first; if (addrType.value != addrTypeGot) { throw AddressConverterException( "Invalid address type (expected ${addrType.value}, got $addrTypeGot)"); } - List addrDecBytes = Base32Decoder.decode( + final List addrDecBytes = Base32Decoder.decode( addrNoPrefix.substring(1), FilAddrConst.base32Alphabet); AddrDecUtils.validateBytesLength(addrDecBytes, QuickCrypto.blake2b160DigestSize + QuickCrypto.blake2b32DigestSize); @@ -94,18 +95,18 @@ class _FilAddrUtils { /// in base32 using the specified alphabet. /// /// Parameters: - /// - pubKeyBytes: The public key bytes of the address as a List. + /// - pubKeyBytes: The public key bytes of the address as a `List`. /// - addrType: The address type (e.g., secp256k1 or bls). /// /// Returns: /// A string representing the encoded Filecoin address. static String encodeKeyBytes(List pubKeyBytes, FillAddrTypes addrType) { - String addrTypeStr = String.fromCharCode(addrType.value + 48); - List pubKeyHashBytes = QuickCrypto.blake2b160Hash(pubKeyBytes); - List checksumBytes = computeChecksum(pubKeyHashBytes, addrType); + final String addrTypeStr = String.fromCharCode(addrType.value + 48); + final List pubKeyHashBytes = QuickCrypto.blake2b160Hash(pubKeyBytes); + final List checksumBytes = computeChecksum(pubKeyHashBytes, addrType); final bytesWithChecksum = List.from(pubKeyHashBytes + checksumBytes); - String b32Enc = Base32Encoder.encodeNoPaddingBytes( + final String b32Enc = Base32Encoder.encodeNoPaddingBytes( bytesWithChecksum, FilAddrConst.base32Alphabet); return CoinsConf.filecoin.params.addrPrefix! + addrTypeStr + b32Enc; } @@ -117,13 +118,13 @@ class FilSecp256k1AddrDecoder implements BlockchainAddressDecoder { /// /// This method decodes a Filecoin address by calling the internal utility method /// `_FilAddrUtils.decodeAddr`. It expects the address type to be provided as - /// `FillAddrTypes.secp256k1`. The decoded address is returned as a List. + /// `FillAddrTypes.secp256k1`. The decoded address is returned as a `List`. /// /// Parameters: /// - addr: The Filecoin address to decode as a string. /// /// Returns: - /// A List representing the decoded Filecoin address + /// A `List` representing the decoded Filecoin address @override List decodeAddr(String addr, [Map kwargs = const {}]) { return _FilAddrUtils.decodeAddr(addr, FillAddrTypes.secp256k1); @@ -134,13 +135,13 @@ class FilSecp256k1AddrDecoder implements BlockchainAddressDecoder { class FilSecp256k1AddrEncoder implements BlockchainAddressEncoder { /// Encodes a Filecoin address for a public key using the secp256k1 address type. /// - /// This method takes a public key represented as a List, validates it as a + /// This method takes a public key represented as a `List`, validates it as a /// secp256k1 public key, converts it to raw uncompressed bytes, and then encodes /// a Filecoin address of the secp256k1 address type. The resulting address is /// returned as a string. /// /// Parameters: - /// - pubKey: The public key to encode as a List. + /// - pubKey: The public key to encode as a `List`. /// /// Returns: /// A string representing the encoded Filecoin address. diff --git a/lib/bip/address/icx_addr.dart b/lib/bip/address/icx_addr.dart index 4820ff5..fe8f1f9 100644 --- a/lib/bip/address/icx_addr.dart +++ b/lib/bip/address/icx_addr.dart @@ -21,24 +21,24 @@ class IcxAddrDecoder implements BlockchainAddressDecoder { /// keyword arguments for custom ICON address parameters. The method performs the following steps: /// 1. Removes the ICON address prefix. /// 2. Validates the length of the decoded public key hash. - /// 3. Returns the decoded public key hash as a List. + /// 3. Returns the decoded public key hash as a `List`. /// /// Parameters: /// - addr: The ICON address to be decoded as a string. /// - kwargs: Optional keyword arguments for custom ICON address parameters (not used in this implementation). /// /// Returns: - /// A List containing the decoded public key hash of the ICON address. + /// A `List` containing the decoded public key hash of the ICON address. @override List decodeAddr(String addr, [Map kwargs = const {}]) { /// Remove the ICON address prefix. - String addrNoPrefix = AddrDecUtils.validateAndRemovePrefix( + final String addrNoPrefix = AddrDecUtils.validateAndRemovePrefix( addr, CoinsConf.icon.params.addrPrefix!, ); - /// Convert the remaining string to a List and validate its length. - List pubKeyHashBytes = BytesUtils.fromHexString(addrNoPrefix); + /// Convert the remaining string to a `List` and validate its length. + final List pubKeyHashBytes = BytesUtils.fromHexString(addrNoPrefix); AddrDecUtils.validateBytesLength( pubKeyHashBytes, IcxAddrConst.keyHashByteLen); @@ -50,14 +50,14 @@ class IcxAddrDecoder implements BlockchainAddressDecoder { class IcxAddrEncoder implements BlockchainAddressEncoder { /// Overrides the base class method to encode a public key as an ICON (ICX) address. /// - /// This method encodes a public key as an ICON address. It expects the public key as a List + /// This method encodes a public key as an ICON address. It expects the public key as a `List` /// and returns the ICON address as a string. The encoding process involves: /// 1. Validating and transforming the public key into a 32-byte hash. /// 2. Truncating the hash to the required ICON address length. /// 3. Adding the ICON address prefix to the hash. /// /// Parameters: - /// - pubKey: The public key to be encoded as an ICON address in the form of a List. + /// - pubKey: The public key to be encoded as an ICON address in the form of a `List`. /// - kwargs: Optional keyword arguments (not used in this implementation). /// /// Returns: @@ -65,7 +65,8 @@ class IcxAddrEncoder implements BlockchainAddressEncoder { @override String encodeKey(List pubKey, [Map kwargs = const {}]) { /// Validate and transform the public key into a 32-byte hash. - IPublicKey pubKeyObj = AddrKeyValidator.validateAndGetSecp256k1Key(pubKey); + final IPublicKey pubKeyObj = + AddrKeyValidator.validateAndGetSecp256k1Key(pubKey); List pubKeyHashBytes = QuickCrypto.sha3256Hash(pubKeyObj.uncompressed.sublist(1)); diff --git a/lib/bip/address/inj_addr.dart b/lib/bip/address/inj_addr.dart index 3f75b93..1c1ba0e 100644 --- a/lib/bip/address/inj_addr.dart +++ b/lib/bip/address/inj_addr.dart @@ -14,14 +14,14 @@ class InjAddrDecoder implements BlockchainAddressDecoder { /// keyword arguments for custom INJ address parameters. The method performs the following steps: /// 1. Decodes the Bech32-encoded address using the INJ address human-readable part (hrp). /// 2. Validates the length of the decoded address. - /// 3. Returns the decoded address as a List. + /// 3. Returns the decoded address as a `List`. /// /// Parameters: /// - addr: The INJ address to be decoded as a string. /// - kwargs: Optional keyword arguments for custom INJ address parameters (not used in this implementation). /// /// Returns: - /// A List containing the decoded INJ address. + /// A `List` containing the decoded INJ address. @override List decodeAddr(String addr, [Map kwargs = const {}]) { /// Decode the Bech32-encoded address using the INJ address human-readable part (hrp). @@ -43,13 +43,13 @@ class InjAddrDecoder implements BlockchainAddressDecoder { class InjAddrEncoder implements BlockchainAddressEncoder { /// Overrides the base class method to encode a public key as an INJ (Injective Protocol) address. /// - /// This method encodes a public key as an INJ address. It expects the public key as a List + /// This method encodes a public key as an INJ address. It expects the public key as a `List` /// and returns the INJ address as a string. The encoding process involves: /// 1. Encoding the public key as an Ethereum (ETH) address using EthAddrEncoder. /// 2. Encoding the ETH address using the INJ address human-readable part (hrp). /// /// Parameters: - /// - pubKey: The public key to be encoded as an INJ address in the form of a List. + /// - pubKey: The public key to be encoded as an INJ address in the form of a `List`. /// - kwargs: Optional keyword arguments (not used in this implementation). /// /// Returns: diff --git a/lib/bip/address/nano_addr.dart b/lib/bip/address/nano_addr.dart index 2778de6..fa691ba 100644 --- a/lib/bip/address/nano_addr.dart +++ b/lib/bip/address/nano_addr.dart @@ -25,13 +25,13 @@ class _NanoAddrUtils { /// Computes the checksum for a Nano address based on the provided public key bytes. /// /// This method computes the checksum for a Nano address by taking the reversed Blake2b-40 hash - /// of the provided public key bytes. The result is returned as a List. + /// of the provided public key bytes. The result is returned as a `List`. /// /// Parameters: /// - pubKeyBytes: The public key bytes used to compute the checksum. /// /// Returns: - /// A List containing the computed checksum for the Nano address. + /// A `List` containing the computed checksum for the Nano address. static List computeChecksum(List pubKeyBytes) { return QuickCrypto.blake2b40Hash(pubKeyBytes).reversed.toList(); } @@ -54,7 +54,7 @@ class NanoAddrDecoder implements BlockchainAddressDecoder { /// - kwargs: Optional keyword arguments for custom Nano address parameters. /// /// Returns: - /// A List containing the decoded public key bytes for the Nano address. + /// A `List` containing the decoded public key bytes for the Nano address. @override List decodeAddr(String addr, [Map kwargs = const {}]) { /// Validate and remove the Nano address prefix. @@ -100,7 +100,7 @@ class NanoAddrDecoder implements BlockchainAddressDecoder { class NanoAddrEncoder implements BlockchainAddressEncoder { /// Overrides the base class method to encode a public key as a Nano address. /// - /// This method encodes a public key as a Nano address. It expects the public key as a List + /// This method encodes a public key as a Nano address. It expects the public key as a `List` /// and returns the Nano address as a string. The encoding process involves: /// 1. Validating and obtaining the Ed25519 Blake2b public key. /// 2. Calculating the Nano address payload by appending padding, public key bytes, and checksum. @@ -108,7 +108,7 @@ class NanoAddrEncoder implements BlockchainAddressEncoder { /// 4. Prepending the Nano address prefix. /// /// Parameters: - /// - pubKey: The public key to be encoded as a Nano address in the form of a List. + /// - pubKey: The public key to be encoded as a Nano address in the form of a `List`. /// - kwargs: Optional keyword arguments (not used in this implementation). /// /// Returns: diff --git a/lib/bip/address/near_addr.dart b/lib/bip/address/near_addr.dart index deb5881..bde48d2 100644 --- a/lib/bip/address/near_addr.dart +++ b/lib/bip/address/near_addr.dart @@ -12,18 +12,18 @@ class NearAddrDecoder implements BlockchainAddressDecoder { /// This method decodes a Near Protocol address from the provided input string, which is expected /// to be a hexadecimal representation of the public key bytes. It validates the length of the input, /// ensuring it matches the expected compressed Ed25519 public key length. The decoded public key bytes - /// are returned as a List. + /// are returned as a `List`. /// /// Parameters: /// - addr: The hexadecimal representation of the public key bytes for the Near Protocol address. /// - kwargs: Optional keyword arguments (not used in this implementation). /// /// Returns: - /// A List containing the decoded public key bytes for the Near Protocol address. + /// A `List` containing the decoded public key bytes for the Near Protocol address. @override List decodeAddr(String addr, [Map kwargs = const {}]) { /// Convert the hexadecimal input to bytes. - List pubKeyBytes = BytesUtils.fromHexString(addr); + final List pubKeyBytes = BytesUtils.fromHexString(addr); /// Validate the length of the public key bytes. AddrDecUtils.validateBytesLength( @@ -37,11 +37,11 @@ class NearAddrDecoder implements BlockchainAddressDecoder { class NearAddrEncoder implements BlockchainAddressEncoder { /// Overrides the base class method to encode a public key as a Near Protocol address. /// - /// This method encodes a public key as a Near Protocol address. It expects the public key as a List + /// This method encodes a public key as a Near Protocol address. It expects the public key as a `List` /// and returns it as a hexadecimal representation, stripping the '0x' prefix from the result. /// /// Parameters: - /// - pubKey: The public key to be encoded as a Near Protocol address in the form of a List. + /// - pubKey: The public key to be encoded as a Near Protocol address in the form of a `List`. /// - kwargs: Optional keyword arguments (not used in this implementation). /// /// Returns: diff --git a/lib/bip/address/neo_addr.dart b/lib/bip/address/neo_addr.dart index ae052f5..a87ea6b 100644 --- a/lib/bip/address/neo_addr.dart +++ b/lib/bip/address/neo_addr.dart @@ -24,27 +24,27 @@ class NeoAddrDecoder implements BlockchainAddressDecoder { /// This method decodes a Neo address from the provided input string using Base58 encoding. /// It expects an optional map of keyword arguments with 'ver' specifying the version bytes. /// The method validates the arguments, decodes the Base58 address, checks its version, length, - /// and checksum, and returns the decoded Neo address as a List. + /// and checksum, and returns the decoded Neo address as a `List`. /// /// Parameters: /// - addr: The Base58-encoded Neo address to be decoded. /// - kwargs: Optional keyword arguments with 'ver' for the version bytes. /// /// Returns: - /// A List containing the decoded Neo address bytes. + /// A `List` containing the decoded Neo address bytes. @override List decodeAddr(String addr, [Map kwargs = const {}]) { /// Validate the version argument. AddrKeyValidator.validateAddressArgs>(kwargs, "ver"); - List verBytes = kwargs["ver"]; - List addrDecBytes = Base58Decoder.checkDecode(addr); + final List verBytes = kwargs["ver"]; + final List addrDecBytes = Base58Decoder.checkDecode(addr); /// Validate the length of the decoded address. AddrDecUtils.validateBytesLength( addrDecBytes, QuickCrypto.hash160DigestSize + verBytes.length); /// Retrieve the version byte from the decoded address and compare it with the expected version. - List verGot = IntUtils.toBytes(addrDecBytes[0], + final List verGot = IntUtils.toBytes(addrDecBytes[0], length: IntUtils.bitlengthInBytes(addrDecBytes[0]), byteOrder: Endian.little); if (!BytesUtils.bytesEqual(verGot, verBytes)) { @@ -66,7 +66,7 @@ class NeoAddrEncoder implements BlockchainAddressEncoder { /// and encodes it as a Base58 address. The result is returned as a String representing the Neo address. /// /// Parameters: - /// - pubKey: The public key to be encoded as a Neo address in the form of a List. + /// - pubKey: The public key to be encoded as a Neo address in the form of a `List`. /// - kwargs: Optional keyword arguments with 'ver' for the version bytes. /// /// Returns: @@ -75,13 +75,13 @@ class NeoAddrEncoder implements BlockchainAddressEncoder { String encodeKey(List pubKey, [Map kwargs = const {}]) { /// Validate the version argument. AddrKeyValidator.validateAddressArgs>(kwargs, "ver"); - List verBytes = kwargs["ver"]; + final List verBytes = kwargs["ver"]; /// Validate and get the Nist256p1 public key. final pubKeyObj = AddrKeyValidator.validateAndGetNist256p1Key(pubKey); /// Construct the Neo address payload. - List payloadBytes = List.from([ + final List payloadBytes = List.from([ ...NeoAddrConst.prefixByte, ...pubKeyObj.compressed, ...NeoAddrConst.suffixByte, diff --git a/lib/bip/address/okex_addr.dart b/lib/bip/address/okex_addr.dart index ee446e2..aea1d64 100644 --- a/lib/bip/address/okex_addr.dart +++ b/lib/bip/address/okex_addr.dart @@ -15,7 +15,7 @@ class OkexAddrDecoder implements BlockchainAddressDecoder { /// It expects an optional map of keyword arguments for custom behavior, but specifically, it skips /// the checksum encoding validation. The address Human-Readable Part (HRP) is retrieved from the /// OKExChain configuration. The method first decodes the Bech32 address and then decodes it again - /// as an Ethereum address with a custom prefix. The result is returned as a List containing + /// as an Ethereum address with a custom prefix. The result is returned as a `List` containing /// the decoded Ethereum address bytes. /// /// Parameters: @@ -23,12 +23,12 @@ class OkexAddrDecoder implements BlockchainAddressDecoder { /// - kwargs: Optional keyword arguments (with 'skip_chksum_enc' for skipping checksum encoding). /// /// Returns: - /// A List containing the decoded Ethereum address bytes derived from the OKExChain address. + /// A `List` containing the decoded Ethereum address bytes derived from the OKExChain address. @override List decodeAddr(String addr, [Map kwargs = const {}]) { try { /// Decode the OKExChain address using the OKExChain configuration's HRP. - List addrDecBytes = + final List addrDecBytes = Bech32Decoder.decode(CoinsConf.okexChain.params.addrHrp!, addr); /// Decode the address again as an Ethereum address with a custom prefix. @@ -55,7 +55,7 @@ class OkexAddrEncoder implements BlockchainAddressEncoder { /// the Bech32-encoded OKExChain address. /// /// Parameters: - /// - pubKey: The Ethereum address in the form of a List. + /// - pubKey: The Ethereum address in the form of a `List`. /// - kwargs: Optional keyword arguments. /// /// Returns: @@ -63,7 +63,8 @@ class OkexAddrEncoder implements BlockchainAddressEncoder { @override String encodeKey(List pubKey, [Map kwargs = const {}]) { /// Encode the Ethereum address without the '0x' prefix. - String ethAddr = StringUtils.strip0x(EthAddrEncoder().encodeKey(pubKey)); + final String ethAddr = + StringUtils.strip0x(EthAddrEncoder().encodeKey(pubKey)); /// Encode the Ethereum address as an OKExChain address using Bech32 encoding. return Bech32Encoder.encode( diff --git a/lib/bip/address/one_addr.dart b/lib/bip/address/one_addr.dart index 8679974..626a5e0 100644 --- a/lib/bip/address/one_addr.dart +++ b/lib/bip/address/one_addr.dart @@ -13,7 +13,7 @@ class OneAddrDecoder implements BlockchainAddressDecoder { /// It expects an optional map of keyword arguments for custom behavior, but specifically, it skips /// the checksum encoding validation. The address Human-Readable Part (HRP) is retrieved from the /// Harmony ONE configuration. The method first decodes the Bech32 address, and then decodes it again - /// as an Ethereum address with a custom prefix. The result is returned as a List containing + /// as an Ethereum address with a custom prefix. The result is returned as a `List` containing /// the decoded Ethereum address bytes. /// /// Parameters: @@ -21,10 +21,10 @@ class OneAddrDecoder implements BlockchainAddressDecoder { /// - kwargs: Optional keyword arguments (with 'skip_chksum_enc' for skipping checksum encoding). /// /// Returns: - /// A List containing the decoded Ethereum address bytes derived from the Harmony ONE address. + /// A `List` containing the decoded Ethereum address bytes derived from the Harmony ONE address. @override List decodeAddr(String addr, [Map kwargs = const {}]) { - List addrDecBytes = + final List addrDecBytes = Bech32Decoder.decode(CoinsConf.harmonyOne.params.addrHrp!, addr); /// Decode the address again as an Ethereum address with a custom prefix. @@ -45,7 +45,7 @@ class OneAddrEncoder implements BlockchainAddressEncoder { /// Bech32-encoded Harmony ONE address. /// /// Parameters: - /// - pubKey: The Ethereum address in the form of a List. + /// - pubKey: The Ethereum address in the form of a `List`. /// - kwargs: Optional keyword arguments. /// /// Returns: @@ -53,7 +53,8 @@ class OneAddrEncoder implements BlockchainAddressEncoder { @override String encodeKey(List pubKey, [Map kwargs = const {}]) { /// Encode the Ethereum address without the '0x' prefix. - String ethAddr = StringUtils.strip0x(EthAddrEncoder().encodeKey(pubKey)); + final String ethAddr = + StringUtils.strip0x(EthAddrEncoder().encodeKey(pubKey)); /// Encode the Ethereum address as a Harmony ONE address using Bech32 encoding. return Bech32Encoder.encode( diff --git a/lib/bip/address/p2pkh_addr.dart b/lib/bip/address/p2pkh_addr.dart index a75527c..428fb2e 100644 --- a/lib/bip/address/p2pkh_addr.dart +++ b/lib/bip/address/p2pkh_addr.dart @@ -1,5 +1,6 @@ import 'package:blockchain_utils/base58/base58.dart'; import 'package:blockchain_utils/bech32/bch_bech32.dart'; +import 'package:blockchain_utils/bip/bip/types/types.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'; @@ -8,15 +9,6 @@ import 'package:blockchain_utils/crypto/quick_crypto.dart'; import 'decoder.dart'; import 'exception/exception.dart'; -/// Enumeration representing different modes for public keys used in P2PKH addresses. -/// -/// This enum defines different modes for public keys that can be used in P2PKH (Pay-to-Public-Key-Hash) -/// addresses. These modes may include compressed and uncompressed public keys, among others. -enum PubKeyModes { - compressed, - uncompressed, -} - /// Implementation of the [BlockchainAddressDecoder] for P2PKH (Pay-to-Public-Key-Hash) addresses. class P2PKHAddrDecoder implements BlockchainAddressDecoder { /// Overrides the base class method to decode a P2PKH (Pay-to-Public-Key-Hash) address. @@ -24,25 +16,25 @@ class P2PKHAddrDecoder implements BlockchainAddressDecoder { /// This method decodes a P2PKH address from the provided input string using Base58 encoding. /// It expects an optional map of keyword arguments with 'net_ver' specifying the network version bytes, /// and 'base58_alph' for the Base58 alphabet. It validates the arguments, decodes the address, - /// checks its length and network version, and returns the decoded P2PKH address as a List. + /// checks its length and network version, and returns the decoded P2PKH address as a `List`. /// /// Parameters: /// - addr: The P2PKH address to be decoded. /// - kwargs: Optional keyword arguments with 'net_ver' for the network version and 'base58_alph' for Base58 alphabet. /// /// Returns: - /// A List containing the decoded P2PKH address bytes. + /// A `List` containing the decoded P2PKH address bytes. @override List decodeAddr(String addr, [Map kwargs = const {}]) { /// Validate network version and Base58 alphabet arguments. AddrKeyValidator.validateAddressArgs>(kwargs, "net_ver"); - List netVarBytes = kwargs["net_ver"]; + final List netVarBytes = kwargs["net_ver"]; final Base58Alphabets alphabet = kwargs["base58_alph"] ?? Base58Alphabets.bitcoin; /// Decode the address using the specified Base58 alphabet. - List addrDecBytes = Base58Decoder.checkDecode(addr, alphabet); + final List addrDecBytes = Base58Decoder.checkDecode(addr, alphabet); /// Validate the length of the decoded address and its network version. AddrDecUtils.validateBytesLength( @@ -110,14 +102,14 @@ class BchP2PKHAddrDecoder implements BlockchainAddressDecoder { /// This method decodes a P2PKH address from the provided input string using Bech32 encoding. /// It expects an optional map of keyword arguments with 'net_ver' specifying the network version bytes /// and 'hrp' for the Human-Readable Part (HRP). It validates the arguments, decodes the Bech32 address, - /// checks its network version, length, and checksum, and returns the decoded P2PKH address as a List. + /// checks its network version, length, and checksum, and returns the decoded P2PKH address as a `List`. /// /// Parameters: /// - addr: The Bech32-encoded P2PKH address to be decoded. /// - kwargs: Optional keyword arguments with 'net_ver' for the network version and 'hrp' for HRP. /// /// Returns: - /// A List containing the decoded P2PKH address bytes. + /// A `List` containing the decoded P2PKH address bytes. @override List decodeAddr(String addr, [Map kwargs = const {}]) { /// Validate network version and HRP arguments. @@ -128,8 +120,8 @@ class BchP2PKHAddrDecoder implements BlockchainAddressDecoder { /// Decode the Bech32 address and retrieve network version and decoded bytes. final result = BchBech32Decoder.decode(hrp, addr); - List netVerBytesGot = result.item1; - List addrDecBytes = result.item2; + final List netVerBytesGot = result.item1; + final List addrDecBytes = result.item2; /// Validate that the decoded network version matches the expected network version. if (!BytesUtils.bytesEqual(netVerBytes, netVerBytesGot)) { @@ -163,8 +155,8 @@ class BchP2PKHAddrEncoder implements BlockchainAddressEncoder { /// Validate network version and HRP arguments. AddrKeyValidator.validateAddressArgs>(kwargs, "net_ver"); AddrKeyValidator.validateAddressArgs(kwargs, "hrp"); - String hrp = kwargs['hrp']; - List netVerBytes = kwargs['net_ver']; + final String hrp = kwargs['hrp']; + final List netVerBytes = kwargs['net_ver']; /// Validate and process the public key as a Secp256k1 key. final pubKeyObj = AddrKeyValidator.validateAndGetSecp256k1Key(pubKey); diff --git a/lib/bip/address/p2sh_addr.dart b/lib/bip/address/p2sh_addr.dart index 158ead1..aea99df 100644 --- a/lib/bip/address/p2sh_addr.dart +++ b/lib/bip/address/p2sh_addr.dart @@ -28,7 +28,7 @@ class _P2SHAddrUtils { /// - pubKey: The public key from which to generate the P2SH script signature. /// /// Returns: - /// A List representing the P2SH script signature. + /// A `List` representing the P2SH script signature. static List addScriptSig(IPublicKey pubKey) { /// Compute the key hash from the compressed public key. final keyHashBytes = QuickCrypto.hash160(pubKey.compressed); @@ -48,14 +48,14 @@ class P2SHAddrDecoder implements BlockchainAddressDecoder { /// /// This method delegates the decoding process to the P2PKHAddrDecoder class, which /// specializes in decoding P2SH addresses. It expects the provided address and - /// an optional map of keyword arguments. The decoded P2SH address is returned as a List. + /// an optional map of keyword arguments. The decoded P2SH address is returned as a `List`. /// /// Parameters: /// - addr: The P2SH address to be decoded. /// - kwargs: Optional keyword arguments for customization (not used in this implementation). /// /// Returns: - /// A List containing the decoded P2SH address bytes. + /// A `List` containing the decoded P2SH address bytes. @override List decodeAddr(String addr, [Map kwargs = const {}]) { return P2PKHAddrDecoder().decodeAddr(addr, kwargs); @@ -82,16 +82,17 @@ class P2SHAddrEncoder implements BlockchainAddressEncoder { String encodeKey(List pubKey, [Map kwargs = const {}]) { /// Validate network version arguments and retrieve the network version bytes. AddrKeyValidator.validateAddressArgs>(kwargs, 'net_ver'); - List netVerBytes = kwargs['net_ver']; + final List netVerBytes = kwargs['net_ver']; /// Validate and process the public key as a Secp256k1 key. - IPublicKey pubKeyObj = AddrKeyValidator.validateAndGetSecp256k1Key(pubKey); + final IPublicKey pubKeyObj = + AddrKeyValidator.validateAndGetSecp256k1Key(pubKey); /// Generate the script signature from the public key. - List scriptSigBytes = _P2SHAddrUtils.addScriptSig(pubKeyObj); + final List scriptSigBytes = _P2SHAddrUtils.addScriptSig(pubKeyObj); /// Combine the network version and script signature to form the address bytes. - List addressBytes = + final List addressBytes = List.filled(netVerBytes.length + scriptSigBytes.length, 0); addressBytes.setAll(0, netVerBytes); addressBytes.setAll(netVerBytes.length, scriptSigBytes); @@ -115,14 +116,14 @@ class BchP2SHAddrDecoder implements BlockchainAddressDecoder { /// - kwargs: Optional keyword arguments with 'hrp' for HRP and 'net_ver' for network version. /// /// Returns: - /// A List containing the decoded P2SH address bytes. + /// A `List` containing the decoded P2SH address bytes. @override List decodeAddr(String addr, [Map kwargs = const {}]) { /// Validate HRP and network version arguments. AddrKeyValidator.validateAddressArgs(kwargs, "hrp"); AddrKeyValidator.validateAddressArgs>(kwargs, "net_ver"); - String hrp = kwargs['hrp']; - List netVerBytes = kwargs['net_ver']; + final String hrp = kwargs['hrp']; + final List netVerBytes = kwargs['net_ver']; /// Delegate the decoding process to a specialized P2PKH address decoder with HRP and network version. return BchP2PKHAddrDecoder() @@ -151,11 +152,12 @@ class BchP2SHAddrEncoder implements BlockchainAddressEncoder { /// Validate HRP and network version arguments. AddrKeyValidator.validateAddressArgs(kwargs, "hrp"); AddrKeyValidator.validateAddressArgs>(kwargs, "net_ver"); - String hrp = kwargs['hrp']; - List netVerBytes = kwargs['net_ver']; + final String hrp = kwargs['hrp']; + final List netVerBytes = kwargs['net_ver']; /// Validate and process the public key as a Secp256k1 key. - IPublicKey pubKeyObj = AddrKeyValidator.validateAndGetSecp256k1Key(pubKey); + final IPublicKey pubKeyObj = + AddrKeyValidator.validateAndGetSecp256k1Key(pubKey); /// Encode the P2SH address using Bech32 encoding. return BchBech32Encoder.encode( diff --git a/lib/bip/address/p2tr_addr.dart b/lib/bip/address/p2tr_addr.dart index 35b3070..2cbc313 100644 --- a/lib/bip/address/p2tr_addr.dart +++ b/lib/bip/address/p2tr_addr.dart @@ -39,7 +39,7 @@ class P2TRUtils { /// - dataBytes: The data bytes to be hashed. /// /// Returns: - /// A List representing the tagged hash. + /// A `List` representing the tagged hash. /// /// Throws: /// - ArgumentException if the tag is not a string or bytes. @@ -47,7 +47,7 @@ class P2TRUtils { if (tag! is String && tag! is List) { throw const AddressConverterException("tag must be bytes or string"); } - List tagHash = + final List tagHash = tag is String ? QuickCrypto.sha256Hash(StringUtils.encode(tag)) : tag; return QuickCrypto.sha256Hash( List.from([...tagHash, ...tagHash, ...dataBytes])); @@ -61,7 +61,7 @@ class P2TRUtils { /// - pubKey: The public key for which to compute the TapTweak. /// /// Returns: - /// A List representing the TapTweak hash. + /// A `List` representing the TapTweak hash. static List hashTapTweak(ProjectiveECCPoint pubPoint) { return P2TRUtils.taggedHash( P2TRConst.tapTweakSHA256, @@ -93,7 +93,7 @@ class P2TRUtils { if (y.modPow(BigInt.two, p) != ySq) { throw const AddressConverterException("Unable to compute LiftX point"); } - BigInt result = (y & BigInt.one) == BigInt.zero ? y : p - y; + final BigInt result = (y & BigInt.one) == BigInt.zero ? y : p - y; return ProjectiveECCPoint( curve: Curves.curveSecp256k1, x: x, y: result, z: BigInt.one); } @@ -163,8 +163,8 @@ class P2TRUtils { // /// - pubKey: The public key to be tweaked. // /// // /// Returns: - // /// A List representing the tweaked public key for P2TR. - // static List tweakPublicKey(ProjectiveECCPoint pubPoint) { + // /// A `List` representing the tweaked public key for P2TR. + // static `List` tweakPublicKey(ProjectiveECCPoint pubPoint) { // final h = hashTapTweak(pubPoint); // final n = Curves.generatorSecp256k1 * BigintUtils.fromBytes(h); // final outPoint = liftX(pubPoint) + n; @@ -189,14 +189,14 @@ class P2TRAddrDecoder implements BlockchainAddressDecoder { /// This method decodes a P2TR address from the given input string using Bech32 encoding. /// It expects an optional map of keyword arguments, with the 'hrp' key specifying the /// Human-Readable Part (HRP) of the address. It validates the arguments, decodes the - /// address, checks the witness version, and returns the decoded address as a List. + /// address, checks the witness version, and returns the decoded address as a `List`. /// /// Parameters: /// - addr: The Bech32-encoded P2TR address to be decoded. /// - kwargs: Optional keyword arguments, with 'hrp' for the Human-Readable Part. /// /// Returns: - /// A List containing the decoded P2TR address bytes. + /// A `List` containing the decoded P2TR address bytes. /// /// Throws: /// - ArgumentException if the provided address has an incorrect witness version, @@ -222,7 +222,7 @@ class P2TRAddrDecoder implements BlockchainAddressDecoder { 'Invalid witness version (expected ${P2TRConst.witnessVer}, got $witVerGot)'); } - /// Return the decoded P2TR address as a List. + /// Return the decoded P2TR address as a `List`. return addrDecBytes; } } diff --git a/lib/bip/address/p2wpkh_addr.dart b/lib/bip/address/p2wpkh_addr.dart index 3158417..4359d1c 100644 --- a/lib/bip/address/p2wpkh_addr.dart +++ b/lib/bip/address/p2wpkh_addr.dart @@ -20,14 +20,14 @@ class P2WPKHAddrDecoder implements BlockchainAddressDecoder { /// This method decodes a P2WPKH address from the given input string using the Bech32 /// encoding. It expects an optional map of keyword arguments, with the 'hrp' key /// specifying the Human-Readable Part (HRP) of the address. It validates the arguments, - /// decodes the address, checks the witness version, and returns the decoded address as a List. + /// decodes the address, checks the witness version, and returns the decoded address as a `List`. /// /// Parameters: /// - addr: The Bech32-encoded P2WPKH address to be decoded. /// - kwargs: Optional keyword arguments, with 'hrp' for the Human-Readable Part. /// /// Returns: - /// A List containing the decoded P2WPKH address bytes. + /// A `List` containing the decoded P2WPKH address bytes. /// /// Throws: /// - FormatException if the provided address has an incorrect witness version. @@ -49,7 +49,7 @@ class P2WPKHAddrDecoder implements BlockchainAddressDecoder { 'Invalid witness version (expected ${P2WPKHAddrConst.witnessVer}, got $witVerGot)'); } - /// Return the decoded P2WPKH address as a List. + /// Return the decoded P2WPKH address as a `List`. return List.from(addrDecBytes); } } diff --git a/lib/bip/address/sol_addr.dart b/lib/bip/address/sol_addr.dart index ab65987..540495e 100644 --- a/lib/bip/address/sol_addr.dart +++ b/lib/bip/address/sol_addr.dart @@ -11,14 +11,14 @@ class SolAddrDecoder implements BlockchainAddressDecoder { /// /// This method decodes a Solana SOL address from the given Base58-encoded input string. /// It expects an optional map of keyword arguments. It decodes the address, validates - /// its byte length, and returns the decoded address as a List. + /// its byte length, and returns the decoded address as a `List`. /// /// Parameters: /// - addr: The Base58-encoded Solana SOL address to be decoded. /// - kwargs: Optional keyword arguments for customization (not used in this implementation). /// /// Returns: - /// A List containing the decoded Solana SOL address bytes. + /// A `List` containing the decoded Solana SOL address bytes. /// /// Throws: /// - FormatException if the decoded address has an incorrect byte length. @@ -31,7 +31,7 @@ class SolAddrDecoder implements BlockchainAddressDecoder { AddrDecUtils.validateBytesLength( addrDecBytes, Ed25519KeysConst.pubKeyByteLen); - /// Return the decoded address as a List. + /// Return the decoded address as a `List`. return List.from(addrDecBytes); } } @@ -40,7 +40,7 @@ class SolAddrDecoder implements BlockchainAddressDecoder { class SolAddrEncoder implements BlockchainAddressEncoder { /// Overrides the base class method to encode a public key as a Solana SOL address. /// - /// This method takes a public key as a List and an optional map of keyword + /// This method takes a public key as a `List` and an optional map of keyword /// arguments, although they are not used in this implementation. It validates /// and processes the public key as an Ed25519 key, then encodes it into a Solana /// SOL address using Base58 encoding. The resulting address is returned as a String. diff --git a/lib/bip/address/substrate_addr.dart b/lib/bip/address/substrate_addr.dart index a0b2211..14907e2 100644 --- a/lib/bip/address/substrate_addr.dart +++ b/lib/bip/address/substrate_addr.dart @@ -44,14 +44,14 @@ class SubstrateEd25519AddrDecoder implements BlockchainAddressDecoder { /// This method decodes a Substrate address from the given input string. It expects a /// map of optional keyword arguments, with the 'ss58_format' key specifying the expected /// SS58 format for the address. It validates the arguments, decodes the address, and returns - /// the decoded address as a List. + /// the decoded address as a `List`. /// /// Parameters: /// - addr: The address to be decoded. /// - kwargs: Optional keyword arguments (e.g., 'ss58_format') for customization. /// /// Returns: - /// A List containing the decoded address bytes. + /// A `List` containing the decoded address bytes. /// /// Throws: /// - FormatException if the provided address is not in the expected SS58 format. @@ -69,7 +69,7 @@ class SubstrateEd25519AddrDecoder implements BlockchainAddressDecoder { class SubstrateEd25519AddrEncoder implements BlockchainAddressEncoder { /// Encodes a public key into a Substrate address. /// - /// This method takes a public key as a List and an optional map of keyword + /// This method takes a public key as a `List` and an optional map of keyword /// arguments, with the 'ss58_format' key specifying the desired SS58 format for /// the address. It validates the arguments, encodes the public key, and returns /// the resulting Substrate address as a String. @@ -101,14 +101,14 @@ class SubstrateSr25519AddrDecoder implements BlockchainAddressDecoder { /// This method decodes a Substrate address from the given input string. It expects a /// map of optional keyword arguments, with the 'ss58_format' key specifying the expected /// SS58 format for the address. It validates the arguments, decodes the address, and returns - /// the decoded address as a List. + /// the decoded address as a `List`. /// /// Parameters: /// - addr: The address to be decoded. /// - kwargs: Optional keyword arguments (e.g., 'ss58_format') for customization. /// /// Returns: - /// A List containing the decoded address bytes. + /// A `List` containing the decoded address bytes. /// /// Throws: /// - FormatException if the provided address is not in the expected SS58 format. @@ -126,7 +126,7 @@ class SubstrateSr25519AddrDecoder implements BlockchainAddressDecoder { class SubstrateSr25519AddrEncoder implements BlockchainAddressEncoder { /// Encodes a public key into a Substrate address. /// - /// This method takes a public key as a List and an optional map of keyword + /// This method takes a public key as a `List` and an optional map of keyword /// arguments, with the 'ss58_format' key specifying the desired SS58 format for /// the address. It validates the arguments, encodes the public key, and returns /// the resulting Substrate address as a String. @@ -157,14 +157,14 @@ class SubstrateSecp256k1AddrDecoder implements BlockchainAddressDecoder { /// This method decodes a Substrate address from the given input string. It expects a /// map of optional keyword arguments, with the 'ss58_format' key specifying the expected /// SS58 format for the address. It validates the arguments, decodes the address, and returns - /// the decoded address as a List. + /// the decoded address as a `List`. /// /// Parameters: /// - addr: The address to be decoded. /// - kwargs: Optional keyword arguments (e.g., 'ss58_format') for customization. /// /// Returns: - /// A List containing the decoded address bytes. + /// A `List` containing the decoded address bytes. /// /// Throws: /// - FormatException if the provided address is not in the expected SS58 format. @@ -181,7 +181,7 @@ class SubstrateSecp256k1AddrDecoder implements BlockchainAddressDecoder { class SubstrateSecp256k1AddrEncoder implements BlockchainAddressEncoder { /// Encodes a public key into a Substrate address. /// - /// This method takes a public key as a List and an optional map of keyword + /// This method takes a public key as a `List` and an optional map of keyword /// arguments, with the 'ss58_format' key specifying the desired SS58 format for /// the address. It validates the arguments, encodes the public key, and returns /// the resulting Substrate address as a String. diff --git a/lib/bip/address/ton_addr.dart b/lib/bip/address/ton_addr.dart index eb40341..9b14f04 100644 --- a/lib/bip/address/ton_addr.dart +++ b/lib/bip/address/ton_addr.dart @@ -101,7 +101,7 @@ class TonAddressUtils { throw AddressConverterException("Invalid checksum", details: {"excepted": calcedCrc, "checksum": crc}); } - List flags = []; + final List flags = []; // Parse tag int tag = addr[0]; // bool isTestOnly = false; diff --git a/lib/bip/address/trx_addr.dart b/lib/bip/address/trx_addr.dart index 80eb060..8764f56 100644 --- a/lib/bip/address/trx_addr.dart +++ b/lib/bip/address/trx_addr.dart @@ -23,10 +23,10 @@ class TrxAddrDecoder implements BlockchainAddressDecoder { /// /// The `addr` parameter is the encoded Tron address to be decoded. /// The optional `kwargs` parameter allows for additional configuration. - /// Returns the decoded address as a List. + /// Returns the decoded address as a `List`. @override List decodeAddr(String addr, [Map kwargs = const {}]) { - List addrDec = Base58Decoder.checkDecode(addr); + final List addrDec = Base58Decoder.checkDecode(addr); final tronPrefix = BytesUtils.fromHexString(CoinsConf.tron.params.addrPrefix!); AddrDecUtils.validateBytesLength( @@ -59,7 +59,7 @@ class TrxAddrEncoder implements BlockchainAddressEncoder { /// A Tron address encoded as a Base58 string. @override String encodeKey(List pubKey, [Map kwargs = const {}]) { - String ethAddr = EthAddrEncoder().encodeKey(pubKey).substring(2); + final String ethAddr = EthAddrEncoder().encodeKey(pubKey).substring(2); return Base58Encoder.checkEncode(List.from([ ...BytesUtils.fromHexString(CoinsConf.tron.params.addrPrefix!), ...BytesUtils.fromHexString(ethAddr) diff --git a/lib/bip/address/xlm_addr.dart b/lib/bip/address/xlm_addr.dart index 9c015af..a3b99cc 100644 --- a/lib/bip/address/xlm_addr.dart +++ b/lib/bip/address/xlm_addr.dart @@ -157,7 +157,7 @@ class XlmAddrDecoder implements BlockchainAddressDecoder { /// Decode a Stellar (XLM) address and return the public key. /// - /// This method decodes a Stellar address and extracts the public key part, returning it as a List. + /// This method decodes a Stellar address and extracts the public key part, returning it as a `List`. /// /// - [addr]: The Stellar address to decode. /// - [kwargs]: A map of optional keyword arguments. @@ -193,7 +193,7 @@ class XlmAddrEncoder implements BlockchainAddressEncoder { /// Example usage: /// ```dart /// final encoder = XlmAddrEncoder(); - /// final publicKey = List.from([6, ...bytes]); // Replace 'bytes' with the actual public key bytes. + /// final publicKey = `List`.from([6, ...bytes]); // Replace 'bytes' with the actual public key bytes. /// final addr = encoder.encodeKey(publicKey, {'addr_type': XlmAddrTypes.pubKey}); /// ``` @override @@ -224,9 +224,9 @@ class XlmAddrEncoder implements BlockchainAddressEncoder { pubKey = [...pubKey, ...idBytes]; } - List payloadBytes = List.from([addrType.value, ...pubKey]); + final List payloadBytes = List.from([addrType.value, ...pubKey]); - List checksumBytes = _XlmAddrUtils.computeChecksum(payloadBytes); + final List checksumBytes = _XlmAddrUtils.computeChecksum(payloadBytes); return Base32Encoder.encodeNoPaddingBytes( List.from([...payloadBytes, ...checksumBytes])); } diff --git a/lib/bip/address/xmr_addr.dart b/lib/bip/address/xmr_addr.dart index 53b6819..a451dce 100644 --- a/lib/bip/address/xmr_addr.dart +++ b/lib/bip/address/xmr_addr.dart @@ -266,9 +266,9 @@ class XmrAddrDecoder implements BlockchainAddressDecoder { /// Decodes a Monero (XMR) address. /// /// Given an XMR address and optional decoding parameters specified in [kwargs], - /// this method decodes the XMR address and returns the result as a List. + /// this method decodes the XMR address and returns the result as a `List`. /// - /// If decoding parameters are provided, ensure that "net_ver" is a List + /// If decoding parameters are provided, ensure that "net_ver" is a `List` /// representing the network version bytes. /// /// Parameters: @@ -276,7 +276,7 @@ class XmrAddrDecoder implements BlockchainAddressDecoder { /// - kwargs: A map of optional decoding parameters, such as "net_ver." /// /// Returns: - /// A List containing the decoded address data. + /// A `List` containing the decoded address data. @override List decodeAddr(String addr, [Map kwargs = const {}]) { final List netVerBytes = @@ -302,7 +302,7 @@ class XmrAddrEncoder extends BlockchainAddressEncoder { /// Given a public key, view key, and optional encoding parameters specified in [kwargs], /// this method encodes the public keys as an XMR address and returns the result as a string. /// - /// Ensure that the "net_ver" and "pub_vkey" parameters are provided as List instances. + /// Ensure that the "net_ver" and "pub_vkey" parameters are provided as `List` instances. /// /// Parameters: /// - pubKey: The public key to be encoded. @@ -329,7 +329,7 @@ class XmrIntegratedAddrDecoder extends BlockchainAddressDecoder { /// Given an XMR address and optional decoding parameters specified in [kwargs], /// this method decodes the address to extract the public key and view key components. /// - /// Ensure that the "net_ver" and "payment_id" parameters are provided as List instances. + /// Ensure that the "net_ver" and "payment_id" parameters are provided as `List` instances. /// /// Parameters: /// - addr: The XMR address to be decoded. @@ -337,7 +337,7 @@ class XmrIntegratedAddrDecoder extends BlockchainAddressDecoder { /// and "payment_id" (payment ID bytes). /// /// Returns: - /// A List representing the decoded public key and view key components. + /// A `List` representing the decoded public key and view key components. @override List decodeAddr(String addr, [Map kwargs = const {}]) { final List netVerBytes = @@ -357,7 +357,7 @@ class XmrIntegratedAddrEncoder implements BlockchainAddressEncoder { /// Given a public key, view key, and optional encoding parameters specified in [kwargs], /// this method encodes the public keys as an XMR address and returns the result as a string. /// - /// Ensure that the "net_ver" and "pub_vkey", "payment_id" parameters are provided as List instances. + /// Ensure that the "net_ver" and "pub_vkey", "payment_id" parameters are provided as `List` instances. /// /// Parameters: /// - pubKey: The public key to be encoded. diff --git a/lib/bip/address/xrp_addr.dart b/lib/bip/address/xrp_addr.dart index f4655b3..2900a24 100644 --- a/lib/bip/address/xrp_addr.dart +++ b/lib/bip/address/xrp_addr.dart @@ -84,7 +84,7 @@ class XRPAddressUtils { "Invalid tag. Tag should be lower than 2^32 for Ripple X address"); } List addrBytes = [...xAddrPrefix, ...addrHash]; - List tagBytes = writeUint64LE(tag ?? 0); + final List tagBytes = writeUint64LE(tag ?? 0); addrBytes = [...addrBytes, tag == null ? 0 : 1, ...tagBytes]; return Base58Encoder.checkEncode(addrBytes, Base58Alphabets.ripple); } @@ -100,7 +100,7 @@ class XRPAddressUtils { /// throws ArgumentException if the decoded address has invalid length, prefix mismatch, or an invalid tag. static XRPXAddressDecodeResult decodeXAddress( String addr, List? prefix) { - List addrDecBytes = + final List addrDecBytes = Base58Decoder.checkDecode(addr, Base58Alphabets.ripple); AddrDecUtils.validateBytesLength( @@ -132,7 +132,7 @@ class XRPAddressUtils { List tagBytes = addrDecBytes .sublist(addrDecBytes.length - _XRPAddressConst.xAddressTagLength); - int tagFlag = tagBytes[0]; + final int tagFlag = tagBytes[0]; if (tagFlag != 0 && tagFlag != 1) { throw AddressConverterException( 'Invalid tag flag, tag flag should be 0 or 1 but got ${tagBytes[0]}'); @@ -318,7 +318,7 @@ class XrpAddrEncoder implements BlockchainAddressEncoder { /// ``` @override String encodeKey(List pubKey, [Map kwargs = const {}]) { - var publicType = kwargs["curve_type"] ?? EllipticCurveTypes.secp256k1; + final publicType = kwargs["curve_type"] ?? EllipticCurveTypes.secp256k1; if (publicType is! EllipticCurveTypes || (publicType != EllipticCurveTypes.secp256k1 && publicType != EllipticCurveTypes.ed25519)) { diff --git a/lib/bip/algorand/algorand.dart b/lib/bip/algorand/algorand.dart index 6e81310..be11d15 100644 --- a/lib/bip/algorand/algorand.dart +++ b/lib/bip/algorand/algorand.dart @@ -2,7 +2,7 @@ // for working with Algorand mnemonics, a critical component in the Algorand // blockchain ecosystem. -library algorand_mnemonic; +library; // Export statement for the entropy generator module. export 'mnemonic/algorand_entropy_generator.dart'; diff --git a/lib/bip/algorand/mnemonic/algorand_mnemonic.dart b/lib/bip/algorand/mnemonic/algorand_mnemonic.dart index fc96fe2..9f6fea5 100644 --- a/lib/bip/algorand/mnemonic/algorand_mnemonic.dart +++ b/lib/bip/algorand/mnemonic/algorand_mnemonic.dart @@ -54,8 +54,8 @@ class AlgorandMnemonicConst { /// Represents Algorand mnemonic phrases, extending the Bip39Mnemonic class. class AlgorandMnemonic extends Bip39Mnemonic { /// Constructs an AlgorandMnemonic instance from a string mnemonic. - AlgorandMnemonic.fromString(String mnemonic) : super.fromString(mnemonic); + AlgorandMnemonic.fromString(super.mnemonic) : super.fromString(); /// Constructs an AlgorandMnemonic instance from a list of mnemonic words. - AlgorandMnemonic.fromList(List mnemonic) : super.fromList(mnemonic); + AlgorandMnemonic.fromList(super.mnemonic) : super.fromList(); } diff --git a/lib/bip/algorand/mnemonic/algorand_mnemonic_decoder.dart b/lib/bip/algorand/mnemonic/algorand_mnemonic_decoder.dart index 919ec47..5a46e27 100644 --- a/lib/bip/algorand/mnemonic/algorand_mnemonic_decoder.dart +++ b/lib/bip/algorand/mnemonic/algorand_mnemonic_decoder.dart @@ -4,7 +4,7 @@ import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic_utils.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_decoder_base.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_ex.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Decodes Algorand mnemonics to obtain the corresponding entropy. class AlgorandMnemonicDecoder extends MnemonicDecoderBase { @@ -34,7 +34,7 @@ class AlgorandMnemonicDecoder extends MnemonicDecoderBase { final words = mnemonicObj.toList(); final wordsList = findLanguage(mnemonicObj).item1; - final wordIndexes = [for (var w in words) wordsList.getWordIdx(w)]; + final wordIndexes = [for (final w in words) wordsList.getWordIdx(w)]; final entropyList = AlgorandMnemonicUtils.convertBits( wordIndexes.getRange(0, words.length - 1).toList(), 11, 8); assert(entropyList != null); diff --git a/lib/bip/algorand/mnemonic/algorand_mnemonic_encoder.dart b/lib/bip/algorand/mnemonic/algorand_mnemonic_encoder.dart index 50406b3..bdd63c2 100644 --- a/lib/bip/algorand/mnemonic/algorand_mnemonic_encoder.dart +++ b/lib/bip/algorand/mnemonic/algorand_mnemonic_encoder.dart @@ -4,7 +4,7 @@ import 'package:blockchain_utils/bip/algorand/mnemonic/algorand_mnemonic_utils.d import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic_utils.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_encoder_base.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/helper/helper.dart'; /// Algorand mnemonic encoder class. @@ -39,6 +39,6 @@ class AlgorandMnemonicEncoder extends MnemonicEncoderBase { /// find words at index List _indexesToWords(List indexes) { - return [for (var idx in indexes) wordsList.getWordAtIdx(idx)]; + return [for (final idx in indexes) wordsList.getWordAtIdx(idx)]; } } diff --git a/lib/bip/algorand/mnemonic/algorand_mnemonic_generator.dart b/lib/bip/algorand/mnemonic/algorand_mnemonic_generator.dart index 594fc7a..e3a0a0c 100644 --- a/lib/bip/algorand/mnemonic/algorand_mnemonic_generator.dart +++ b/lib/bip/algorand/mnemonic/algorand_mnemonic_generator.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/algorand/mnemonic/algorand_entropy_generato import 'package:blockchain_utils/bip/algorand/mnemonic/algorand_mnemonic.dart'; import 'package:blockchain_utils/bip/algorand/mnemonic/algorand_mnemonic_encoder.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Constants related to Algorand mnemonic generation. /// diff --git a/lib/bip/algorand/mnemonic/algorand_mnemonic_utils.dart b/lib/bip/algorand/mnemonic/algorand_mnemonic_utils.dart index aae2d2a..af9942d 100644 --- a/lib/bip/algorand/mnemonic/algorand_mnemonic_utils.dart +++ b/lib/bip/algorand/mnemonic/algorand_mnemonic_utils.dart @@ -6,13 +6,13 @@ class AlgorandMnemonicUtils { /// Computes the checksum for the given [dataBytes] using SHA-512/256. /// /// The [dataBytes] parameter should be the data bytes for which the checksum - /// needs to be computed. The method returns a [List] containing the + /// needs to be computed. The method returns a [`List`] containing the /// computed checksum. /// /// Example usage: /// /// ```dart - /// final data = List.from([1, 2, 3, 4, 5]); + /// final data = `List`.from([1, 2, 3, 4, 5]); /// final checksum = AlgorandMnemonicUtils.computeChecksum(data); /// ``` static List computeChecksum(List dataBytes) { @@ -30,7 +30,7 @@ class AlgorandMnemonicUtils { /// Example usage: /// /// ```dart - /// final data = List.from([1, 2, 3, 4, 5]); + /// final data = `List`.from([1, 2, 3, 4, 5]); /// final checksumWordIndex = AlgorandMnemonicUtils.computeChecksumWordIndex(data); /// ``` /// @@ -53,19 +53,19 @@ class AlgorandMnemonicUtils { /// It returns a list of integers where every number is less than 2^toBits. /// /// Args: - /// data (List): Data to be converted + /// data (`List`): Data to be converted /// fromBits (int) : Number of bits to start from /// toBits (int) : Number of bits to end with /// /// Returns: - /// List: List of converted values, null in case of errors + /// `List`: List of converted values, null in case of errors static List? convertBits(List data, int fromBits, int toBits) { - int maxOutVal = (1 << toBits) - 1; + final int maxOutVal = (1 << toBits) - 1; int acc = 0; int bits = 0; - List ret = []; + final List ret = []; - for (var value in data) { + for (final value in data) { if (value < 0 || (value >> fromBits) > 0) { return null; } diff --git a/lib/bip/bip.dart b/lib/bip/bip.dart new file mode 100644 index 0000000..76f114b --- /dev/null +++ b/lib/bip/bip.dart @@ -0,0 +1,42 @@ +library; + +/// Export for cryptocurrency address encoding utilities. +export 'address/encoders.dart'; + +/// Export for cryptocurrency address decoding utilities. +export 'address/decoders.dart'; + +/// Export for Algorand blockchain-specific utilities. +export 'algorand/algorand.dart'; + +/// Export for BIP (Bitcoin Improvement Proposals) utilities. +export 'bip/bip.dart'; + +/// Export for Cardano blockchain-specific utilities. +export 'cardano/cardano.dart'; + +/// Export for Electrum wallet and mnemonic utilities. +export 'electrum/electrum.dart'; + +/// Export for Monero-specific utilities, including mnemonics. +export 'monero/monero.dart'; + +/// Export for Substrate blockchain-specific utilities. +export 'substrate/substrate.dart'; + +/// Export for Wallet Import Format (WIF) encoding and decoding utilities. +export 'wif/wif.dart'; + +/// Exports modules related to ECC (Elliptic Curve Cryptography) in the context of BIP. +export 'ecc/bip_ecc.dart'; + +/// Exports utility functions related to TON mnemonic. +export 'ton/ton.dart'; + +/// Exports utility functions related to mnemonic. +export 'mnemonic/mnemonic.dart'; + +/// config of every bip coin +export 'coin_conf/config.dart'; + +export 'slip/slip.dart'; diff --git a/lib/bip/bip/bip.dart b/lib/bip/bip/bip.dart index 85a76d0..e0805df 100644 --- a/lib/bip/bip/bip.dart +++ b/lib/bip/bip/bip.dart @@ -1,6 +1,6 @@ /// The 'bip' library serves as a comprehensive collection of libraries for working /// with various Bitcoin Improvement Proposals (BIPs) in the realm of cryptocurrency. -library bip; +library; /// Export statement for the 'bip32' library, providing tools for working with BIP-32, /// which defines hierarchical deterministic wallets and key derivation. @@ -35,3 +35,5 @@ export 'bip86/bip86.dart'; /// Export statement for the 'conf/bip_config' library, which centralizes coin-related /// definitions, coin names, parameters, and coin configuration information for different BIPs. export 'conf/bip_config.dart'; + +export 'types/types.dart'; diff --git a/lib/bip/bip/bip32/base/bip32_base.dart b/lib/bip/bip/bip32/base/bip32_base.dart index ae83cb7..3d5888c 100644 --- a/lib/bip/bip/bip32/base/bip32_base.dart +++ b/lib/bip/bip/bip32/base/bip32_base.dart @@ -7,7 +7,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/ecc/curve/elliptic_curve_types.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/helper/helper.dart'; import 'ibip32_mst_key_generator.dart'; @@ -44,7 +44,7 @@ abstract class Bip32Base { Bip32KeyDeserializer.deserializeKey(exKeyStr, keyNetVer: keyNetVer); final keyBytes = deserKey.keyBytes; - Bip32KeyData keyData = deserKey.keyData; + final Bip32KeyData keyData = deserKey.keyData; final isPublic = deserKey.isPublic; if (keyData.depth.depth == 0) { diff --git a/lib/bip/bip/bip32/bip32.dart b/lib/bip/bip/bip32/bip32.dart index a734ec1..3a1021f 100644 --- a/lib/bip/bip/bip32/bip32.dart +++ b/lib/bip/bip/bip32/bip32.dart @@ -1,7 +1,7 @@ /// The 'bip32' library provides a comprehensive set of tools for working with /// BIP-32 Hierarchical Deterministic Wallets, which are commonly used in /// cryptocurrencies to manage and derive keys. -library bip32; +library; export 'base/bip32_base.dart'; export 'base/ibip32_key_derivator.dart'; diff --git a/lib/bip/bip/bip32/bip32_ex.dart b/lib/bip/bip/bip32/bip32_ex.dart index 5768838..aba8b71 100644 --- a/lib/bip/bip/bip32/bip32_ex.dart +++ b/lib/bip/bip/bip32/bip32_ex.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// The `Bip32KeyError` class represents an exception that can be thrown in case /// of a key-related error during Bip32 key operations. It allows you to provide @@ -6,8 +6,7 @@ import 'package:blockchain_utils/exception/exception.dart'; /// can access the error message using the `toString()` method or the `message` /// property, if provided. class Bip32KeyError extends BlockchainUtilsException { - const Bip32KeyError(String message, {Map? details}) - : super(message, details: details); + const Bip32KeyError(super.message, {super.details}); } /// The `Bip32PathError` class represents an exception that can be thrown in case @@ -16,6 +15,5 @@ class Bip32KeyError extends BlockchainUtilsException { /// an optional error message to describe the specific issue. To access the error /// message, use the `toString()` method or the `message` property, if provided. class Bip32PathError extends BlockchainUtilsException { - const Bip32PathError(String message, {Map? details}) - : super(message, details: details); + const Bip32PathError(super.message, {super.details}); } diff --git a/lib/bip/bip/bip32/bip32_key_data.dart b/lib/bip/bip/bip32/bip32_key_data.dart index e129d72..ff68253 100644 --- a/lib/bip/bip/bip32/bip32_key_data.dart +++ b/lib/bip/bip/bip32/bip32_key_data.dart @@ -1,6 +1,6 @@ import 'dart:typed_data'; import 'package:blockchain_utils/utils/utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Class container for BIP32 key data constants. class Bip32KeyDataConst { diff --git a/lib/bip/bip/bip32/bip32_key_net_ver.dart b/lib/bip/bip/bip32/bip32_key_net_ver.dart index f3696ff..b683b25 100644 --- a/lib/bip/bip/bip32/bip32_key_net_ver.dart +++ b/lib/bip/bip/bip32/bip32_key_net_ver.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/helper/helper.dart'; /// Contains constants related to BIP32 key network versions. diff --git a/lib/bip/bip/bip32/bip32_key_ser.dart b/lib/bip/bip/bip32/bip32_key_ser.dart index 1fca414..4cd5fe6 100644 --- a/lib/bip/bip/bip32/bip32_key_ser.dart +++ b/lib/bip/bip/bip32/bip32_key_ser.dart @@ -24,7 +24,7 @@ class _Bip32KeySerializer { /// Serialize the specified key bytes. static String serialize( List keyBytes, Bip32KeyData keyData, List keyNetVerBytes) { - List serKey = List.from([ + final List serKey = List.from([ ...keyNetVerBytes, ...keyData.depth.toBytes(), ...keyData.parentFingerPrint.toBytes(), diff --git a/lib/bip/bip/bip32/bip32_path.dart b/lib/bip/bip/bip32/bip32_path.dart index 5364ace..cda8ade 100644 --- a/lib/bip/bip/bip32/bip32_path.dart +++ b/lib/bip/bip/bip32/bip32_path.dart @@ -136,7 +136,7 @@ class Bip32PathParser { isAbsolute = true; } - List parsedElems = pathElems.map(_parseElem).toList(); + final List parsedElems = pathElems.map(_parseElem).toList(); return Bip32Path(elems: parsedElems, isAbsolute: isAbsolute); } @@ -145,14 +145,14 @@ class Bip32PathParser { /// [pathElem] is the path element to be parsed. static Bip32KeyIndex _parseElem(String pathElem) { pathElem = pathElem.trim(); - bool isHardened = Bip32PathConst.hardenedChars + final bool isHardened = Bip32PathConst.hardenedChars .where((element) => pathElem.endsWith(element)) .isNotEmpty; if (isHardened) { pathElem = pathElem.substring(0, pathElem.length - 1); } - bool isNumeric = int.tryParse(pathElem) != null; + final bool isNumeric = int.tryParse(pathElem) != null; if (!isNumeric) { throw Bip32PathError("Invalid path element ($pathElem)"); } diff --git a/lib/bip/bip/bip32/khalow/bip32_kholaw_ed25519.dart b/lib/bip/bip/bip32/khalow/bip32_kholaw_ed25519.dart index 05c11ad..58ef0af 100644 --- a/lib/bip/bip/bip32/khalow/bip32_kholaw_ed25519.dart +++ b/lib/bip/bip/bip32/khalow/bip32_kholaw_ed25519.dart @@ -23,15 +23,11 @@ import 'bip32_kholaw_ed25519_key_derivator.dart'; class Bip32KholawEd25519 extends Bip32Base { /// Private constructor for creating an instance with specified parameters. Bip32KholawEd25519._({ - required Bip32KeyData keyData, - required Bip32KeyNetVersions keyNetVer, - required List? privKey, - required List? pubKey, - }) : super( - keyData: keyData, - keyNetVer: keyNetVer, - privKey: privKey, - pubKey: pubKey); + required super.keyData, + required super.keyNetVer, + required super.privKey, + required super.pubKey, + }); /// Creates a Bip32 key pair from a private key. Bip32KholawEd25519.fromPrivateKey(List privKey, @@ -39,14 +35,12 @@ class Bip32KholawEd25519 extends Bip32Base { : super.fromPrivateKey(privKey, keyData, keyNetVer); /// Creates a Bip32 key pair from an extended key. - Bip32KholawEd25519.fromExtendedKey(String exKeyStr, - [Bip32KeyNetVersions? keyNetVer]) - : super.fromExtendedKey(exKeyStr, keyNetVer); + Bip32KholawEd25519.fromExtendedKey(super.exKeyStr, [super.keyNetVer]) + : super.fromExtendedKey(); /// Creates a Bip32 key pair from a seed. - Bip32KholawEd25519.fromSeed(List seedBytes, - [Bip32KeyNetVersions? keyNetVer]) - : super.fromSeed(seedBytes, keyNetVer); + Bip32KholawEd25519.fromSeed(super.seedBytes, [super.keyNetVer]) + : super.fromSeed(); /// Creates a Bip32 key pair from a public key. Bip32KholawEd25519.fromPublicKey(List pubkey, 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 0bc5f03..a505248 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 @@ -31,20 +31,21 @@ class Bip32KholawEd25519KeyDerivator /// - [curve]: The elliptic curve type used for the key derivation. /// /// Returns: - /// - The new left part of the private key as a List. + /// - The new left part of the private key as a `List`. /// /// Throws: /// - [Bip32KeyError]: If the computed child key is not valid, indicating a very unlucky index. @override List newPrivateKeyLeftPart( List zlBytes, List klBytes, EllipticCurveTypes curve) { - BigInt zlInt = + final BigInt zlInt = BigintUtils.fromBytes(zlBytes.sublist(0, 28), byteOrder: Endian.little); - BigInt klInt = BigintUtils.fromBytes(klBytes, byteOrder: Endian.little); + final BigInt klInt = + BigintUtils.fromBytes(klBytes, byteOrder: Endian.little); final EDPoint generator = EllipticCurveGetter.generatorFromType(curve) as EDPoint; - BigInt prvlInt = (zlInt * BigInt.from(8)) + klInt; + final BigInt prvlInt = (zlInt * BigInt.from(8)) + klInt; if (prvlInt % generator.order! == BigInt.zero) { throw const Bip32KeyError( 'Computed child key is not valid, very unlucky index'); @@ -57,7 +58,7 @@ class Bip32KholawEd25519KeyDerivator /// Computes the new right part of the private key based on ZR bytes and KR bytes. /// - /// This method adds ZR and KR, taking the result modulo 2^256, and returns it as a List. + /// This method adds ZR and KR, taking the result modulo 2^256, and returns it as a `List`. /// The resulting bytes are then converted to match the format of a private key. /// /// Parameters: @@ -65,12 +66,14 @@ class Bip32KholawEd25519KeyDerivator /// - [krBytes]: The KR bytes, representing part of the private key. /// /// Returns: - /// - The new right part of the private key as a List. + /// - The new right part of the private key as a `List`. @override List newPrivateKeyRightPart(List zrBytes, List krBytes) { - BigInt zrInt = BigintUtils.fromBytes(zrBytes, byteOrder: Endian.little); - BigInt kprInt = BigintUtils.fromBytes(krBytes, byteOrder: Endian.little); - BigInt krInt = (zrInt + kprInt) % (BigInt.one << 256); + final BigInt zrInt = + BigintUtils.fromBytes(zrBytes, byteOrder: Endian.little); + final BigInt kprInt = + BigintUtils.fromBytes(krBytes, byteOrder: Endian.little); + final BigInt krInt = (zrInt + kprInt) % (BigInt.one << 256); final tobytes = BigintUtils.toBytes(krInt, order: Endian.little, length: Ed25519KholawKeysConst.privKeyByteLen ~/ 2); @@ -94,7 +97,7 @@ class Bip32KholawEd25519KeyDerivator @override EDPoint newPublicKeyPoint(Bip32PublicKey pubKey, List zlBytes) { assert(pubKey.point is EDPoint); - BigInt zlInt = + final BigInt zlInt = BigintUtils.fromBytes(zlBytes.sublist(0, 28), byteOrder: Endian.little); final EDPoint generator = EllipticCurveGetter.generatorFromType(pubKey.curveType) as EDPoint; 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 ec49a77..6359294 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 @@ -30,16 +30,16 @@ abstract class Bip32KholawEd25519KeyDerivatorBase Tuple, List> ckdPriv(Bip32PrivateKey privKey, Bip32PublicKey pubKey, Bip32KeyIndex index, EllipticCurveTypes type) { /// Serialize the 'index' to bytes. - List indexBytes = serializeIndex(index); + final List indexBytes = serializeIndex(index); /// Get the chain code bytes from the 'privKey'. List chainCodeBytes = privKey.chainCode.toBytes(); /// Extract raw private key bytes from 'privKey'. - List privKeyBytes = privKey.raw; + final List privKeyBytes = privKey.raw; /// Extract compressed public key bytes from 'pubKey' and remove the compression flag. - List pubKeyBytes = pubKey.compressed.sublist(1); + final List pubKeyBytes = pubKey.compressed.sublist(1); List zBytes; if (index.isHardened) { @@ -62,9 +62,11 @@ abstract class Bip32KholawEd25519KeyDerivatorBase /// Compute left and right part of private key const hmacHalfLen = QuickCrypto.hmacSha512DigestSize ~/ 2; - List pLBytes = newPrivateKeyLeftPart(zBytes.sublist(0, hmacHalfLen), - privKeyBytes.sublist(0, hmacHalfLen), type); - List pRBytes = newPrivateKeyRightPart( + final List pLBytes = newPrivateKeyLeftPart( + zBytes.sublist(0, hmacHalfLen), + privKeyBytes.sublist(0, hmacHalfLen), + type); + final List pRBytes = newPrivateKeyRightPart( zBytes.sublist(hmacHalfLen), privKeyBytes.sublist(hmacHalfLen)); /// Return the child private key bytes and the updated chain code. @@ -78,23 +80,23 @@ abstract class Bip32KholawEd25519KeyDerivatorBase Tuple, List> ckdPub( Bip32PublicKey pubKey, Bip32KeyIndex index, EllipticCurveTypes type) { /// Serialize the 'index' to bytes. - List indexBytes = serializeIndex(index); + final List indexBytes = serializeIndex(index); /// Get the chain code bytes from the 'pubKey'. List chainCodeBytes = pubKey.chainCode.toBytes(); /// Extract compressed public key bytes from 'pubKey' and remove the compression flag. - List pubKeyBytes = pubKey.compressed.sublist(1); + final List pubKeyBytes = pubKey.compressed.sublist(1); /// Compute 'Z' and update the chain code. - List zBytes = QuickCrypto.hmacSha512Hash( + final List zBytes = QuickCrypto.hmacSha512Hash( chainCodeBytes, List.from([0x02, ...pubKeyBytes, ...indexBytes])); chainCodeBytes = QuickCrypto.hmacSha512HashHalves(chainCodeBytes, List.from([0x03, ...pubKeyBytes, ...indexBytes])).item2; /// Compute the new public key point based on 'pubKey' and 'zBytes'. const hmacHalfLen = QuickCrypto.hmacSha512DigestSize ~/ 2; - EDPoint newPubKeyPoint = + final EDPoint newPubKeyPoint = newPublicKeyPoint(pubKey, zBytes.sublist(0, hmacHalfLen)); /// Check if the new public key point is the identity point (0, 1). 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 97d2089..e60cdd0 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 @@ -1,7 +1,7 @@ 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/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/utils/utils.dart'; /// Constants for generating master keys for Bip32KholawEd25519 keys. @@ -96,7 +96,7 @@ class Bip32KholawEd25519MstKeyGenerator implements IBip32MstKeyGenerator { /// Note: This method is called within the `generateFromSeed` method to prepare /// the master key bits. static List _tweakMasterKeyBits(List keyBytes) { - List keyBytesList = keyBytes.toList(); + final List keyBytesList = keyBytes.toList(); // Clear the lowest 3 bits of the first byte of kL keyBytesList[0] = keyBytesList[0] & 0xF8; // Clear the highest bit of the last byte of kL diff --git a/lib/bip/bip/bip32/slip10/bip32_slip10_ed25519.dart b/lib/bip/bip/bip32/slip10/bip32_slip10_ed25519.dart index 0d6deae..5e0ab23 100644 --- a/lib/bip/bip/bip32/slip10/bip32_slip10_ed25519.dart +++ b/lib/bip/bip/bip32/slip10/bip32_slip10_ed25519.dart @@ -28,20 +28,14 @@ import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; class Bip32Slip10Ed25519 extends Bip32Base { /// constructor for creating an instance with provided key data. Bip32Slip10Ed25519( - {required Bip32KeyData keyData, - required Bip32KeyNetVersions keyNetVer, - required List? privKey, - required List? pubKey}) - : super( - keyData: keyData, - keyNetVer: keyNetVer, - privKey: privKey, - pubKey: pubKey); + {required super.keyData, + required super.keyNetVer, + required super.privKey, + required super.pubKey}); /// constructor for creating a key from a seed. - Bip32Slip10Ed25519.fromSeed(List seedBytes, - [Bip32KeyNetVersions? keyNetVer]) - : super.fromSeed(seedBytes, keyNetVer); + Bip32Slip10Ed25519.fromSeed(super.seedBytes, [super.keyNetVer]) + : super.fromSeed(); /// constructor for creating a key from a private key. Bip32Slip10Ed25519.fromPrivateKey(List privKey, @@ -54,9 +48,8 @@ class Bip32Slip10Ed25519 extends Bip32Base { : super.fromPublicKey(pubkey, keyData, keyNetVer); /// constructor for creating a key from an extended key string. - Bip32Slip10Ed25519.fromExtendedKey(String exKeyStr, - [Bip32KeyNetVersions? keyNetVer]) - : super.fromExtendedKey(exKeyStr, keyNetVer); + Bip32Slip10Ed25519.fromExtendedKey(super.exKeyStr, [super.keyNetVer]) + : super.fromExtendedKey(); /// Derives a child key from the current key, based on the provided index. /// diff --git a/lib/bip/bip/bip32/slip10/bip32_slip10_ed25519_blake2b.dart b/lib/bip/bip/bip32/slip10/bip32_slip10_ed25519_blake2b.dart index 0384f71..20ef349 100644 --- a/lib/bip/bip/bip32/slip10/bip32_slip10_ed25519_blake2b.dart +++ b/lib/bip/bip/bip32/slip10/bip32_slip10_ed25519_blake2b.dart @@ -1,5 +1,4 @@ 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/curve/elliptic_curve_types.dart'; import 'bip32_slip10_ed25519.dart'; @@ -22,35 +21,28 @@ import 'bip32_slip10_ed25519.dart'; class Bip32Slip10Ed25519Blake2b extends Bip32Slip10Ed25519 { /// constructor for creating an instance with provided key data. Bip32Slip10Ed25519Blake2b( - {required Bip32KeyData keyData, - required Bip32KeyNetVersions keyNetVer, - required List? privKey, - required List? pubKey}) - : super( - keyData: keyData, - keyNetVer: keyNetVer, - pubKey: pubKey, - privKey: privKey); + {required super.keyData, + required super.keyNetVer, + required super.privKey, + required super.pubKey}); /// constructor for creating a key from a seed. - Bip32Slip10Ed25519Blake2b.fromSeed(List seedBytes, - [Bip32KeyNetVersions? keyNetVer]) - : super.fromSeed(seedBytes, keyNetVer); + Bip32Slip10Ed25519Blake2b.fromSeed(super.seedBytes, [super.keyNetVer]) + : super.fromSeed(); /// constructor for creating a key from a private key. - Bip32Slip10Ed25519Blake2b.fromExtendedKey(String exKeyStr, - [Bip32KeyNetVersions? keyNetVer]) - : super.fromExtendedKey(exKeyStr, keyNetVer); + Bip32Slip10Ed25519Blake2b.fromExtendedKey(super.exKeyStr, [super.keyNetVer]) + : super.fromExtendedKey(); /// constructor for creating a key from a public key. - Bip32Slip10Ed25519Blake2b.fromPrivateKey(List privKey, - {Bip32KeyData? keyData, Bip32KeyNetVersions? keyNetVer}) - : super.fromPrivateKey(privKey, keyData: keyData, keyNetVer: keyNetVer); + Bip32Slip10Ed25519Blake2b.fromPrivateKey(super.privKey, + {super.keyData, super.keyNetVer}) + : super.fromPrivateKey(); /// constructor for creating a key from an extended key string. - Bip32Slip10Ed25519Blake2b.fromPublicKey(List pubkey, - {Bip32KeyData? keyData, Bip32KeyNetVersions? keyNetVer}) - : super.fromPublicKey(pubkey, keyData: keyData, keyNetVer: keyNetVer); + Bip32Slip10Ed25519Blake2b.fromPublicKey(super.pubkey, + {super.keyData, super.keyNetVer}) + : super.fromPublicKey(); /// Returns the curve type Ed25519-blake2b. @override 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 1bf8518..10420dd 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 @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/bip/bip32/base/ibip32_mst_key_generator.dar 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/exception/exceptions.dart'; import 'package:blockchain_utils/utils/utils.dart'; /// Constants used by the Slip-10-based master key generator. diff --git a/lib/bip/bip/bip32/slip10/bip32_slip10_nist256p1.dart b/lib/bip/bip/bip32/slip10/bip32_slip10_nist256p1.dart index 331d22c..fe4a9d2 100644 --- a/lib/bip/bip/bip32/slip10/bip32_slip10_nist256p1.dart +++ b/lib/bip/bip/bip32/slip10/bip32_slip10_nist256p1.dart @@ -27,25 +27,18 @@ import 'bip32_slip10_key_derivator.dart'; /// working with this curve, such as key derivation and management. class Bip32Slip10Nist256p1 extends Bip32Base { Bip32Slip10Nist256p1._( - {required Bip32KeyData keyData, - required Bip32KeyNetVersions keyNetVer, - required List? privKey, - required List? pubKey}) - : super( - keyData: keyData, - keyNetVer: keyNetVer, - privKey: privKey, - pubKey: pubKey); + {required super.keyData, + required super.keyNetVer, + required super.privKey, + required super.pubKey}); /// constructor for creating a key from a seed. - Bip32Slip10Nist256p1.fromSeed(List seedBytes, - [Bip32KeyNetVersions? keyNetVer]) - : super.fromSeed(seedBytes, keyNetVer); + Bip32Slip10Nist256p1.fromSeed(super.seedBytes, [super.keyNetVer]) + : super.fromSeed(); /// constructor for creating a key from an extended key string. - Bip32Slip10Nist256p1.fromExtendedKey(String exKeyStr, - [Bip32KeyNetVersions? keyNetVer]) - : super.fromExtendedKey(exKeyStr, keyNetVer); + Bip32Slip10Nist256p1.fromExtendedKey(super.exKeyStr, [super.keyNetVer]) + : super.fromExtendedKey(); /// constructor for creating a key from a private key. Bip32Slip10Nist256p1.fromPrivateKey(List privKey, diff --git a/lib/bip/bip/bip32/slip10/bip32_slip10_secp256k1.dart b/lib/bip/bip/bip32/slip10/bip32_slip10_secp256k1.dart index 26038b1..686f858 100644 --- a/lib/bip/bip/bip32/slip10/bip32_slip10_secp256k1.dart +++ b/lib/bip/bip/bip32/slip10/bip32_slip10_secp256k1.dart @@ -27,20 +27,14 @@ import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; class Bip32Slip10Secp256k1 extends Bip32Base { /// constructor for creating an instance with provided key data. Bip32Slip10Secp256k1._( - {required Bip32KeyData keyData, - required Bip32KeyNetVersions keyNetVer, - required List? privKey, - required List? pubKey}) - : super( - keyData: keyData, - keyNetVer: keyNetVer, - privKey: privKey, - pubKey: pubKey); + {required super.keyData, + required super.keyNetVer, + required super.privKey, + required super.pubKey}); /// constructor for creating a key from a seed. - Bip32Slip10Secp256k1.fromSeed(List seedBytes, - [Bip32KeyNetVersions? keyNetVer]) - : super.fromSeed(seedBytes, keyNetVer); + Bip32Slip10Secp256k1.fromSeed(super.seedBytes, [super.keyNetVer]) + : super.fromSeed(); /// constructor for creating a key from a public key. Bip32Slip10Secp256k1.fromPublicKey(List pubkey, @@ -53,9 +47,8 @@ class Bip32Slip10Secp256k1 extends Bip32Base { : super.fromPrivateKey(privKey, keyData, keyNetVer); /// constructor for creating a key from an extended key string. - Bip32Slip10Secp256k1.fromExtendedKey(String exKeyStr, - [Bip32KeyNetVersions? keyNetVer]) - : super.fromExtendedKey(exKeyStr, keyNetVer); + Bip32Slip10Secp256k1.fromExtendedKey(super.exKeyStr, [super.keyNetVer]) + : super.fromExtendedKey(); /// Returns the curve type, SECP256K1. @override diff --git a/lib/bip/bip/bip38/bip38.dart b/lib/bip/bip/bip38/bip38.dart index 16e5d83..6f2cac1 100644 --- a/lib/bip/bip/bip38/bip38.dart +++ b/lib/bip/bip/bip38/bip38.dart @@ -1,6 +1,6 @@ /// The 'bip38' library provides tools for working with BIP-38, a standard for /// encrypting and decrypting private keys in a human-readable format. -library bip38; +library; /// Export statement for BIP-38 address-related functions and utilities. export 'bip38_addr.dart'; diff --git a/lib/bip/bip/bip38/bip38_addr.dart b/lib/bip/bip/bip38/bip38_addr.dart index 7fd55af..07aa54a 100644 --- a/lib/bip/bip/bip38/bip38_addr.dart +++ b/lib/bip/bip/bip38/bip38_addr.dart @@ -53,6 +53,7 @@ */ import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; +import 'package:blockchain_utils/bip/bip/types/types.dart'; import 'package:blockchain_utils/bip/coin_conf/constant/coins_conf.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; import 'package:blockchain_utils/utils/utils.dart'; @@ -79,7 +80,7 @@ class Bip38Addr { /// - [pubKey]: The public key for which the address hash is calculated. /// - [pubKeyMode]: The public key mode that specifies the type of address /// encoding. - /// - Returns: A List representing the calculated address hash. + /// - Returns: A `List` representing the calculated address hash. static List addressHash(List pubKey, PubKeyModes pubKeyMode) { final address = P2PKHAddrEncoder().encodeKey(pubKey, { "net_ver": CoinsConf.bitcoinMainNet.params.p2pkhNetVer!, diff --git a/lib/bip/bip/bip38/bip38_base.dart b/lib/bip/bip/bip38/bip38_base.dart index 4104419..7c8a5ba 100644 --- a/lib/bip/bip/bip38/bip38_base.dart +++ b/lib/bip/bip/bip38/bip38_base.dart @@ -1,5 +1,5 @@ -import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:blockchain_utils/bip/bip/bip38/bip38_no_ec.dart'; +import 'package:blockchain_utils/bip/bip/types/types.dart'; import 'bip38_ec.dart'; import 'package:blockchain_utils/utils/utils.dart'; @@ -68,7 +68,7 @@ class Bip38Decrypter { /// /// - [privKeyEnc]: The BIP38-encrypted Bitcoin private key. /// - [passphrase]: The passphrase for decryption. - /// - Returns: A tuple (pair) containing the decrypted private key as a List + /// - Returns: A tuple (pair) containing the decrypted private key as a `List` /// and the selected public key mode (compressed or uncompressed). static Tuple, PubKeyModes> decryptNoEc( String privKeyEnc, String passphrase) { @@ -84,7 +84,7 @@ class Bip38Decrypter { /// /// - [privKeyEnc]: The BIP38-encrypted Bitcoin private key. /// - [passphrase]: The passphrase for decryption. - /// - Returns: A tuple (pair) containing the decrypted private key as a List + /// - Returns: A tuple (pair) containing the decrypted private key as a `List` /// and the selected public key mode (compressed or uncompressed). static Tuple, PubKeyModes> decryptEc( String privKeyEnc, String passphrase) { diff --git a/lib/bip/bip/bip38/bip38_ec.dart b/lib/bip/bip/bip38/bip38_ec.dart index d7fd9ad..75bc53c 100644 --- a/lib/bip/bip/bip38/bip38_ec.dart +++ b/lib/bip/bip/bip38/bip38_ec.dart @@ -1,15 +1,15 @@ import 'dart:typed_data'; import 'package:blockchain_utils/base58/base58.dart'; +import 'package:blockchain_utils/bip/bip/types/types.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/crypto/crypto/cdsa/curve/curves.dart'; import 'package:blockchain_utils/crypto/crypto/scrypt/scrypt.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; // /// Constants for BIP38 encryption and decryption operations. @@ -85,7 +85,7 @@ class Bip38EcUtils { /// /// - [lotNum]: The lot number to use for owner entropy. /// - [sequenceNum]: The sequence number to use for owner entropy. - /// - Returns: A List representing the generated owner entropy. + /// - Returns: A `List` representing the generated owner entropy. static List ownerEntropyWithLotSeq(int lotNum, int sequenceNum) { if (lotNum < Bip38EcConst.lotNumMinVal || lotNum > Bip38EcConst.lotNumMaxVal) { @@ -111,7 +111,7 @@ class Bip38EcUtils { /// Generates owner entropy without including lot and sequence numbers. This /// method is used when BIP38 does not require lot and sequence numbers. /// - /// - Returns: A List representing the generated owner entropy. + /// - Returns: A `List` representing the generated owner entropy. static List ownerEntropyNoLotSeq() { final ownerSalt = QuickCrypto.generateRandom(Bip38EcConst.ownerSaltNoLotSeqByteLen); @@ -126,7 +126,7 @@ class Bip38EcUtils { /// - [ownerEntropy]: The owner entropy containing owner salt. /// - [hasLotSeq]: A boolean flag indicating whether lot and sequence numbers are /// included in the owner entropy. - /// - Returns: A List representing the extracted owner salt. + /// - Returns: A `List` representing the extracted owner salt. static List ownerSaltFromEntropy( List ownerEntropy, bool hasLotSeq) { return hasLotSeq @@ -145,7 +145,7 @@ class Bip38EcUtils { /// - [ownerEntropy]: The owner entropy from which the pass factor is derived. /// - [hasLotSeq]: A boolean flag indicating whether lot and sequence numbers are /// included in the owner entropy. - /// - Returns: A List representing the derived pass factor. + /// - Returns: A `List` representing the derived pass factor. static List passFactor( String passphrase, List ownerEntropy, bool hasLotSeq) { final ownerSalt = ownerSaltFromEntropy(ownerEntropy, hasLotSeq); @@ -176,7 +176,7 @@ class Bip38EcUtils { /// multiplication to derive the EC point. /// /// - [passfactor]: The pass factor for which the EC point is calculated. - /// - Returns: A List representing the calculated EC point. + /// - Returns: A `List` representing the calculated EC point. static List passPoint(List passfactor) { /// Get the generator point for the Secp256k1 curve. final generator = Curves.generatorSecp256k1; @@ -201,7 +201,7 @@ class Bip38EcUtils { /// - [passpoint]: The passpoint used in key derivation. /// - [addressHash]: The address hash to be combined in key derivation. /// - [ownerEntropy]: The owner entropy used in key derivation. - /// - Returns: A tuple (pair) of Lists representing the two derived key halves. + /// - Returns: A tuple (pair) of `List`s representing the two derived key halves. static Tuple, List> deriveKeyHalves( List passpoint, List addressHash, List ownerEntropy) { /// Derive a key using Scrypt with combined data. @@ -339,7 +339,7 @@ class Bip38EcKeysGenerator { /// - [seedb]: The 'seedb' value to be encrypted. /// - [derivedHalf1]: The first derived key half. /// - [derivedHalf2]: The second derived key half. - /// - Returns: A tuple (pair) of Lists representing the two encrypted parts. + /// - Returns: A tuple (pair) of `List`s representing the two encrypted parts. static Tuple, List> _encryptSeedb( List seedb, List derivedHalf1, List derivedHalf2) { /// Encrypt the first part of 'seedb'. @@ -362,11 +362,11 @@ class Bip38EcKeysGenerator { /// This method sets specific flag bits in the 'flagbyte' to indicate the /// chosen public key mode (compressed or uncompressed) and the presence of /// lot and sequence numbers in the intermediate passphrase, as defined by the - /// provided magic number. It returns the modified 'flagbyte' as a List. + /// provided magic number. It returns the modified 'flagbyte' as a `List`. /// /// - [magic]: The magic number extracted from the intermediate passphrase. /// - [pubKeyMode]: The selected public key mode (compressed or uncompressed). - /// - Returns: A List representing the 'flagbyte' with set bits. + /// - Returns: A `List` representing the 'flagbyte' with set bits. static List _setFlagbyteBits(List magic, PubKeyModes pubKeyMode) { int flagbyteInt = 0; @@ -466,7 +466,7 @@ class Bip38EcDecrypter { /// - [encryptedPart2]: The second encrypted segment. /// - [derivedHalf1]: The first derived key half. /// - [derivedHalf2]: The second derived key half. - /// - Returns: The decrypted 'factorb' as a List. + /// - Returns: The decrypted 'factorb' as a `List`. static List _decryptAndGetFactorb( List encryptedPart1Lower, List encryptedPart2, diff --git a/lib/bip/bip/bip38/bip38_no_ec.dart b/lib/bip/bip/bip38/bip38_no_ec.dart index f4936a6..afc788a 100644 --- a/lib/bip/bip/bip38/bip38_no_ec.dart +++ b/lib/bip/bip/bip38/bip38_no_ec.dart @@ -1,11 +1,11 @@ import 'package:blockchain_utils/base58/base58.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/bip/types/types.dart'; import 'package:blockchain_utils/bip/ecc/keys/secp256k1_keys_ecdsa.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/scrypt/scrypt.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Constants for BIP38 encryption and decryption without ECDSA. /// @@ -50,7 +50,7 @@ class Bip38NoEcUtils { /// /// - [privKeyBytes]: The private key bytes. /// - [pubKeyMode]: The selected public key mode. - /// - Returns: The address hash as a List. + /// - Returns: The address hash as a `List`. static List addressHash(List privKeyBytes, PubKeyModes pubKeyMode) { final publicBytes = Secp256k1PrivateKeyEcdsa.fromBytes(privKeyBytes) .publicKey @@ -68,7 +68,7 @@ class Bip38NoEcUtils { /// /// - [passphrase]: The passphrase for key derivation. /// - [addressHash]: The address hash as input for key derivation. - /// - Returns: A tuple (pair) containing the two derived key halves as Lists. + /// - Returns: A tuple (pair) containing the two derived key halves as `List`s. static Tuple, List> deriveKeyHalves( String passphrase, List addressHash) { final key = Scrypt.deriveKey( @@ -153,7 +153,7 @@ class Bip38NoEcEncrypter { /// - [derivedHalf1]: The first derived key half. /// - [derivedHalf2]: The second derived key half. /// - Returns: A tuple (pair) containing the two encrypted private key halves - /// as Lists. + /// as `List`s. static Tuple, List> _encryptPrivateKey( List privKeyBytes, List derivedHalf1, List derivedHalf2) { /// Encrypt the first half of the private key. @@ -186,7 +186,7 @@ class Bip38NoEcDecrypter { /// /// - [privKeyEnc]: The BIP38-encrypted Bitcoin private key. /// - [passphrase]: The passphrase for decryption. - /// - Returns: A tuple (pair) containing the decrypted private key as a List + /// - Returns: A tuple (pair) containing the decrypted private key as a `List` /// and the selected public key mode (compressed or uncompressed). static Tuple, PubKeyModes> decrypt( String privKeyEnc, String passphrase) { @@ -245,13 +245,13 @@ class Bip38NoEcDecrypter { /// /// This method decrypts the Bitcoin private key from the encrypted halves using /// the derived key halves. It combines the two decrypted halves to reconstruct - /// the private key and returns it as a List. + /// the private key and returns it as a `List`. /// /// - [encryptedHalf1]: The first encrypted half of the private key. /// - [encryptedHalf2]: The second encrypted half of the private key. /// - [derivedHalf1]: The first derived key half. /// - [derivedHalf2]: The second derived key half. - /// - Returns: The decrypted private key as a List. + /// - Returns: The decrypted private key as a `List`. static List _decryptAndGetPrivKey( List encryptedHalf1, List encryptedHalf2, diff --git a/lib/bip/bip/bip39/bip39.dart b/lib/bip/bip/bip39/bip39.dart index a7e56ec..ce7e0da 100644 --- a/lib/bip/bip/bip39/bip39.dart +++ b/lib/bip/bip/bip39/bip39.dart @@ -1,7 +1,7 @@ /// The 'bip39' library provides a comprehensive set of tools for working with /// BIP-39 mnemonics, a standard for creating human-readable mnemonic phrases /// for cryptographic keys. -library bip39; +library; /// Export statement for word list languages used in BIP-39 mnemonics. export 'word_list/languages.dart'; diff --git a/lib/bip/bip/bip39/bip39_mnemonic.dart b/lib/bip/bip/bip39/bip39_mnemonic.dart index ffe7e26..cfd8d00 100644 --- a/lib/bip/bip/bip39/bip39_mnemonic.dart +++ b/lib/bip/bip/bip39/bip39_mnemonic.dart @@ -147,9 +147,9 @@ class Bip39MnemonicConst { class Bip39Mnemonic extends Mnemonic { /// Constructs a BIP-39 mnemonic from a mnemonic phrase provided as a string. /// This constructor initializes a BIP-39 mnemonic object by parsing the input string. - Bip39Mnemonic.fromString(String mnemonic) : super.fromString(mnemonic); + Bip39Mnemonic.fromString(super.mnemonic) : super.fromString(); /// Constructs a BIP-39 mnemonic from a list of words. /// This constructor initializes a BIP-39 mnemonic object using a list of BIP-39 words. - Bip39Mnemonic.fromList(List mnemonic) : super.fromList(mnemonic); + Bip39Mnemonic.fromList(super.mnemonic) : super.fromList(); } diff --git a/lib/bip/bip/bip39/bip39_mnemonic_decoder.dart b/lib/bip/bip/bip39/bip39_mnemonic_decoder.dart index 594c6fc..fb80eb3 100644 --- a/lib/bip/bip/bip39/bip39_mnemonic_decoder.dart +++ b/lib/bip/bip/bip39/bip39_mnemonic_decoder.dart @@ -6,7 +6,7 @@ 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'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// BIP39 (Bitcoin Improvement Proposal 39) mnemonic decoder class. /// diff --git a/lib/bip/bip/bip39/bip39_mnemonic_encoder.dart b/lib/bip/bip/bip39/bip39_mnemonic_encoder.dart index 65e2be1..1d2e01b 100644 --- a/lib/bip/bip/bip39/bip39_mnemonic_encoder.dart +++ b/lib/bip/bip/bip39/bip39_mnemonic_encoder.dart @@ -5,7 +5,7 @@ import 'package:blockchain_utils/crypto/quick_crypto.dart'; import 'package:blockchain_utils/helper/helper.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'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// BIP39 Mnemonic Encoder for generating mnemonic phrases. /// diff --git a/lib/bip/bip/bip39/bip39_mnemonic_utils.dart b/lib/bip/bip/bip39/bip39_mnemonic_utils.dart index 8368d9e..fe2d2ff 100644 --- a/lib/bip/bip/bip39/bip39_mnemonic_utils.dart +++ b/lib/bip/bip/bip39/bip39_mnemonic_utils.dart @@ -2,7 +2,7 @@ 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/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/utils/utils.dart'; import 'bip39_mnemonic.dart'; diff --git a/lib/bip/bip/bip39/word_list/languages.dart b/lib/bip/bip/bip39/word_list/languages.dart index 1740a57..3f7d93d 100644 --- a/lib/bip/bip/bip39/word_list/languages.dart +++ b/lib/bip/bip/bip39/word_list/languages.dart @@ -2,7 +2,7 @@ /// for different languages as defined in BIP-39 (Bitcoin Improvement Proposal 39). /// These word lists are used for creating and recovering cryptocurrency wallets. -library bip39_menemonic_languages; +library; import 'package:blockchain_utils/bip/bip/bip39/bip39_mnemonic.dart'; diff --git a/lib/bip/bip/bip44/base/bip44_base.dart b/lib/bip/bip/bip44/base/bip44_base.dart index 7e37d47..54a5b8a 100644 --- a/lib/bip/bip/bip44/base/bip44_base.dart +++ b/lib/bip/bip/bip44/base/bip44_base.dart @@ -10,7 +10,7 @@ import 'package:blockchain_utils/bip/bip/bip44/base/bip44_base_ex.dart'; import 'package:blockchain_utils/bip/bip/conf/config/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/exception/exceptions.dart'; import 'package:blockchain_utils/utils/utils.dart'; import 'bip44_keys.dart'; @@ -232,7 +232,7 @@ abstract class Bip44Base { /// Internal validation method for checking the depth of the BIP object. static Tuple _validate( Bip32Base bip32Obj, BipCoinConfig coinConf) { - int depth = bip32Obj.depth.depth; + final int depth = bip32Obj.depth.depth; if (bip32Obj.isPublicOnly) { if (depth < Bip44Levels.account.value || diff --git a/lib/bip/bip/bip44/base/bip44_base_ex.dart b/lib/bip/bip/bip44/base/bip44_base_ex.dart index 6a6f3ce..1335d00 100644 --- a/lib/bip/bip/bip44/base/bip44_base_ex.dart +++ b/lib/bip/bip/bip44/base/bip44_base_ex.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Custom exception for errors related to BIP-44 depth. /// @@ -6,6 +6,5 @@ import 'package:blockchain_utils/exception/exception.dart'; /// errors related to the BIP-44 hierarchical deterministic wallet structure's /// depth. It can be thrown to indicate issues with depth levels in BIP-44 paths. class Bip44DepthError extends BlockchainUtilsException { - const Bip44DepthError(String message, {Map? details}) - : super(message, details: details); + const Bip44DepthError(super.message, {super.details}); } diff --git a/lib/bip/bip/bip44/base/bip44_keys.dart b/lib/bip/bip/bip44/base/bip44_keys.dart index cfc4363..afce1ae 100644 --- a/lib/bip/bip/bip44/base/bip44_keys.dart +++ b/lib/bip/bip/bip44/base/bip44_keys.dart @@ -1,11 +1,11 @@ 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/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_keys.dart'; import 'package:blockchain_utils/bip/bip/conf/config/bip_coin_conf.dart'; +import 'package:blockchain_utils/bip/bip/types/types.dart'; import 'package:blockchain_utils/bip/wif/wif.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Represents a BIP44 public key for a specific cryptocurrency coin. This class /// ensures that the elliptic curve type of the public key matches the coin's @@ -65,7 +65,7 @@ class Bip44PublicKey { /// Shelley or Monero, which require using specific classes to generate /// addresses. String get toAddress { - BlockchainAddressEncoder encoder = coinConf.encoder(); + final BlockchainAddressEncoder encoder = coinConf.encoder(); if (encoder is AdaShelleyAddrEncoder) { throw const ArgumentException( 'Use the CardanoShelley class to get Cardano Shelley addresses'); diff --git a/lib/bip/bip/bip44/bip44.dart b/lib/bip/bip/bip44/bip44.dart index 50d902f..1c79d31 100644 --- a/lib/bip/bip/bip44/bip44.dart +++ b/lib/bip/bip/bip44/bip44.dart @@ -1,6 +1,6 @@ /// The 'bip44' library provides tools for working with BIP-44, a standard for /// hierarchical deterministic wallets and key derivation in cryptocurrencies. -library bip44; +library; /// Export statement for the base BIP-44 implementation and key-related functions. export 'base/bip44_base.dart'; diff --git a/lib/bip/bip/bip44/bip44_base.dart b/lib/bip/bip/bip44/bip44_base.dart index a158b45..3db88ed 100644 --- a/lib/bip/bip/bip44/bip44_base.dart +++ b/lib/bip/bip/bip44/bip44_base.dart @@ -1,9 +1,7 @@ -import 'package:blockchain_utils/bip/bip/bip32/base/bip32_base.dart'; +import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip44/base/bip44_base.dart'; import 'package:blockchain_utils/bip/bip/bip44/base/bip44_base_ex.dart'; import 'package:blockchain_utils/bip/bip/conf/bip44/bip44_coins.dart'; -import 'package:blockchain_utils/bip/bip/conf/config/bip_coin_conf.dart'; -import '../bip32/bip32_key_data.dart'; /// Constants related to BIP-44 (Bitcoin Improvement Proposal 44). class Bip44Const { @@ -16,8 +14,7 @@ class Bip44Const { class Bip44 extends Bip44Base { // private constractor - Bip44._(Bip32Base bip32Obj, BipCoinConfig coinConf) - : super(bip32Obj, coinConf); + Bip44._(super.bip32Obj, super.coinConf); /// Constructor for creating a [Bip44] object from a seed and coin. Bip44.fromSeed(List seedBytes, Bip44Coins coinType) @@ -53,7 +50,7 @@ class Bip44 extends Bip44Base { /// derive default path @override Bip44 get deriveDefaultPath { - Bip44 bipObj = purpose.coin; + final Bip44 bipObj = purpose.coin; return Bip44._(bipObj.bip32.derivePath(bipObj.coinConf.defPath), coinConf); } diff --git a/lib/bip/bip/bip49/bip49.dart b/lib/bip/bip/bip49/bip49.dart index 0f827af..dec0c64 100644 --- a/lib/bip/bip/bip49/bip49.dart +++ b/lib/bip/bip/bip49/bip49.dart @@ -3,6 +3,6 @@ /// Export statement for the BIP-49 base implementation, which includes key /// derivation and wallet management functions. -library bip49; +library; export 'bip49_base.dart'; diff --git a/lib/bip/bip/bip49/bip49_base.dart b/lib/bip/bip/bip49/bip49_base.dart index d8bea2f..79940ad 100644 --- a/lib/bip/bip/bip49/bip49_base.dart +++ b/lib/bip/bip/bip49/bip49_base.dart @@ -52,12 +52,10 @@ OF THE POSSIBILITY OF SUCH DAMAGE. */ -import 'package:blockchain_utils/bip/bip/bip32/base/bip32_base.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip44/base/bip44_base.dart'; import 'package:blockchain_utils/bip/bip/bip44/base/bip44_base_ex.dart'; import 'package:blockchain_utils/bip/bip/conf/bip49/bip49_coins.dart'; -import 'package:blockchain_utils/bip/bip/conf/config/bip_coin_conf.dart'; /// Constants related to BIP-49 (Bitcoin Improvement Proposal 44). class Bip49Const { @@ -70,8 +68,7 @@ class Bip49Const { class Bip49 extends Bip44Base { /// private constractor - Bip49._(Bip32Base bip32Obj, BipCoinConfig coinConf) - : super(bip32Obj, coinConf); + Bip49._(super.bip32Obj, super.coinConf); /// Constructor for creating a [Bip49] object from a seed and coin. Bip49.fromSeed(List seedBytes, Bip49Coins coinType) @@ -158,7 +155,7 @@ class Bip49 extends Bip44Base { /// derive default path @override Bip49 get deriveDefaultPath { - Bip44Base bipObj = purpose.coin; + final Bip44Base bipObj = purpose.coin; return Bip49._(bipObj.bip32.derivePath(bipObj.coinConf.defPath), coinConf); } diff --git a/lib/bip/bip/bip84/bip84.dart b/lib/bip/bip/bip84/bip84.dart index 6d61222..6d551f2 100644 --- a/lib/bip/bip/bip84/bip84.dart +++ b/lib/bip/bip/bip84/bip84.dart @@ -1,6 +1,6 @@ /// The 'bip84' library provides tools for working with BIP-84, a standard for /// hierarchical deterministic wallets and key derivation in cryptocurrencies. -library bip84; +library; /// Export statement for the BIP-84 base implementation, which includes key /// derivation and wallet management functions. diff --git a/lib/bip/bip/bip84/bip84_base.dart b/lib/bip/bip/bip84/bip84_base.dart index 806587f..c5bfe1b 100644 --- a/lib/bip/bip/bip84/bip84_base.dart +++ b/lib/bip/bip/bip84/bip84_base.dart @@ -1,9 +1,7 @@ -import 'package:blockchain_utils/bip/bip/bip32/base/bip32_base.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip44/base/bip44_base.dart'; import 'package:blockchain_utils/bip/bip/bip44/base/bip44_base_ex.dart'; import 'package:blockchain_utils/bip/bip/conf/bip84/bip84_coins.dart'; -import 'package:blockchain_utils/bip/bip/conf/config/bip_coin_conf.dart'; /// Constants related to BIP-84 (Bitcoin Improvement Proposal 84). class Bip84Const { @@ -16,8 +14,7 @@ class Bip84Const { class Bip84 extends Bip44Base { /// private constractor - Bip84._(Bip32Base bip32Obj, BipCoinConfig coinConf) - : super(bip32Obj, coinConf); + Bip84._(super.bip32Obj, super.coinConf); /// Constructor for creating a [Bip84] object from a seed and coin. Bip84.fromSeed(List seedBytes, Bip84Coins coinType) @@ -104,7 +101,7 @@ class Bip84 extends Bip44Base { /// derive default path @override Bip84 get deriveDefaultPath { - Bip44Base bipObj = purpose.coin; + final Bip44Base bipObj = purpose.coin; return Bip84._(bipObj.bip32.derivePath(bipObj.coinConf.defPath), coinConf); } diff --git a/lib/bip/bip/bip86/bip86.dart b/lib/bip/bip/bip86/bip86.dart index 75a29f8..f16d8a0 100644 --- a/lib/bip/bip/bip86/bip86.dart +++ b/lib/bip/bip/bip86/bip86.dart @@ -1,6 +1,6 @@ /// The 'bip86' library provides tools for working with BIP-86, a standard for /// hierarchical deterministic wallets and key derivation in cryptocurrencies. -library bip86; +library; /// Export statement for the BIP-86 base implementation, which includes key /// derivation and wallet management functions. diff --git a/lib/bip/bip/bip86/bip86_base.dart b/lib/bip/bip/bip86/bip86_base.dart index 00f49e3..0b6713b 100644 --- a/lib/bip/bip/bip86/bip86_base.dart +++ b/lib/bip/bip/bip86/bip86_base.dart @@ -1,9 +1,7 @@ -import 'package:blockchain_utils/bip/bip/bip32/base/bip32_base.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip44/base/bip44_base.dart'; import 'package:blockchain_utils/bip/bip/bip44/base/bip44_base_ex.dart'; import 'package:blockchain_utils/bip/bip/conf/bip86/bip86_coins.dart'; -import 'package:blockchain_utils/bip/bip/conf/config/bip_coin_conf.dart'; /// Constants related to BIP-86 (Bitcoin Improvement Proposal 86). class Bip86Const { @@ -16,8 +14,7 @@ class Bip86Const { class Bip86 extends Bip44Base { /// private constructor - Bip86._(Bip32Base bip32Obj, BipCoinConfig coinConf) - : super(bip32Obj, coinConf); + Bip86._(super.bip32Obj, super.coinConf); /// Constructor for creating a [Bip86] object from a seed and coin. Bip86.fromSeed(List seedBytes, Bip86Coins coinType) @@ -104,7 +101,7 @@ class Bip86 extends Bip44Base { /// derive default path @override Bip86 get deriveDefaultPath { - Bip44Base bipObj = purpose.coin; + final Bip44Base bipObj = purpose.coin; return Bip86._(bipObj.bip32.derivePath(bipObj.coinConf.defPath), coinConf); } diff --git a/lib/bip/bip/conf/bip44/bip44_coins.dart b/lib/bip/bip/conf/bip44/bip44_coins.dart index e5e9a58..737129b 100644 --- a/lib/bip/bip/conf/bip44/bip44_coins.dart +++ b/lib/bip/bip/conf/bip44/bip44_coins.dart @@ -141,6 +141,19 @@ class Bip44Coins extends BipCoins { /// Cosmos static const cosmosTestnetNist256p1 = Bip44Coins._('cosmosTestnetNist256p1'); + /// Cosmos + static const cosmosEd25519 = Bip44Coins._('cosmosEd25519'); + + /// Cosmos + static const cosmosTestnetEd25519 = Bip44Coins._('cosmosTestnetEd25519'); + + /// Cosmos + static const cosmosEthSecp256k1 = Bip44Coins._('cosmosEthSecp256k1'); + + /// Cosmos + static const cosmosTestnetEthSecp256k1 = + Bip44Coins._('cosmosTestnetEthSecp256k1'); + /// Dash static const dash = Bip44Coins._('dash'); @@ -418,6 +431,10 @@ class Bip44Coins extends BipCoins { Bip44Coins.cosmosTestnet: Bip44Conf.cosmosTestnet, Bip44Coins.cosmosNist256p1: Bip44Conf.cosmosNist256p1, Bip44Coins.cosmosTestnetNist256p1: Bip44Conf.cosmosTestnetNist256p1, + Bip44Coins.cosmosEd25519: Bip44Conf.cosmosEd25519, + Bip44Coins.cosmosTestnetEd25519: Bip44Conf.cosmosTestnetEd25519, + Bip44Coins.cosmosEthSecp256k1: Bip44Conf.cosmosEthSecp256k1, + Bip44Coins.cosmosTestnetEthSecp256k1: Bip44Conf.cosmosTestnetEthSecp256k1, Bip44Coins.dash: Bip44Conf.dashMainNet, Bip44Coins.dashTestnet: Bip44Conf.dashTestNet, Bip44Coins.dogecoin: Bip44Conf.dogecoinMainNet, @@ -487,7 +504,6 @@ class Bip44Coins extends BipCoins { Bip44Coins.electraProtocol: Bip44Conf.electraProtocolMainNet, Bip44Coins.electraProtocolTestnet: Bip44Conf.electraProtocolTestNet, }; - @override BipProposal get proposal => BipProposal.bip44; diff --git a/lib/bip/bip/conf/bip44/bip44_conf.dart b/lib/bip/bip/conf/bip44/bip44_conf.dart index 314d5d8..4028e04 100644 --- a/lib/bip/bip/conf/bip44/bip44_conf.dart +++ b/lib/bip/bip/conf/bip44/bip44_conf.dart @@ -1,10 +1,12 @@ +import 'package:blockchain_utils/bip/address/atom_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/config/bip_bitcoin_cash_conf.dart'; import 'package:blockchain_utils/bip/bip/conf/config/bip_coin_conf.dart'; -import 'package:blockchain_utils/bip/bip/conf/config/bip_litecoin_conf.dart'; import 'package:blockchain_utils/bip/bip/conf/const/bip_conf_const.dart'; +import 'package:blockchain_utils/bip/bip/conf/config/bip_litecoin_conf.dart'; +import 'package:blockchain_utils/bip/bip/conf/core/coin_conf.dart'; import 'package:blockchain_utils/bip/coin_conf/constant/coins_conf.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; import 'package:blockchain_utils/bip/slip/slip44/slip44.dart'; @@ -24,7 +26,7 @@ class Bip44Conf { static final BipCoinConfig akashNetwork = BipCoinConfig( coinNames: CoinsConf.akashNetwork.coinName, coinIdx: Slip44.atom, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -40,7 +42,7 @@ class Bip44Conf { coinNames: CoinsConf.algorand.coinName, addressEncoder: ([dynamic kwargs]) => AlgoAddrEncoder(), coinIdx: Slip44.algorand, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -52,7 +54,7 @@ class Bip44Conf { static final BipCoinConfig aptos = BipCoinConfig( coinNames: CoinsConf.aptos.coinName, coinIdx: Slip44.aptos, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -65,7 +67,7 @@ class Bip44Conf { static final BipCoinConfig avaxCChain = BipCoinConfig( coinNames: CoinsConf.avaxCChain.coinName, coinIdx: Slip44.ethereum, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -78,7 +80,7 @@ class Bip44Conf { static final BipCoinConfig avaxPChain = BipCoinConfig( coinNames: CoinsConf.avaxPChain.coinName, coinIdx: Slip44.avalanche, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -91,7 +93,7 @@ class Bip44Conf { static final BipCoinConfig avaxXChain = BipCoinConfig( coinNames: CoinsConf.avaxXChain.coinName, coinIdx: Slip44.avalanche, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -104,7 +106,7 @@ class Bip44Conf { static final BipCoinConfig axelar = BipCoinConfig( coinNames: CoinsConf.axelar.coinName, coinIdx: Slip44.atom, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -119,7 +121,7 @@ class Bip44Conf { static final BipCoinConfig bandProtocol = BipCoinConfig( coinNames: CoinsConf.bandProtocol.coinName, coinIdx: Slip44.bandProtocol, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -134,7 +136,7 @@ class Bip44Conf { static final BipCoinConfig binanceChain = BipCoinConfig( coinNames: CoinsConf.binanceChain.coinName, coinIdx: Slip44.binanceChain, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -149,7 +151,7 @@ class Bip44Conf { static final BipCoinConfig binanceSmartChain = BipCoinConfig( coinNames: CoinsConf.binanceSmartChain.coinName, coinIdx: Slip44.ethereum, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -162,7 +164,7 @@ class Bip44Conf { static final BipCoinConfig bitcoinMainNet = BipCoinConfig( coinNames: CoinsConf.bitcoinMainNet.coinName, coinIdx: Slip44.bitcoin, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: CoinsConf.bitcoinMainNet.params.wifNetVer, @@ -177,7 +179,7 @@ class Bip44Conf { static final BipCoinConfig bitcoinTestNet = BipCoinConfig( coinNames: CoinsConf.bitcoinTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerTest, wifNetVer: CoinsConf.bitcoinTestNet.params.wifNetVer, @@ -192,7 +194,7 @@ class Bip44Conf { static final BipBitcoinCashConf bitcoinCashMainNet = BipBitcoinCashConf( coinNames: CoinsConf.bitcoinCashMainNet.coinName, coinIdx: Slip44.bitcoinCash, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: CoinsConf.bitcoinCashMainNet.params.wifNetVer, @@ -218,7 +220,7 @@ class Bip44Conf { static final BipBitcoinCashConf bitcoinCashTestNet = BipBitcoinCashConf( coinNames: CoinsConf.bitcoinCashTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, addressEncoder: ([dynamic legacy]) { if (legacy == true) { @@ -244,7 +246,7 @@ class Bip44Conf { static final BipBitcoinCashConf bitcoinCashSlpMainNet = BipBitcoinCashConf( coinNames: CoinsConf.bitcoinCashSlpMainNet.coinName, coinIdx: Slip44.bitcoinCash, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: CoinsConf.bitcoinCashSlpMainNet.params.wifNetVer, @@ -270,7 +272,7 @@ class Bip44Conf { static final BipBitcoinCashConf bitcoinCashSlpTestNet = BipBitcoinCashConf( coinNames: CoinsConf.bitcoinCashSlpTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerTest, wifNetVer: CoinsConf.bitcoinCashSlpTestNet.params.wifNetVer, @@ -296,7 +298,7 @@ class Bip44Conf { static final BipCoinConfig bitcoinSvMainNet = BipCoinConfig( coinNames: CoinsConf.bitcoinSvMainNet.coinName, coinIdx: Slip44.bitcoinSv, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: CoinsConf.bitcoinSvMainNet.params.wifNetVer, @@ -313,7 +315,7 @@ class Bip44Conf { static final BipCoinConfig bitcoinSvTestNet = BipCoinConfig( coinNames: CoinsConf.bitcoinSvTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerTest, wifNetVer: CoinsConf.bitcoinSvTestNet.params.wifNetVer, @@ -327,7 +329,7 @@ class Bip44Conf { static final BipCoinConfig cardanoByronIcarus = BipCoinConfig( coinNames: CoinsConf.cardanoMainNet.coinName, coinIdx: Slip44.cardano, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32Const.kholawKeyNetVersions, wifNetVer: null, @@ -340,7 +342,7 @@ class Bip44Conf { static final BipCoinConfig cardanoByronLedger = BipCoinConfig( coinNames: CoinsConf.cardanoMainNet.coinName, coinIdx: Slip44.cardano, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32Const.kholawKeyNetVersions, wifNetVer: null, @@ -351,7 +353,7 @@ class Bip44Conf { static final BipCoinConfig cardanoByronIcarusTestnet = BipCoinConfig( coinNames: CoinsConf.cardanoMainNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32Const.kholawKeyNetVersions, wifNetVer: null, @@ -364,7 +366,7 @@ class Bip44Conf { static final BipCoinConfig cardanoByronLedgerTestnet = BipCoinConfig( coinNames: CoinsConf.cardanoMainNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32Const.kholawKeyNetVersions, wifNetVer: null, @@ -377,7 +379,7 @@ class Bip44Conf { static final BipCoinConfig celo = BipCoinConfig( coinNames: CoinsConf.celo.coinName, coinIdx: Slip44.celo, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -390,7 +392,7 @@ class Bip44Conf { static final BipCoinConfig certik = BipCoinConfig( coinNames: CoinsConf.certik.coinName, coinIdx: Slip44.atom, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -405,7 +407,7 @@ class Bip44Conf { static final BipCoinConfig chihuahua = BipCoinConfig( coinNames: CoinsConf.chihuahua.coinName, coinIdx: Slip44.atom, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -420,7 +422,7 @@ class Bip44Conf { static final BipCoinConfig cosmos = BipCoinConfig( coinNames: CoinsConf.cosmos.coinName, coinIdx: Slip44.atom, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -433,7 +435,7 @@ class Bip44Conf { static final BipCoinConfig cosmosTestnet = BipCoinConfig( coinNames: CoinsConf.cosmos.coinName, coinIdx: Slip44.testnet, - isTestnet: false, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -444,11 +446,38 @@ class Bip44Conf { }, ); + static final BipCoinConfig cosmosEthSecp256k1 = BipCoinConfig( + coinNames: CoinsConf.cosmos.coinName, + coinIdx: Slip44.atom, + chainType: ChainType.mainnet, + defPath: derPathNonHardenedFull, + keyNetVer: bip44BtcKeyNetVerMain, + wifNetVer: null, + type: EllipticCurveTypes.secp256k1, + addressEncoder: ([dynamic kwargs]) => AtomEthSecp256k1AddrEncoder(), + addrParams: { + "hrp": CoinsConf.cosmos.params.addrHrp!, + }, + ); + static final BipCoinConfig cosmosTestnetEthSecp256k1 = BipCoinConfig( + coinNames: CoinsConf.cosmos.coinName, + coinIdx: Slip44.testnet, + chainType: ChainType.testnet, + defPath: derPathNonHardenedFull, + keyNetVer: bip44BtcKeyNetVerMain, + wifNetVer: null, + type: EllipticCurveTypes.secp256k1, + addressEncoder: ([dynamic kwargs]) => AtomEthSecp256k1AddrEncoder(), + addrParams: { + "hrp": CoinsConf.cosmos.params.addrHrp!, + }, + ); + /// Configuration for Cosmos static final BipCoinConfig cosmosNist256p1 = BipCoinConfig( coinNames: CoinsConf.cosmos.coinName, coinIdx: Slip44.atom, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -461,7 +490,7 @@ class Bip44Conf { static final BipCoinConfig cosmosTestnetNist256p1 = BipCoinConfig( coinNames: CoinsConf.cosmos.coinName, coinIdx: Slip44.testnet, - isTestnet: false, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -472,11 +501,39 @@ class Bip44Conf { }, ); + /// Configuration for Cosmos + static final BipCoinConfig cosmosEd25519 = BipCoinConfig( + coinNames: CoinsConf.cosmos.coinName, + coinIdx: Slip44.atom, + chainType: ChainType.mainnet, + defPath: derPathHardenedFull, + keyNetVer: bip44BtcKeyNetVerMain, + wifNetVer: null, + type: EllipticCurveTypes.ed25519, + addressEncoder: ([dynamic kwargs]) => AtomEd25519AddrEncoder(), + addrParams: { + "hrp": CoinsConf.cosmos.params.addrHrp!, + }, + ); + static final BipCoinConfig cosmosTestnetEd25519 = BipCoinConfig( + coinNames: CoinsConf.cosmos.coinName, + coinIdx: Slip44.testnet, + chainType: ChainType.testnet, + defPath: derPathHardenedFull, + keyNetVer: bip44BtcKeyNetVerMain, + wifNetVer: null, + type: EllipticCurveTypes.ed25519, + addressEncoder: ([dynamic kwargs]) => AtomEd25519AddrEncoder(), + addrParams: { + "hrp": CoinsConf.cosmos.params.addrHrp!, + }, + ); + /// Configuration for Dash main net static final BipCoinConfig dashMainNet = BipCoinConfig( coinNames: CoinsConf.dashMainNet.coinName, coinIdx: Slip44.dash, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: CoinsConf.dashMainNet.params.wifNetVer, @@ -491,7 +548,7 @@ class Bip44Conf { static final BipCoinConfig dashTestNet = BipCoinConfig( coinNames: CoinsConf.dashTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerTest, wifNetVer: CoinsConf.dashTestNet.params.wifNetVer, @@ -506,7 +563,7 @@ class Bip44Conf { static final BipCoinConfig dogecoinMainNet = BipCoinConfig( coinNames: CoinsConf.dogecoinMainNet.coinName, coinIdx: Slip44.dogecoin, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions(List.from([0x02, 0xfa, 0xca, 0xfd]), List.from([0x02, 0xfa, 0xc3, 0x98])), @@ -522,7 +579,7 @@ class Bip44Conf { static final BipCoinConfig dogecoinTestNet = BipCoinConfig( coinNames: CoinsConf.dogecoinTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions(List.from([0x04, 0x32, 0xa9, 0xa8]), List.from([0x04, 0x32, 0xa2, 0x43])), @@ -538,7 +595,7 @@ class Bip44Conf { static final BipCoinConfig pepeMainnet = BipCoinConfig( coinNames: CoinsConf.pepeMainnet.coinName, coinIdx: Slip44.pepecoin, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions(List.from([0x02, 0xfa, 0xca, 0xfd]), List.from([0x02, 0xfa, 0xc3, 0x98])), @@ -552,7 +609,7 @@ class Bip44Conf { static final BipCoinConfig pepeTestnet = BipCoinConfig( coinNames: CoinsConf.pepeTestnet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions(List.from([0x04, 0x32, 0xa9, 0xa8]), List.from([0x04, 0x32, 0xa2, 0x43])), @@ -566,7 +623,7 @@ class Bip44Conf { static final BipBitcoinCashConf ecashMainNet = BipBitcoinCashConf( coinNames: CoinsConf.ecashMainNet.coinName, coinIdx: Slip44.bitcoinCash, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: CoinsConf.ecashMainNet.params.wifNetVer, @@ -592,7 +649,7 @@ class Bip44Conf { static final BipBitcoinCashConf ecashTestNet = BipBitcoinCashConf( coinNames: CoinsConf.ecashTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, addressEncoder: ([dynamic legacy]) { if (legacy == true) { return P2PKHAddrEncoder(); @@ -620,7 +677,7 @@ class Bip44Conf { static final BipCoinConfig elrond = BipCoinConfig( coinNames: CoinsConf.elrond.coinName, coinIdx: Slip44.elrond, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -633,7 +690,7 @@ class Bip44Conf { static final BipCoinConfig eos = BipCoinConfig( coinNames: CoinsConf.eos.coinName, coinIdx: Slip44.eos, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -646,7 +703,7 @@ class Bip44Conf { static final BipCoinConfig ergoMainNet = BipCoinConfig( coinNames: CoinsConf.ergoMainNet.coinName, coinIdx: Slip44.ergo, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -661,7 +718,7 @@ class Bip44Conf { static final BipCoinConfig ergoTestNet = BipCoinConfig( coinNames: CoinsConf.ergoTestNet.coinName, coinIdx: Slip44.ergo, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerTest, wifNetVer: null, @@ -676,7 +733,7 @@ class Bip44Conf { static final BipCoinConfig ethereum = BipCoinConfig( coinNames: CoinsConf.ethereum.coinName, coinIdx: Slip44.ethereum, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -689,7 +746,7 @@ class Bip44Conf { static final BipCoinConfig ethereumTestnet = BipCoinConfig( coinNames: CoinsConf.ethereum.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -702,7 +759,7 @@ class Bip44Conf { static final BipCoinConfig ethereumClassic = BipCoinConfig( coinNames: CoinsConf.ethereumClassic.coinName, coinIdx: Slip44.ethereumClassic, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -715,7 +772,7 @@ class Bip44Conf { static final BipCoinConfig fantomOpera = BipCoinConfig( coinNames: CoinsConf.fantomOpera.coinName, coinIdx: Slip44.ethereum, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -728,7 +785,7 @@ class Bip44Conf { static final BipCoinConfig filecoin = BipCoinConfig( coinNames: CoinsConf.filecoin.coinName, coinIdx: Slip44.filecoin, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -741,7 +798,7 @@ class Bip44Conf { static final BipCoinConfig harmonyOneMetamask = BipCoinConfig( coinNames: CoinsConf.harmonyOne.coinName, coinIdx: Slip44.ethereum, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -754,7 +811,7 @@ class Bip44Conf { static final BipCoinConfig harmonyOneEth = BipCoinConfig( coinNames: CoinsConf.harmonyOne.coinName, coinIdx: Slip44.harmonyOne, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -767,7 +824,7 @@ class Bip44Conf { static final BipCoinConfig harmonyOneAtom = BipCoinConfig( coinNames: CoinsConf.harmonyOne.coinName, coinIdx: Slip44.harmonyOne, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -780,7 +837,7 @@ class Bip44Conf { static final BipCoinConfig huobiChain = BipCoinConfig( coinNames: CoinsConf.huobiChain.coinName, coinIdx: Slip44.ethereum, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -793,7 +850,7 @@ class Bip44Conf { static final BipCoinConfig icon = BipCoinConfig( coinNames: CoinsConf.icon.coinName, coinIdx: Slip44.icon, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -806,7 +863,7 @@ class Bip44Conf { static final BipCoinConfig injective = BipCoinConfig( coinNames: CoinsConf.injective.coinName, coinIdx: Slip44.ethereum, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -819,7 +876,7 @@ class Bip44Conf { static final BipCoinConfig irisNet = BipCoinConfig( coinNames: CoinsConf.irisNet.coinName, coinIdx: Slip44.atom, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -834,7 +891,7 @@ class Bip44Conf { static final BipCoinConfig kava = BipCoinConfig( coinNames: CoinsConf.kava.coinName, coinIdx: Slip44.kava, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -849,7 +906,7 @@ class Bip44Conf { static final BipCoinConfig kusamaEd25519Slip = BipCoinConfig( coinNames: CoinsConf.kusama.coinName, coinIdx: Slip44.kusama, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -864,7 +921,7 @@ class Bip44Conf { static final BipCoinConfig kusamaTestnetEd25519Slip = BipCoinConfig( coinNames: CoinsConf.kusama.coinName, coinIdx: Slip44.testnet, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -879,7 +936,7 @@ class Bip44Conf { static final BipLitecoinConf litecoinMainNet = BipLitecoinConf( coinNames: CoinsConf.litecoinMainNet.coinName, coinIdx: Slip44.litecoin, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, addressEncoder: ([dynamic kwargs]) => P2PKHAddrEncoder(), @@ -899,7 +956,7 @@ class Bip44Conf { static final BipLitecoinConf litecoinTestNet = BipLitecoinConf( coinNames: CoinsConf.litecoinTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions( List.from([0x04, 0x36, 0xf6, 0xe1]), @@ -922,7 +979,7 @@ class Bip44Conf { static final BipCoinConfig moneroEd25519Slip = BipCoinConfig( coinNames: CoinsConf.moneroMainNet.coinName, coinIdx: Slip44.monero, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -935,7 +992,7 @@ class Bip44Conf { static final BipCoinConfig moneroSecp256k1 = BipCoinConfig( coinNames: CoinsConf.moneroMainNet.coinName, coinIdx: Slip44.monero, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -948,7 +1005,7 @@ class Bip44Conf { static final BipCoinConfig nano = BipCoinConfig( coinNames: CoinsConf.nano.coinName, coinIdx: Slip44.nano, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathHardenedShort, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -961,7 +1018,7 @@ class Bip44Conf { static final BipCoinConfig nearProtocol = BipCoinConfig( coinNames: CoinsConf.nearProtocol.coinName, coinIdx: Slip44.nearProtocol, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathHardenedShort, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -974,7 +1031,7 @@ class Bip44Conf { static final BipCoinConfig neo = BipCoinConfig( coinNames: CoinsConf.neo.coinName, coinIdx: Slip44.neo, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -989,7 +1046,7 @@ class Bip44Conf { static final BipCoinConfig nineChroniclesGold = BipCoinConfig( coinNames: CoinsConf.nineChroniclesGold.coinName, coinIdx: Slip44.nineChronicles, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1002,7 +1059,7 @@ class Bip44Conf { static final BipCoinConfig okexChainEth = BipCoinConfig( coinNames: CoinsConf.okexChain.coinName, coinIdx: Slip44.ethereum, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1015,7 +1072,7 @@ class Bip44Conf { static final BipCoinConfig okexChainAtom = BipCoinConfig( coinNames: CoinsConf.okexChain.coinName, coinIdx: Slip44.ethereum, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1028,7 +1085,7 @@ class Bip44Conf { static final BipCoinConfig okexChainAtomOld = BipCoinConfig( coinNames: CoinsConf.okexChain.coinName, coinIdx: Slip44.okexChain, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1041,7 +1098,7 @@ class Bip44Conf { static final BipCoinConfig ontology = BipCoinConfig( coinNames: CoinsConf.ontology.coinName, coinIdx: Slip44.ontology, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1056,7 +1113,7 @@ class Bip44Conf { static final BipCoinConfig osmosis = BipCoinConfig( coinNames: CoinsConf.osmosis.coinName, coinIdx: Slip44.atom, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1071,7 +1128,7 @@ class Bip44Conf { static final BipCoinConfig piNetwork = BipCoinConfig( coinNames: CoinsConf.piNetwork.coinName, coinIdx: Slip44.piNetwork, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathHardenedShort, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1084,7 +1141,7 @@ class Bip44Conf { static final BipCoinConfig polkadotEd25519Slip = BipCoinConfig( coinNames: CoinsConf.polkadot.coinName, coinIdx: Slip44.polkadot, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1097,7 +1154,7 @@ class Bip44Conf { static final BipCoinConfig polkadotTestnetEd25519Slip = BipCoinConfig( coinNames: CoinsConf.polkadot.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1112,7 +1169,7 @@ class Bip44Conf { static final BipCoinConfig polygon = BipCoinConfig( coinNames: CoinsConf.polygon.coinName, coinIdx: Slip44.ethereum, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1125,7 +1182,7 @@ class Bip44Conf { static final BipCoinConfig ripple = BipCoinConfig( coinNames: CoinsConf.ripple.coinName, coinIdx: Slip44.ripple, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1138,7 +1195,7 @@ class Bip44Conf { static final BipCoinConfig rippleTestnet = BipCoinConfig( coinNames: CoinsConf.ripple.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1151,7 +1208,7 @@ class Bip44Conf { static final BipCoinConfig rippleEd25519 = BipCoinConfig( coinNames: CoinsConf.ripple.coinName, coinIdx: Slip44.ripple, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1167,7 +1224,7 @@ class Bip44Conf { static final BipCoinConfig rippleTestnetEd25519 = BipCoinConfig( coinNames: CoinsConf.ripple.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1181,7 +1238,7 @@ class Bip44Conf { static final BipCoinConfig secretNetworkOld = BipCoinConfig( coinNames: CoinsConf.secretNetwork.coinName, coinIdx: Slip44.atom, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1196,7 +1253,7 @@ class Bip44Conf { static final BipCoinConfig secretNetworkNew = BipCoinConfig( coinNames: CoinsConf.secretNetwork.coinName, coinIdx: Slip44.secretNetwork, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1211,7 +1268,7 @@ class Bip44Conf { static final BipCoinConfig solana = BipCoinConfig( coinNames: CoinsConf.solana.coinName, coinIdx: Slip44.solana, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathHardenedShort, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1224,7 +1281,7 @@ class Bip44Conf { static final BipCoinConfig solanaTestnet = BipCoinConfig( coinNames: CoinsConf.solana.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathHardenedShort, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1237,7 +1294,7 @@ class Bip44Conf { static final BipCoinConfig stellar = BipCoinConfig( coinNames: CoinsConf.stellar.coinName, coinIdx: Slip44.stellar, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathHardenedShort, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1250,7 +1307,7 @@ class Bip44Conf { static final BipCoinConfig stellarTestnet = BipCoinConfig( coinNames: CoinsConf.stellar.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathHardenedShort, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1263,7 +1320,7 @@ class Bip44Conf { static final BipCoinConfig terra = BipCoinConfig( coinNames: CoinsConf.terra.coinName, coinIdx: Slip44.terra, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1278,7 +1335,7 @@ class Bip44Conf { static final BipCoinConfig tezos = BipCoinConfig( coinNames: CoinsConf.tezos.coinName, coinIdx: Slip44.tezos, - isTestnet: false, + chainType: ChainType.mainnet, defPath: "0'/0'", keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1291,7 +1348,7 @@ class Bip44Conf { static final BipCoinConfig theta = BipCoinConfig( coinNames: CoinsConf.theta.coinName, coinIdx: Slip44.theta, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1304,7 +1361,7 @@ class Bip44Conf { static final BipCoinConfig tron = BipCoinConfig( coinNames: CoinsConf.tron.coinName, coinIdx: Slip44.tron, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1317,7 +1374,7 @@ class Bip44Conf { static final BipCoinConfig tronTestnet = BipCoinConfig( coinNames: CoinsConf.tron.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1330,7 +1387,7 @@ class Bip44Conf { static final BipCoinConfig vechain = BipCoinConfig( coinNames: CoinsConf.veChain.coinName, coinIdx: Slip44.vechain, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1343,7 +1400,7 @@ class Bip44Conf { static final BipCoinConfig verge = BipCoinConfig( coinNames: CoinsConf.verge.coinName, coinIdx: Slip44.verge, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: CoinsConf.verge.params.wifNetVer, @@ -1358,7 +1415,7 @@ class Bip44Conf { static final BipCoinConfig zcashMainNet = BipCoinConfig( coinNames: CoinsConf.zcashMainNet.coinName, coinIdx: Slip44.zcash, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: CoinsConf.zcashMainNet.params.wifNetVer, @@ -1373,7 +1430,7 @@ class Bip44Conf { static final BipCoinConfig zcashTestNet = BipCoinConfig( coinNames: CoinsConf.zcashTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerTest, wifNetVer: CoinsConf.zcashTestNet.params.wifNetVer, @@ -1388,7 +1445,7 @@ class Bip44Conf { static final BipCoinConfig zilliqa = BipCoinConfig( coinNames: CoinsConf.zilliqa.coinName, coinIdx: Slip44.zilliqa, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1400,7 +1457,7 @@ class Bip44Conf { static final BipCoinConfig tonMainnet = BipCoinConfig( coinNames: CoinsConf.tonMainnet.coinName, coinIdx: Slip44.ton, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathHardenedShort, keyNetVer: Bip44Conf.bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1408,11 +1465,10 @@ class Bip44Conf { addressEncoder: ([dynamic kwargs]) => TonAddrEncoder(), addrParams: {"workchain": CoinsConf.tonMainnet.params.workchain}, ); - static final BipCoinConfig tonTestnet = BipCoinConfig( coinNames: CoinsConf.tonTestnet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathHardenedShort, keyNetVer: Bip44Conf.bip44BtcKeyNetVerMain, wifNetVer: null, @@ -1425,7 +1481,7 @@ class Bip44Conf { static final BipCoinConfig electraProtocolMainNet = BipCoinConfig( coinNames: CoinsConf.electraProtocolMainNet.coinName, coinIdx: Slip44.electraProtocol, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions( List.from([0x04, 0x88, 0xb2, 0x1e]), @@ -1443,7 +1499,7 @@ class Bip44Conf { static final BipCoinConfig electraProtocolTestNet = BipCoinConfig( coinNames: CoinsConf.electraProtocolTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions( List.from([0x04, 0x35, 0x87, 0xcf]), diff --git a/lib/bip/bip/conf/bip49/bip49_coins.dart b/lib/bip/bip/conf/bip49/bip49_coins.dart index bc3173c..bf0aa00 100644 --- a/lib/bip/bip/conf/bip49/bip49_coins.dart +++ b/lib/bip/bip/conf/bip49/bip49_coins.dart @@ -32,7 +32,6 @@ class Bip49Coins extends BipCoins { static const Bip49Coins pepecoinTestnet = Bip49Coins._('pepecoinTestnet'); static const Bip49Coins electraProtocolTestnet = Bip49Coins._('electraProtocolTestnet'); - final String name; const Bip49Coins._(this.name); diff --git a/lib/bip/bip/conf/bip49/bip49_conf.dart b/lib/bip/bip/conf/bip49/bip49_conf.dart index 55ab95f..4617584 100644 --- a/lib/bip/bip/conf/bip49/bip49_conf.dart +++ b/lib/bip/bip/conf/bip49/bip49_conf.dart @@ -1,9 +1,10 @@ import 'package:blockchain_utils/bip/address/p2sh_addr.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_key_net_ver.dart'; +import 'package:blockchain_utils/bip/bip/conf/const/bip_conf_const.dart'; import 'package:blockchain_utils/bip/bip/conf/config/bip_bitcoin_cash_conf.dart'; import 'package:blockchain_utils/bip/bip/conf/config/bip_coin_conf.dart'; import 'package:blockchain_utils/bip/bip/conf/config/bip_litecoin_conf.dart'; -import 'package:blockchain_utils/bip/bip/conf/const/bip_conf_const.dart'; +import 'package:blockchain_utils/bip/bip/conf/core/coin_conf.dart'; import 'package:blockchain_utils/bip/coin_conf/constant/coins_conf.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; import 'package:blockchain_utils/bip/slip/slip44/slip44.dart'; @@ -27,7 +28,7 @@ class Bip49Conf { static final BipCoinConfig dashMainNet = BipCoinConfig( coinNames: CoinsConf.dashMainNet.coinName, coinIdx: Slip44.dash, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip49BtcKeyNetVerMain, wifNetVer: CoinsConf.dashMainNet.params.wifNetVer, @@ -41,7 +42,7 @@ class Bip49Conf { static final BipCoinConfig dashTestNet = BipCoinConfig( coinNames: CoinsConf.dashTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: bip49BtcKeyNetVerTest, wifNetVer: CoinsConf.dashTestNet.params.wifNetVer, @@ -55,7 +56,7 @@ class Bip49Conf { static final BipCoinConfig dogecoinMainNet = BipCoinConfig( coinNames: CoinsConf.dogecoinMainNet.coinName, coinIdx: Slip44.dogecoin, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions( List.from([0x02, 0xfa, 0xca, 0xfd]), @@ -72,7 +73,7 @@ class Bip49Conf { static final BipCoinConfig dogecoinTestNet = BipCoinConfig( coinNames: CoinsConf.dogecoinTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions( List.from([0x04, 0x32, 0xa9, 0xa8]), @@ -89,7 +90,7 @@ class Bip49Conf { static final BipLitecoinConf litecoinMainNet = BipLitecoinConf( coinNames: CoinsConf.litecoinMainNet.coinName, coinIdx: Slip44.litecoin, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip49BtcKeyNetVerMain, altKeyNetVer: Bip32KeyNetVersions( @@ -112,7 +113,7 @@ class Bip49Conf { static final BipLitecoinConf litecoinTestNet = BipLitecoinConf( coinNames: CoinsConf.litecoinTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions( List.from([0x04, 0x36, 0xf6, 0xe1]), @@ -136,7 +137,7 @@ class Bip49Conf { static final BipCoinConfig zcashMainNet = BipCoinConfig( coinNames: CoinsConf.zcashMainNet.coinName, coinIdx: Slip44.zcash, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip49BtcKeyNetVerMain, wifNetVer: CoinsConf.zcashMainNet.params.wifNetVer, @@ -150,7 +151,7 @@ class Bip49Conf { static final BipCoinConfig zcashTestNet = BipCoinConfig( coinNames: CoinsConf.zcashTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: bip49BtcKeyNetVerTest, wifNetVer: CoinsConf.zcashTestNet.params.wifNetVer, @@ -166,7 +167,7 @@ class Bip49Conf { static final BipCoinConfig bitcoinMainNet = BipCoinConfig( coinNames: CoinsConf.bitcoinMainNet.coinName, coinIdx: Slip44.bitcoin, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip49BtcKeyNetVerMain, wifNetVer: CoinsConf.bitcoinMainNet.params.wifNetVer, @@ -180,7 +181,7 @@ class Bip49Conf { static final BipCoinConfig bitcoinTestNet = BipCoinConfig( coinNames: CoinsConf.bitcoinTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: bip49BtcKeyNetVerTest, wifNetVer: CoinsConf.bitcoinTestNet.params.wifNetVer, @@ -194,7 +195,7 @@ class Bip49Conf { static final BipCoinConfig bitcoinSvMainNet = BipCoinConfig( coinNames: CoinsConf.bitcoinSvMainNet.coinName, coinIdx: Slip44.bitcoinSv, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip49BtcKeyNetVerMain, wifNetVer: CoinsConf.bitcoinSvMainNet.params.wifNetVer, @@ -208,7 +209,7 @@ class Bip49Conf { static final BipCoinConfig bitcoinSvTestNet = BipCoinConfig( coinNames: CoinsConf.bitcoinSvTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: bip49BtcKeyNetVerTest, wifNetVer: CoinsConf.bitcoinSvTestNet.params.wifNetVer, @@ -223,7 +224,7 @@ class Bip49Conf { static final BipBitcoinCashConf bitcoinCashMainNet = BipBitcoinCashConf( coinNames: CoinsConf.bitcoinCashMainNet.coinName, coinIdx: Slip44.bitcoinCash, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip49BtcKeyNetVerMain, wifNetVer: CoinsConf.bitcoinCashMainNet.params.wifNetVer, @@ -249,7 +250,7 @@ class Bip49Conf { static final BipBitcoinCashConf bitcoinCashTestNet = BipBitcoinCashConf( coinNames: CoinsConf.bitcoinCashTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, addressEncoder: ([dynamic legacy]) { if (legacy == true) { @@ -275,7 +276,7 @@ class Bip49Conf { static final BipBitcoinCashConf bitcoinCashSlpMainNet = BipBitcoinCashConf( coinNames: CoinsConf.bitcoinCashSlpMainNet.coinName, coinIdx: Slip44.bitcoinCash, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip49BtcKeyNetVerMain, wifNetVer: CoinsConf.bitcoinCashSlpMainNet.params.wifNetVer, @@ -301,7 +302,7 @@ class Bip49Conf { static final BipBitcoinCashConf bitcoinCashSlpTestNet = BipBitcoinCashConf( coinNames: CoinsConf.bitcoinCashSlpTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: bip49BtcKeyNetVerTest, wifNetVer: CoinsConf.bitcoinCashSlpTestNet.params.wifNetVer, @@ -329,7 +330,7 @@ class Bip49Conf { static final BipBitcoinCashConf ecashMainNet = BipBitcoinCashConf( coinNames: CoinsConf.ecashMainNet.coinName, coinIdx: Slip44.bitcoinCash, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip49BtcKeyNetVerMain, wifNetVer: CoinsConf.ecashMainNet.params.wifNetVer, @@ -355,7 +356,7 @@ class Bip49Conf { static final BipBitcoinCashConf ecashTestNet = BipBitcoinCashConf( coinNames: CoinsConf.ecashTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: bip49BtcKeyNetVerTest, wifNetVer: CoinsConf.ecashTestNet.params.wifNetVer, @@ -381,7 +382,7 @@ class Bip49Conf { static final BipCoinConfig pepeMainnet = BipCoinConfig( coinNames: CoinsConf.pepeMainnet.coinName, coinIdx: Slip44.pepecoin, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions( List.from([0x02, 0xfa, 0xca, 0xfd]), @@ -398,7 +399,7 @@ class Bip49Conf { static final BipCoinConfig pepeTestnet = BipCoinConfig( coinNames: CoinsConf.pepeTestnet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions( List.from([0x04, 0x32, 0xa9, 0xa8]), @@ -415,7 +416,7 @@ class Bip49Conf { static final BipCoinConfig electraProtocolMainNet = BipCoinConfig( coinNames: CoinsConf.electraProtocolMainNet.coinName, coinIdx: Slip44.electraProtocol, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions( List.from([0x04, 0x88, 0xb2, 0x1e]), @@ -433,7 +434,7 @@ class Bip49Conf { static final BipCoinConfig electraProtocolTestNet = BipCoinConfig( coinNames: CoinsConf.electraProtocolTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions( List.from([0x04, 0x35, 0x87, 0xcf]), diff --git a/lib/bip/bip/conf/bip84/bip84_coins.dart b/lib/bip/bip/conf/bip84/bip84_coins.dart index ba45a2b..492362a 100644 --- a/lib/bip/bip/conf/bip84/bip84_coins.dart +++ b/lib/bip/bip/conf/bip84/bip84_coins.dart @@ -69,14 +69,13 @@ class Bip84Coins extends BipCoins { static const Bip84Coins litecoinTestnet = Bip84Coins._('litecoinTestnet'); static const Bip84Coins electraProtocolTestnet = Bip84Coins._('electraProtocolTestnet'); - static const List values = [ bitcoin, litecoin, electraProtocol, bitcoinTestnet, litecoinTestnet, - electraProtocolTestnet, + electraProtocolTestnet ]; final String name; diff --git a/lib/bip/bip/conf/bip84/bip84_conf.dart b/lib/bip/bip/conf/bip84/bip84_conf.dart index 79b7ea0..4ff3fcf 100644 --- a/lib/bip/bip/conf/bip84/bip84_conf.dart +++ b/lib/bip/bip/conf/bip84/bip84_conf.dart @@ -1,7 +1,8 @@ -import 'package:blockchain_utils/bip/address/encoders.dart'; +import 'package:blockchain_utils/bip/address/p2wpkh_addr.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_key_net_ver.dart'; import 'package:blockchain_utils/bip/bip/conf/config/bip_coin_conf.dart'; import 'package:blockchain_utils/bip/bip/conf/const/bip_conf_const.dart'; +import 'package:blockchain_utils/bip/bip/conf/core/coin_conf.dart'; import 'package:blockchain_utils/bip/coin_conf/constant/coins_conf.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; import 'package:blockchain_utils/bip/slip/slip44/slip44.dart'; @@ -19,7 +20,7 @@ class Bip84Conf { static final BipCoinConfig bitcoinMainNet = BipCoinConfig( coinNames: CoinsConf.bitcoinMainNet.coinName, coinIdx: Slip44.bitcoin, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip84BtcKeyNetVer, wifNetVer: CoinsConf.bitcoinMainNet.params.wifNetVer, @@ -32,7 +33,7 @@ class Bip84Conf { static final BipCoinConfig bitcoinTestNet = BipCoinConfig( coinNames: CoinsConf.bitcoinTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions( List.from([0x04, 0x5f, 0x1c, 0xf6]), @@ -48,7 +49,7 @@ class Bip84Conf { static final BipCoinConfig litecoinMainNet = BipCoinConfig( coinNames: CoinsConf.litecoinMainNet.coinName, coinIdx: Slip44.litecoin, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip84BtcKeyNetVer, wifNetVer: CoinsConf.litecoinMainNet.params.wifNetVer, @@ -61,7 +62,7 @@ class Bip84Conf { static final BipCoinConfig litecoinTestNet = BipCoinConfig( coinNames: CoinsConf.litecoinTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions( List.from([0x04, 0x36, 0xf6, 0xe1]), @@ -77,7 +78,7 @@ class Bip84Conf { static final BipCoinConfig electraProtocolMainNet = BipCoinConfig( coinNames: CoinsConf.electraProtocolMainNet.coinName, coinIdx: Slip44.electraProtocol, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions( List.from([0x04, 0x88, 0xb2, 0x1e]), @@ -95,7 +96,7 @@ class Bip84Conf { static final BipCoinConfig electraProtocolTestNet = BipCoinConfig( coinNames: CoinsConf.electraProtocolTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32KeyNetVersions( List.from([0x04, 0x35, 0x87, 0xcf]), diff --git a/lib/bip/bip/conf/bip86/bip86_conf.dart b/lib/bip/bip/conf/bip86/bip86_conf.dart index e21a91c..f52ac76 100644 --- a/lib/bip/bip/conf/bip86/bip86_conf.dart +++ b/lib/bip/bip/conf/bip86/bip86_conf.dart @@ -56,6 +56,7 @@ import 'package:blockchain_utils/bip/address/p2tr_addr.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_const.dart'; import 'package:blockchain_utils/bip/bip/conf/config/bip_coin_conf.dart'; import 'package:blockchain_utils/bip/bip/conf/const/bip_conf_const.dart'; +import 'package:blockchain_utils/bip/bip/conf/core/coin_conf.dart'; import 'package:blockchain_utils/bip/coin_conf/constant/coins_conf.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; import 'package:blockchain_utils/bip/slip/slip44/slip44.dart'; @@ -73,7 +74,7 @@ class Bip86Conf { static BipCoinConfig bitcoinMainNet = BipCoinConfig( coinNames: CoinsConf.bitcoinMainNet.coinName, coinIdx: Slip44.bitcoin, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: bip86BtcKeyNetVer, wifNetVer: CoinsConf.bitcoinMainNet.params.wifNetVer, @@ -88,7 +89,7 @@ class Bip86Conf { static BipCoinConfig bitcoinTestNet = BipCoinConfig( coinNames: CoinsConf.bitcoinTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, addressEncoder: ([dynamic kwargs]) => P2TRAddrEncoder(), keyNetVer: bip86BtcKeyNetVerTest, diff --git a/lib/bip/bip/conf/bip_config.dart b/lib/bip/bip/conf/bip_config.dart index c02caaa..8e3945a 100644 --- a/lib/bip/bip/conf/bip_config.dart +++ b/lib/bip/bip/conf/bip_config.dart @@ -3,7 +3,7 @@ /// and BIP-86. It defines coin names, parameters, and coin configuration data for /// hierarchical deterministic wallets in cryptocurrencies, facilitating wallet development /// and key derivation for a variety of blockchain networks. -library bip_config; +library; export 'bip/bip_coins.dart'; diff --git a/lib/bip/bip/conf/config/bip_bitcoin_cash_conf.dart b/lib/bip/bip/conf/config/bip_bitcoin_cash_conf.dart index 28b0a22..f5061ba 100644 --- a/lib/bip/bip/conf/config/bip_bitcoin_cash_conf.dart +++ b/lib/bip/bip/conf/config/bip_bitcoin_cash_conf.dart @@ -2,8 +2,8 @@ import 'package:blockchain_utils/bip/address/encoder.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_key_net_ver.dart'; import 'package:blockchain_utils/bip/bip/conf/config/bip_coin_conf.dart'; import 'package:blockchain_utils/bip/bip/conf/core/coin_conf.dart'; -import 'package:blockchain_utils/bip/coin_conf/conf.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; +import 'package:blockchain_utils/bip/coin_conf/models/coins_name.dart'; /// A class representing the configuration for Bitcoin Cash (BCH) based on the BIP framework. class BipBitcoinCashConf extends BipCoinConfig { @@ -19,26 +19,17 @@ class BipBitcoinCashConf extends BipCoinConfig { /// Constructor for BipBitcoinCashConf. @override const BipBitcoinCashConf({ - required CoinNames coinNames, - required int coinIdx, - required bool isTestnet, - required String defPath, - required Bip32KeyNetVersions keyNetVer, - required List? wifNetVer, - required EllipticCurveTypes type, - required AddrEncoder addressEncoder, - required Map addrParams, + required super.coinNames, + required super.coinIdx, + required super.chainType, + required super.defPath, + required super.keyNetVer, + required super.wifNetVer, + required super.type, + required super.addressEncoder, + required super.addrParams, this.useLagacyAdder = false, - }) : super( - addrParams: addrParams, - addressEncoder: addressEncoder, - coinIdx: coinIdx, - coinNames: coinNames, - defPath: defPath, - isTestnet: isTestnet, - keyNetVer: keyNetVer, - type: type, - wifNetVer: wifNetVer); + }); /// Overrides the 'addrParams' getter to return the appropriate address parameters /// based on the 'useLagacyAdder' flag. @@ -55,7 +46,7 @@ class BipBitcoinCashConf extends BipCoinConfig { BipBitcoinCashConf copy({ CoinNames? coinNames, int? coinIdx, - bool? isTestnet, + ChainType? chainType, String? defPath, Bip32KeyNetVersions? keyNetVer, Bip32KeyNetVersions? altKeyNetVer, @@ -68,7 +59,7 @@ class BipBitcoinCashConf extends BipCoinConfig { return BipBitcoinCashConf( coinNames: coinNames ?? this.coinNames, coinIdx: coinIdx ?? this.coinIdx, - isTestnet: isTestnet ?? this.isTestnet, + chainType: chainType ?? this.chainType, defPath: defPath ?? this.defPath, keyNetVer: keyNetVer ?? this.keyNetVer, wifNetVer: wifNetVer ?? this.wifNetVer, diff --git a/lib/bip/bip/conf/config/bip_coin_conf.dart b/lib/bip/bip/conf/config/bip_coin_conf.dart index 1b1730f..38ea2ee 100644 --- a/lib/bip/bip/conf/config/bip_coin_conf.dart +++ b/lib/bip/bip/conf/config/bip_coin_conf.dart @@ -57,7 +57,7 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_net_ver.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_keys.dart'; import 'package:blockchain_utils/bip/bip/conf/core/coin_conf.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; -import 'package:blockchain_utils/bip/coin_conf/conf.dart'; +import 'package:blockchain_utils/bip/coin_conf/models/coins_name.dart'; /// A base class representing configuration parameters for a cryptocurrency coin. class BipCoinConfig implements CoinConfig { @@ -71,7 +71,7 @@ class BipCoinConfig implements CoinConfig { final CoinNames coinNames; final int coinIdx; @override - final bool isTestnet; + final ChainType chainType; final String defPath; @override final Bip32KeyNetVersions keyNetVer; @@ -88,7 +88,7 @@ class BipCoinConfig implements CoinConfig { BipCoinConfig copy({ CoinNames? coinNames, int? coinIdx, - bool? isTestnet, + ChainType? chainType, String? defPath, Bip32KeyNetVersions? keyNetVer, List? wifNetVer, @@ -99,7 +99,7 @@ class BipCoinConfig implements CoinConfig { return BipCoinConfig( coinNames: coinNames ?? this.coinNames, coinIdx: coinIdx ?? this.coinIdx, - isTestnet: isTestnet ?? this.isTestnet, + chainType: chainType ?? this.chainType, defPath: defPath ?? this.defPath, keyNetVer: keyNetVer ?? this.keyNetVer, wifNetVer: wifNetVer ?? this.wifNetVer, @@ -112,7 +112,7 @@ class BipCoinConfig implements CoinConfig { const BipCoinConfig({ required this.coinNames, required this.coinIdx, - required this.isTestnet, + required this.chainType, required this.defPath, required this.keyNetVer, required this.wifNetVer, diff --git a/lib/bip/bip/conf/config/bip_litecoin_conf.dart b/lib/bip/bip/conf/config/bip_litecoin_conf.dart index 7153211..25088f8 100644 --- a/lib/bip/bip/conf/config/bip_litecoin_conf.dart +++ b/lib/bip/bip/conf/config/bip_litecoin_conf.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_net_ver.dart'; import 'package:blockchain_utils/bip/bip/conf/config/bip_coin_conf.dart'; import 'package:blockchain_utils/bip/bip/conf/core/coin_conf.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; -import 'package:blockchain_utils/bip/coin_conf/conf.dart'; +import 'package:blockchain_utils/bip/coin_conf/models/coins_name.dart'; /// A class representing the configuration for Litecoin (LTC) based on the BIP framework. class BipLitecoinConf extends BipCoinConfig { @@ -13,28 +13,19 @@ class BipLitecoinConf extends BipCoinConfig { /// Constructor for BipLitecoinConf. const BipLitecoinConf({ - required CoinNames coinNames, - required int coinIdx, - required bool isTestnet, - required String defPath, - required Bip32KeyNetVersions keyNetVer, - required List? wifNetVer, - required EllipticCurveTypes type, - required AddrEncoder addressEncoder, - required Map addrParams, + required super.coinNames, + required super.coinIdx, + required super.chainType, + required super.defPath, + required super.keyNetVer, + required super.wifNetVer, + required super.type, + required super.addressEncoder, + required super.addrParams, required this.altKeyNetVer, this.useAltKeyNetVer = false, this.useDeprAddress = false, - }) : super( - addrParams: addrParams, - addressEncoder: addressEncoder, - coinIdx: coinIdx, - coinNames: coinNames, - defPath: defPath, - isTestnet: isTestnet, - keyNetVer: keyNetVer, - type: type, - wifNetVer: wifNetVer); + }); /// Overrides the 'addrParams' getter to return the appropriate address parameters /// based on the 'useDeprAddress' flag. @@ -58,7 +49,7 @@ class BipLitecoinConf extends BipCoinConfig { BipLitecoinConf copy({ CoinNames? coinNames, int? coinIdx, - bool? isTestnet, + ChainType? chainType, String? defPath, Bip32KeyNetVersions? keyNetVer, Bip32KeyNetVersions? altKeyNetVer, @@ -72,7 +63,7 @@ class BipLitecoinConf extends BipCoinConfig { return BipLitecoinConf( coinNames: coinNames ?? this.coinNames, coinIdx: coinIdx ?? this.coinIdx, - isTestnet: isTestnet ?? this.isTestnet, + chainType: chainType ?? this.chainType, defPath: defPath ?? this.defPath, keyNetVer: keyNetVer ?? this.keyNetVer, wifNetVer: wifNetVer ?? this.wifNetVer, diff --git a/lib/bip/bip/conf/core/coin_conf.dart b/lib/bip/bip/conf/core/coin_conf.dart index 1578cd0..2b88591 100644 --- a/lib/bip/bip/conf/core/coin_conf.dart +++ b/lib/bip/bip/conf/core/coin_conf.dart @@ -1,11 +1,29 @@ import 'package:blockchain_utils/bip/address/encoder.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_key_net_ver.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; -import 'package:blockchain_utils/bip/coin_conf/conf.dart'; +import 'package:blockchain_utils/bip/coin_conf/models/coins_name.dart'; +import 'package:blockchain_utils/exception/const/const.dart'; /// A typedef for the address encoder function that takes optional dynamic parameters. typedef AddrEncoder = BlockchainAddressEncoder Function([dynamic kwargs]); +enum ChainType { + testnet("testnet"), + mainnet("mainnet"); + + final String tr; + const ChainType(this.tr); + bool get isMainnet => this == mainnet; + static ChainType fromValue(dynamic val) { + if (val is bool) { + if (val) return ChainType.mainnet; + return ChainType.testnet; + } + return values.firstWhere((e) => e.name == val, + orElse: () => throw ExceptionConst.itemNotFound(item: 'chain type')); + } +} + /// A base class representing configuration parameters for a cryptocurrency coin. abstract class CoinConfig { /// Base Configuration properties. @@ -13,7 +31,7 @@ abstract class CoinConfig { abstract final AddrEncoder addressEncoder; abstract final EllipticCurveTypes type; abstract final Map addrParams; - abstract final bool? isTestnet; + abstract final ChainType chainType; bool get hasWif; bool get hasExtendedKeys; abstract final Bip32KeyNetVersions? keyNetVer; diff --git a/lib/bip/bip/conf/core/coins.dart b/lib/bip/bip/conf/core/coins.dart index 8199c5c..cadf3fb 100644 --- a/lib/bip/bip/conf/core/coins.dart +++ b/lib/bip/bip/conf/core/coins.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/bip/conf/bip/bip_coins.dart'; import 'package:blockchain_utils/bip/cardano/cip1852/conf/cip1852_coins.dart'; import 'package:blockchain_utils/bip/monero/conf/monero_coins.dart'; import 'package:blockchain_utils/bip/substrate/conf/substrate_coins.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'coin_conf.dart'; /// An abstract class representing a collection of cryptocurrency coins. diff --git a/lib/bip/bip/types/types.dart b/lib/bip/bip/types/types.dart new file mode 100644 index 0000000..3b15423 --- /dev/null +++ b/lib/bip/bip/types/types.dart @@ -0,0 +1,22 @@ +import 'package:blockchain_utils/exception/const/const.dart'; + +/// Enumeration representing different modes for public keys used in P2PKH addresses. +/// +/// This enum defines different modes for public keys that can be used in P2PKH (Pay-to-Public-Key-Hash) +/// addresses. These modes may include compressed and uncompressed public keys, among others. +enum PubKeyModes { + compressed(0), + uncompressed(1); + + const PubKeyModes(this.value); + final int value; + + bool get isCompressed => this == compressed; + + static PubKeyModes fromValue(int? value, {PubKeyModes? defaultValue}) { + return values.firstWhere((e) => e.value == value, orElse: () { + if (defaultValue != null && value == null) return defaultValue; + throw ExceptionConst.itemNotFound(item: 'public format'); + }); + } +} diff --git a/lib/bip/cardano/bip32/cardano_byron_legacy_bip32.dart b/lib/bip/cardano/bip32/cardano_byron_legacy_bip32.dart index e48a675..f20d9a7 100644 --- a/lib/bip/cardano/bip32/cardano_byron_legacy_bip32.dart +++ b/lib/bip/cardano/bip32/cardano_byron_legacy_bip32.dart @@ -22,36 +22,29 @@ import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; /// - [CardanoByronLegacyBip32.fromPublicKey]: Creates a Bip32 key pair from a public key. class CardanoByronLegacyBip32 extends Bip32Base { /// Private constructor for creating an instance with specified parameters. - CardanoByronLegacyBip32._({ - required List? privKey, - required List? pubKey, - required Bip32KeyData keyData, - required Bip32KeyNetVersions keyNetVer, - }) : super( - privKey: privKey, - pubKey: pubKey, - keyData: keyData, - keyNetVer: keyNetVer); + CardanoByronLegacyBip32._( + {required super.privKey, + required super.pubKey, + required super.keyData, + required super.keyNetVer}); /// Creates a [CardanoByronLegacyBip32] instance from a private key. - CardanoByronLegacyBip32.fromPrivateKey(List privKey, - [Bip32KeyData? keyData, Bip32KeyNetVersions? keyNetVer]) - : super.fromPrivateKey(privKey, keyData, keyNetVer); + CardanoByronLegacyBip32.fromPrivateKey(super.privKey, + [super.keyData, super.keyNetVer]) + : super.fromPrivateKey(); /// Creates a [CardanoByronLegacyBip32] instance from a extended key. - CardanoByronLegacyBip32.fromExtendedKey(String exKeyStr, - [Bip32KeyNetVersions? keyNetVer]) - : super.fromExtendedKey(exKeyStr, keyNetVer); + CardanoByronLegacyBip32.fromExtendedKey(super.exKeyStr, [super.keyNetVer]) + : super.fromExtendedKey(); /// Creates a [CardanoByronLegacyBip32] instance from a public key. - CardanoByronLegacyBip32.fromPublicKey(List pubkey, - [Bip32KeyData? keyData, Bip32KeyNetVersions? keyNetVer]) - : super.fromPublicKey(pubkey, keyData, keyNetVer); + CardanoByronLegacyBip32.fromPublicKey(super.pubkey, + [super.keyData, super.keyNetVer]) + : super.fromPublicKey(); /// Creates a [CardanoByronLegacyBip32] instance from a seed. - CardanoByronLegacyBip32.fromSeed(List seedBytes, - [Bip32KeyNetVersions? keyNetVer]) - : super.fromSeed(seedBytes, keyNetVer); + CardanoByronLegacyBip32.fromSeed(super.seedBytes, [super.keyNetVer]) + : super.fromSeed(); /// Generates a child key based on the given [index]. /// 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 a300d78..e56a52e 100644 --- a/lib/bip/cardano/bip32/cardano_byron_legacy_key_derivator.dart +++ b/lib/bip/cardano/bip32/cardano_byron_legacy_key_derivator.dart @@ -14,11 +14,13 @@ class CardanoByronLegacyKeyDerivator @override List newPrivateKeyLeftPart( List zlBytes, List klBytes, EllipticCurveTypes type) { - List multiPly = zlBytes.map((e) => (e * 8) & mask8).toList(); - BigInt zl8Int = BigintUtils.fromBytes(multiPly, byteOrder: Endian.little); - BigInt klInt = BigintUtils.fromBytes(klBytes, byteOrder: Endian.little); + final List multiPly = zlBytes.map((e) => (e * 8) & mask8).toList(); + final BigInt zl8Int = + BigintUtils.fromBytes(multiPly, byteOrder: Endian.little); + final BigInt klInt = + BigintUtils.fromBytes(klBytes, byteOrder: Endian.little); final curve = EllipticCurveGetter.generatorFromType(type); - BigInt newPrivateKeyInt = (zl8Int + klInt) % curve.order!; + final BigInt newPrivateKeyInt = (zl8Int + klInt) % curve.order!; return BigintUtils.toBytes(newPrivateKeyInt, length: 32, order: Endian.little); } @@ -37,7 +39,8 @@ class CardanoByronLegacyKeyDerivator EDPoint newPublicKeyPoint(Bip32PublicKey pubKey, List zlBytes) { final curve = EllipticCurveGetter.generatorFromType(pubKey.curveType); final multiply = zlBytes.map((e) => (e * 8) & mask8).toList(); - BigInt zl8Int = BigintUtils.fromBytes(multiply, byteOrder: Endian.little); + final BigInt zl8Int = + BigintUtils.fromBytes(multiply, byteOrder: Endian.little); return pubKey.point + (curve * zl8Int) as EDPoint; } 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 2a51959..52a5408 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,7 +1,7 @@ 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/cbor/types/bytes.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/utils/utils.dart'; /// A class that holds constants related to the Cardano Byron legacy master key generation process. @@ -34,7 +34,7 @@ class CardanoByronLegacyMstKeyGenerator extends IBip32MstKeyGenerator { itrNum.toString()) .codeUnits, ])); - List keyBytes = + final List keyBytes = _tweakMasterKeyBits(QuickCrypto.sha512Hash(halves.item1)); if (BitUtils.areBitsSet(keyBytes[31], 0x20)) { return _hashRepeatedly(dataBytes, itrNum + 1); diff --git a/lib/bip/cardano/bip32/cardano_icarus_bip32.dart b/lib/bip/cardano/bip32/cardano_icarus_bip32.dart index aa84fb4..8849271 100644 --- a/lib/bip/cardano/bip32/cardano_icarus_bip32.dart +++ b/lib/bip/cardano/bip32/cardano_icarus_bip32.dart @@ -22,16 +22,11 @@ import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; /// - [CardanoIcarusBip32.fromPublicKey]: Creates a Bip32 key pair from a public key. class CardanoIcarusBip32 extends Bip32Base { /// Private constructor for creating an instance with specified parameters. - CardanoIcarusBip32._({ - required List? privKey, - required List? pubKey, - required Bip32KeyData keyData, - required Bip32KeyNetVersions keyNetVer, - }) : super( - keyData: keyData, - keyNetVer: keyNetVer, - pubKey: pubKey, - privKey: privKey); + CardanoIcarusBip32._( + {required super.privKey, + required super.pubKey, + required super.keyData, + required super.keyNetVer}); /// Creates a [CardanoIcarusBip32] instance from a private key. CardanoIcarusBip32.fromPrivateKey(List privKey, @@ -39,9 +34,8 @@ class CardanoIcarusBip32 extends Bip32Base { : super.fromPrivateKey(privKey, keyData, keyNetVer); /// Creates a [CardanoIcarusBip32] instance from a extended key. - CardanoIcarusBip32.fromExtendedKey(String exKeyStr, - [Bip32KeyNetVersions? keyNetVer]) - : super.fromExtendedKey(exKeyStr, keyNetVer); + CardanoIcarusBip32.fromExtendedKey(super.exKeyStr, [super.keyNetVer]) + : super.fromExtendedKey(); /// Creates a [CardanoIcarusBip32] instance from a public key. CardanoIcarusBip32.fromPublicKey(List pubkey, @@ -49,9 +43,8 @@ class CardanoIcarusBip32 extends Bip32Base { : super.fromPublicKey(pubkey, keyData, keyNetVer); /// Creates a [CardanoIcarusBip32] instance from a seed. - CardanoIcarusBip32.fromSeed(List seedBytes, - [Bip32KeyNetVersions? keyNetVer]) - : super.fromSeed(seedBytes, keyNetVer); + CardanoIcarusBip32.fromSeed(super.seedBytes, [super.keyNetVer]) + : super.fromSeed(); /// Generates a child key based on the given [index]. /// 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 bb6b48e..a7f8120 100644 --- a/lib/bip/cardano/bip32/cardano_icarus_mst_key_generator.dart +++ b/lib/bip/cardano/bip32/cardano_icarus_mst_key_generator.dart @@ -5,7 +5,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/utils/utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.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 767fb72..7cacb2f 100644 --- a/lib/bip/cardano/byron/cardano_byron_legacy.dart +++ b/lib/bip/cardano/byron/cardano_byron_legacy.dart @@ -97,7 +97,7 @@ class CardanoByronLegacy { /// the wallet's public key (compressed), chain code, and specified parameters. /// /// Returns: - /// - A List containing the derived HD path key. + /// - A `List` containing the derived HD path key. List get hdPathKey { final hdPath = QuickCrypto.pbkdf2DeriveKey( password: List.from([ diff --git a/lib/bip/cardano/cardano.dart b/lib/bip/cardano/cardano.dart index ab7bf57..ceac047 100644 --- a/lib/bip/cardano/cardano.dart +++ b/lib/bip/cardano/cardano.dart @@ -1,7 +1,7 @@ /// The 'cardano' library provides tools and components related to Cardano blockchain, /// including key derivation, hierarchical deterministic wallets, mnemonic seed generation, /// and more. -library cardano; +library; /// Export statement for Cardano Byron Legacy BIP-32 related components. export 'bip32/cardano_byron_legacy_bip32.dart'; diff --git a/lib/bip/cardano/cip1852/cip1852.dart b/lib/bip/cardano/cip1852/cip1852.dart index 4788e94..9e85bf5 100644 --- a/lib/bip/cardano/cip1852/cip1852.dart +++ b/lib/bip/cardano/cip1852/cip1852.dart @@ -52,11 +52,9 @@ OF THE POSSIBILITY OF SUCH DAMAGE. */ -import 'package:blockchain_utils/bip/bip/bip32/base/bip32_base.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_key_data.dart'; import 'package:blockchain_utils/bip/bip/bip44/base/bip44_base.dart'; import 'package:blockchain_utils/bip/bip/bip44/base/bip44_base_ex.dart'; -import 'package:blockchain_utils/bip/bip/conf/config/bip_coin_conf.dart'; import 'package:blockchain_utils/bip/cardano/cip1852/conf/cip1852_coins.dart'; /// Constants related to CIP-1852 (Cardano Improvement Proposal 1852). @@ -70,11 +68,10 @@ class Cip1852Const { class Cip1852 extends Bip44Base { /// private constractor - Cip1852._(Bip32Base bip32Obj, BipCoinConfig coinConf) - : super(bip32Obj, coinConf); + Cip1852._(super.bip32Obj, super.coinConf); /// Constructor for creating a [Cip1852] object from a bip32 object and coin. - Cip1852.fromBip32(Bip32Base bip, BipCoinConfig coin) : super(bip, coin); + Cip1852.fromBip32(super.bip, super.coin); /// Constructor for creating a [Cip1852] object from a seed and coin. Cip1852.fromSeed(List seedBytes, Cip1852Coins coinType) @@ -161,7 +158,7 @@ class Cip1852 extends Bip44Base { /// derive default path @override Cip1852 get deriveDefaultPath { - Bip44Base bipObj = purpose.coin; + final Bip44Base bipObj = purpose.coin; return Cip1852._( bipObj.bip32.derivePath(bipObj.coinConf.defPath), coinConf); } diff --git a/lib/bip/cardano/cip1852/conf/cip1852_conf.dart b/lib/bip/cardano/cip1852/conf/cip1852_conf.dart index ac081ff..c7360cd 100644 --- a/lib/bip/cardano/cip1852/conf/cip1852_conf.dart +++ b/lib/bip/cardano/cip1852/conf/cip1852_conf.dart @@ -3,6 +3,7 @@ import 'package:blockchain_utils/bip/address/ada/network.dart'; import 'package:blockchain_utils/bip/bip/bip32/bip32_const.dart'; import 'package:blockchain_utils/bip/bip/conf/config/bip_coin_conf.dart'; import 'package:blockchain_utils/bip/bip/conf/const/bip_conf_const.dart'; +import 'package:blockchain_utils/bip/bip/conf/core/coin_conf.dart'; import 'package:blockchain_utils/bip/coin_conf/constant/coins_conf.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; import 'package:blockchain_utils/bip/slip/slip44/slip44.dart'; @@ -13,7 +14,7 @@ class Cip1852Conf { static final BipCoinConfig cardanoIcarusMainNet = BipCoinConfig( coinNames: CoinsConf.cardanoMainNet.coinName, coinIdx: Slip44.cardano, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32Const.kholawKeyNetVersions, wifNetVer: null, @@ -29,7 +30,7 @@ class Cip1852Conf { static final BipCoinConfig cardanoIcarusTestNet = BipCoinConfig( coinNames: CoinsConf.cardanoTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32Const.testNetKeyNetVersions, wifNetVer: null, @@ -45,7 +46,7 @@ class Cip1852Conf { static final BipCoinConfig cardanoLedgerMainNet = BipCoinConfig( coinNames: CoinsConf.cardanoMainNet.coinName, coinIdx: Slip44.cardano, - isTestnet: false, + chainType: ChainType.mainnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32Const.kholawKeyNetVersions, wifNetVer: null, @@ -58,7 +59,7 @@ class Cip1852Conf { static final BipCoinConfig cardanoLedgerTestNet = BipCoinConfig( coinNames: CoinsConf.cardanoTestNet.coinName, coinIdx: Slip44.testnet, - isTestnet: true, + chainType: ChainType.testnet, defPath: derPathNonHardenedFull, keyNetVer: Bip32Const.testNetKeyNetVersions, wifNetVer: null, diff --git a/lib/bip/cardano/mnemonic/cardano_byron_legacy_seed_generator.dart b/lib/bip/cardano/mnemonic/cardano_byron_legacy_seed_generator.dart index ac02ae1..083303b 100644 --- a/lib/bip/cardano/mnemonic/cardano_byron_legacy_seed_generator.dart +++ b/lib/bip/cardano/mnemonic/cardano_byron_legacy_seed_generator.dart @@ -77,7 +77,7 @@ class CardanoByronLegacySeedGenerator { _seedBytes = QuickCrypto.blake2b256Hash(cborData); } - /// Generates and returns the Cardano Byron Legacy seed as a List. + /// Generates and returns the Cardano Byron Legacy seed as a `List`. List generate() { return List.from(_seedBytes); } diff --git a/lib/bip/cardano/mnemonic/cardano_icarus_seed_generator.dart b/lib/bip/cardano/mnemonic/cardano_icarus_seed_generator.dart index 928915f..5dd6f21 100644 --- a/lib/bip/cardano/mnemonic/cardano_icarus_seed_generator.dart +++ b/lib/bip/cardano/mnemonic/cardano_icarus_seed_generator.dart @@ -17,7 +17,7 @@ class CardanoIcarusSeedGenerator { Bip39Languages? language, }) : _entropyBytes = Bip39MnemonicDecoder(language).decode(mnemonic); - /// Generates and returns the Cardano Icarus seed as a List. + /// Generates and returns the Cardano Icarus seed as a `List`. List generate() { return List.from(_entropyBytes); } diff --git a/lib/bip/cardano/shelley/cardano_shelley.dart b/lib/bip/cardano/shelley/cardano_shelley.dart index 8ecb79f..ba2954d 100644 --- a/lib/bip/cardano/shelley/cardano_shelley.dart +++ b/lib/bip/cardano/shelley/cardano_shelley.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/address/ada/ada_shelley_addr.dart'; 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/shelley/cardano_shelley_keys.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// A class that represents a Cardano Shelley wallet, including both public and private keys. class CardanoShelley { diff --git a/lib/bip/coin_conf/conf.dart b/lib/bip/coin_conf/conf.dart deleted file mode 100644 index 742eaa2..0000000 --- a/lib/bip/coin_conf/conf.dart +++ /dev/null @@ -1,3 +0,0 @@ -export 'constant/coins_conf.dart'; -export 'model/coin_conf.dart'; -export 'model/coins_name.dart'; diff --git a/lib/bip/coin_conf/config.dart b/lib/bip/coin_conf/config.dart new file mode 100644 index 0000000..053ee19 --- /dev/null +++ b/lib/bip/coin_conf/config.dart @@ -0,0 +1,3 @@ +export 'constant/coins_conf.dart'; +export 'models/coin_conf.dart'; +export 'models/coins_name.dart'; diff --git a/lib/bip/coin_conf/constant/coins_conf.dart b/lib/bip/coin_conf/constant/coins_conf.dart index f9571f9..15f5c6b 100644 --- a/lib/bip/coin_conf/constant/coins_conf.dart +++ b/lib/bip/coin_conf/constant/coins_conf.dart @@ -1,5 +1,6 @@ -import 'package:blockchain_utils/bip/coin_conf/conf.dart'; +import 'package:blockchain_utils/bip/coin_conf/models/coin_conf.dart'; import 'package:blockchain_utils/bip/slip/slip173/slip173.dart'; +import 'package:blockchain_utils/bip/coin_conf/models/coins_name.dart'; /// Bitcoin network parameters for mainnet and testnet. const btcP2PKHNetVerMn = [0x00]; @@ -712,7 +713,8 @@ class CoinsConf { p2pkhNetVer: [0x37], p2shNetVer: [0x89], wifNetVer: [0xa2], - p2wpkhHrp: "ep", + p2wpkhHrp: Slip173.electraProtocol, + p2wpkhWitVer: btcP2WPKHWitVerMn, ), ); @@ -723,7 +725,8 @@ class CoinsConf { p2pkhNetVer: [0x8d], p2shNetVer: [0x13], wifNetVer: [0xef], - p2wpkhHrp: "te", + p2wpkhHrp: Slip173.electraProtocolTestnet, + p2wpkhWitVer: btcP2WPKHWitVerMn, ), ); } diff --git a/lib/bip/coin_conf/model/coin_conf.dart b/lib/bip/coin_conf/models/coin_conf.dart similarity index 98% rename from lib/bip/coin_conf/model/coin_conf.dart rename to lib/bip/coin_conf/models/coin_conf.dart index 57fcd88..57b1de9 100644 --- a/lib/bip/coin_conf/model/coin_conf.dart +++ b/lib/bip/coin_conf/models/coin_conf.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/bip/coin_conf/conf.dart'; +import 'coins_name.dart'; /// A class representing the configuration of a specific cryptocurrency coin. class CoinConf { diff --git a/lib/bip/coin_conf/model/coins_name.dart b/lib/bip/coin_conf/models/coins_name.dart similarity index 100% rename from lib/bip/coin_conf/model/coins_name.dart rename to lib/bip/coin_conf/models/coins_name.dart diff --git a/lib/bip/ecc/keys/ed25519_blake2b_keys.dart b/lib/bip/ecc/keys/ed25519_blake2b_keys.dart index f01a91c..dddf48a 100644 --- a/lib/bip/ecc/keys/ed25519_blake2b_keys.dart +++ b/lib/bip/ecc/keys/ed25519_blake2b_keys.dart @@ -60,7 +60,7 @@ import 'package:blockchain_utils/crypto/crypto/cdsa/eddsa/keys/privatekey.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/eddsa/keys/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/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/utils/utils.dart'; /// Represents an Ed25519 public key with Blake2b hashing, implementing the IPublicKey interface. diff --git a/lib/bip/ecc/keys/ed25519_keys.dart b/lib/bip/ecc/keys/ed25519_keys.dart index 483ca33..2ede41d 100644 --- a/lib/bip/ecc/keys/ed25519_keys.dart +++ b/lib/bip/ecc/keys/ed25519_keys.dart @@ -5,7 +5,7 @@ import 'package:blockchain_utils/crypto/crypto/cdsa/eddsa/keys/privatekey.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/eddsa/keys/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/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'i_keys.dart'; diff --git a/lib/bip/ecc/keys/ed25519_kholaw_keys.dart b/lib/bip/ecc/keys/ed25519_kholaw_keys.dart index f58f709..01f54f0 100644 --- a/lib/bip/ecc/keys/ed25519_kholaw_keys.dart +++ b/lib/bip/ecc/keys/ed25519_kholaw_keys.dart @@ -6,7 +6,7 @@ import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curves.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/eddsa/keys/privatekey.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/eddsa/keys/publickey.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/edwards.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Constants related to Ed25519-Kholaw keys, specifically the private key length in bytes. class Ed25519KholawKeysConst { diff --git a/lib/bip/ecc/keys/ed25519_monero_keys.dart b/lib/bip/ecc/keys/ed25519_monero_keys.dart index 85b3922..6323ba1 100644 --- a/lib/bip/ecc/keys/ed25519_monero_keys.dart +++ b/lib/bip/ecc/keys/ed25519_monero_keys.dart @@ -59,7 +59,9 @@ import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curves.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/eddsa/keys/privatekey.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/eddsa/keys/publickey.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/edwards.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/crypto/crypto/cdsa/utils/ed25519_utils.dart'; +import 'package:blockchain_utils/crypto/quick_crypto.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/utils/utils.dart'; /// A class representing an Ed25519 Monero-compatible public key that implements the IPublicKey interface. @@ -166,6 +168,9 @@ class MoneroPrivateKey implements IPrivateKey { if (keyBytes.length != Ed25519KeysConst.privKeyByteLen) { throw const ArgumentException("invalid private key length"); } + if (!Ed25519Utils.isValidScalar(keyBytes)) { + throw const ArgumentException("Invalid monero private key."); + } final gn = Curves.generatorED25519; final prv = EDDSAPrivateKey.fromKhalow(gn, keyBytes); return MoneroPrivateKey._(prv); @@ -176,6 +181,19 @@ class MoneroPrivateKey implements IPrivateKey { return MoneroPrivateKey.fromBytes(BytesUtils.fromHexString(keyHex)); } + /// Factory method for creating an MoneroPrivateKey from a BIP-44. + factory MoneroPrivateKey.fromBip44(List keyBytes) { + final privateKey = + IPrivateKey.fromBytes(keyBytes, EllipticCurveTypes.ed25519); + return MoneroPrivateKey.fromBytes( + Ed25519Utils.scalarReduce(QuickCrypto.keccack256Hash(privateKey.raw))); + } + + /// Factory method for creating an MoneroPrivateKey from a BIP-44 hex string. + factory MoneroPrivateKey.fromBip44Hex(String keyHex) { + return MoneroPrivateKey.fromBip44(BytesUtils.fromHexString(keyHex)); + } + /// imutable key List get key => privateKey.key; diff --git a/lib/bip/electrum/electrum.dart b/lib/bip/electrum/electrum.dart index af0fa70..40c8aa3 100644 --- a/lib/bip/electrum/electrum.dart +++ b/lib/bip/electrum/electrum.dart @@ -1,6 +1,6 @@ /// The 'electrum' library provides tools for working with Electrum-style mnemonic phrases /// and address keys, including version 1 (v1) and version 2 (v2) of Electrum standards. -library electrum; +library; /// Export statements for Electrum-style mnemonic version 1 (v1) components. export 'mnemonic_v1/electrum_v1_entropy_generator.dart'; diff --git a/lib/bip/electrum/electrum_v1.dart b/lib/bip/electrum/electrum_v1.dart index 6f1007a..2898cbe 100644 --- a/lib/bip/electrum/electrum_v1.dart +++ b/lib/bip/electrum/electrum_v1.dart @@ -1,6 +1,7 @@ import 'dart:typed_data'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/bip/bip/types/types.dart'; +import 'package:blockchain_utils/exception/exceptions.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'; diff --git a/lib/bip/electrum/electrum_v2.dart b/lib/bip/electrum/electrum_v2.dart index 269ac4c..bd475ed 100644 --- a/lib/bip/electrum/electrum_v2.dart +++ b/lib/bip/electrum/electrum_v2.dart @@ -91,7 +91,7 @@ abstract class ElectrumV2Base { /// Implementation of Electrum V2 for the standard type wallet. class ElectrumV2Standard extends ElectrumV2Base { - ElectrumV2Standard(Bip32Slip10Secp256k1 bip32) : super(bip32); + ElectrumV2Standard(super.bip32); /// Factory method to create an instance from a seed. factory ElectrumV2Standard.fromSeed(List seedBytes) { @@ -129,9 +129,7 @@ class ElectrumV2Standard extends ElectrumV2Base { class ElectrumV2Segwit extends ElectrumV2Base { final Bip32Base bip32Account; - ElectrumV2Segwit(Bip32Slip10Secp256k1 bip32) - : bip32Account = bip32.derivePath("m/0'"), - super(bip32); + ElectrumV2Segwit(super.bip32) : bip32Account = bip32.derivePath("m/0'"); /// Factory method to create an instance from a seed. factory ElectrumV2Segwit.fromSeed(List seedBytes) { diff --git a/lib/bip/electrum/mnemonic_v1/electrum_v1_entropy_generator.dart b/lib/bip/electrum/mnemonic_v1/electrum_v1_entropy_generator.dart index 4f8dcc4..f83a8a0 100644 --- a/lib/bip/electrum/mnemonic_v1/electrum_v1_entropy_generator.dart +++ b/lib/bip/electrum/mnemonic_v1/electrum_v1_entropy_generator.dart @@ -1,5 +1,5 @@ import 'package:blockchain_utils/bip/mnemonic/entropy_generator.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Constants related to Electrum V1 entropy bit lengths. class ElectrumV1EntropyBitLen { diff --git a/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic.dart b/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic.dart index ca66149..1dd3a92 100644 --- a/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic.dart +++ b/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic.dart @@ -64,8 +64,8 @@ class ElectrumV1MnemonicConst { /// A class representing Electrum V1 mnemonics, extending the Bip39Mnemonic class. class ElectrumV1Mnemonic extends Bip39Mnemonic { /// Constructs an Electrum V1 mnemonic from a string representation. - ElectrumV1Mnemonic.fromString(String mnemonic) : super.fromString(mnemonic); + ElectrumV1Mnemonic.fromString(super.mnemonic) : super.fromString(); /// Constructs an Electrum V1 mnemonic from a list of words. - ElectrumV1Mnemonic.fromList(List mnemonic) : super.fromList(mnemonic); + ElectrumV1Mnemonic.fromList(super.mnemonic) : super.fromList(); } diff --git a/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_decoder.dart b/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_decoder.dart index 46ffca6..242e786 100644 --- a/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_decoder.dart +++ b/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_decoder.dart @@ -3,7 +3,7 @@ import 'package:blockchain_utils/bip/electrum/mnemonic_v1/electrum_v1_mnemonic.d import 'package:blockchain_utils/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_utils.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_decoder_base.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// A class for decoding Electrum V1 mnemonics, extending the MnemonicDecoderBase class. class ElectrumV1MnemonicDecoder extends MnemonicDecoderBase { @@ -16,7 +16,7 @@ class ElectrumV1MnemonicDecoder extends MnemonicDecoderBase { wordsListGetter: ElectrumV1WordsListGetter(), ); - /// Decodes an Electrum V1 mnemonic string into a List representing entropy. + /// Decodes an Electrum V1 mnemonic string into a `List` representing entropy. /// /// This method takes an Electrum V1 mnemonic string as input and processes it to obtain /// the corresponding entropy bytes. It validates the mnemonic's word count and detects @@ -25,7 +25,7 @@ class ElectrumV1MnemonicDecoder extends MnemonicDecoderBase { /// /// Throws an ArgumentException if the mnemonic words count is not valid. /// - /// Returns a List containing the decoded entropy bytes. + /// Returns a `List` containing the decoded entropy bytes. /// /// [mnemonic]: The Electrum V1 mnemonic string to decode. @override diff --git a/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_encoder.dart b/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_encoder.dart index d59f820..2c11462 100644 --- a/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_encoder.dart +++ b/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_encoder.dart @@ -6,7 +6,7 @@ import 'package:blockchain_utils/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_u 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/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// A class for encoding data into Electrum V1 mnemonics, extending the MnemonicEncoderBase class. class ElectrumV1MnemonicEncoder extends MnemonicEncoderBase { @@ -20,26 +20,26 @@ class ElectrumV1MnemonicEncoder extends MnemonicEncoderBase { [ElectrumV1Languages language = ElectrumV1Languages.english]) : super(language, ElectrumV1WordsListGetter()); - /// Encodes a List of entropy bytes into an Electrum V1 mnemonic. + /// Encodes a `List` of entropy bytes into an Electrum V1 mnemonic. /// - /// This method takes a List of entropy bytes as input and generates an Electrum V1 mnemonic by + /// This method takes a `List` of entropy bytes as input and generates an Electrum V1 mnemonic by /// dividing the entropy into 4-byte chunks and converting each chunk into a list of mnemonic words. /// It checks the validity of the entropy byte length and throws an ArgumentException if it's not valid. /// /// Returns an Electrum V1 mnemonic representing the encoded data. /// - /// [entropyBytes]: The List of entropy bytes to encode. + /// [entropyBytes]: The `List` of entropy bytes to encode. @override Mnemonic encode(List entropyBytes) { // Check entropy length - int entropyByteLen = entropyBytes.length; + final int entropyByteLen = entropyBytes.length; if (!ElectrumV1EntropyGenerator.isValidEntropyByteLength(entropyByteLen)) { throw ArgumentException( 'Entropy byte length ($entropyByteLen) is not valid'); } // Build mnemonic - List mnemonic = []; + final List mnemonic = []; for (int i = 0; i < entropyBytes.length ~/ 4; i++) { mnemonic.addAll(MnemonicUtils.bytesChunkToWords( entropyBytes.sublist(i * 4, (i * 4) + 4), wordsList, 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 fbf3a87..bbfbdac 100644 --- a/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_generator.dart +++ b/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_generator.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/electrum/mnemonic_v1/electrum_v1_entropy_ge import 'package:blockchain_utils/bip/electrum/mnemonic_v1/electrum_v1_mnemonic.dart'; import 'package:blockchain_utils/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_encoder.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Constants related to Electrum V1 mnemonic generation, mapping the number of words to entropy length. class ElectrumV1MnemonicGeneratorConst { @@ -49,7 +49,7 @@ class ElectrumV1MnemonicGenerator { .firstWhere((element) => element.value == wordsNum); /// Get the corresponding entropy bit length - int entropyBitLen = + final int entropyBitLen = ElectrumV1MnemonicGeneratorConst.wordsNumToEntropyLen[wNum]!; /// Generate entropy bytes with the specified bit length @@ -60,15 +60,15 @@ class ElectrumV1MnemonicGenerator { return fromEntropy(entropyBytes); } - /// Generates an Electrum V1 mnemonic from a List of entropy bytes. + /// Generates an Electrum V1 mnemonic from a `List` of entropy bytes. /// - /// This method takes a List of entropy bytes as input and encodes it into an Electrum V1 mnemonic + /// This method takes a `List` of entropy bytes as input and encodes it into an Electrum V1 mnemonic /// using the associated `ElectrumV1MnemonicEncoder`. It essentially converts the raw entropy into a human-readable /// mnemonic for secure storage and recovery of data. /// /// Returns an Electrum V1 mnemonic generated from the provided entropy bytes. /// - /// [entropyBytes]: The List of entropy bytes to use for mnemonic generation. + /// [entropyBytes]: The `List` of entropy bytes to use for mnemonic generation. Mnemonic fromEntropy(List entropyBytes) { return encoder.encode(entropyBytes); } 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 dd07db1..f6412de 100644 --- a/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_utils.dart +++ b/lib/bip/electrum/mnemonic_v1/electrum_v1_mnemonic_utils.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/electrum/mnemonic_v1/electrum_v1_mnemonic.d import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_utils.dart'; import 'package:blockchain_utils/utils/utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// A class responsible for fetching Electrum V1 mnemonic word lists based on language. class ElectrumV1WordsListGetter extends MnemonicWordsListGetterBase { 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 9c8ff75..68a11db 100644 --- a/lib/bip/electrum/mnemonic_v1/electrum_v1_seed_generator.dart +++ b/lib/bip/electrum/mnemonic_v1/electrum_v1_seed_generator.dart @@ -29,7 +29,7 @@ class ElectrumV1SeedGenerator { /// Generates the Electrum V1 seed. /// - /// Returns the generated Electrum V1 seed as a List. + /// Returns the generated Electrum V1 seed as a `List`. List generate() { return List.from(_seed); } diff --git a/lib/bip/electrum/mnemonic_v1/wrodlist/languages.dart b/lib/bip/electrum/mnemonic_v1/wrodlist/languages.dart index 39282af..602cd70 100644 --- a/lib/bip/electrum/mnemonic_v1/wrodlist/languages.dart +++ b/lib/bip/electrum/mnemonic_v1/wrodlist/languages.dart @@ -1,6 +1,6 @@ /// Library for Electrum V1 mnemonic language support. -library elctrum_v1_mnemonic_languages; +library; /// Part for the English Electrum V1 mnemonic language. part 'english.dart'; 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 28995ce..87a81f6 100644 --- a/lib/bip/electrum/mnemonic_v2/electrum_v2_entropy_generator.dart +++ b/lib/bip/electrum/mnemonic_v2/electrum_v2_entropy_generator.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic.dart'; import 'package:blockchain_utils/bip/mnemonic/entropy_generator.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Constants representing bit lengths for Electrum V2 entropy. class ElectrumV2EntropyBitLen { @@ -38,7 +38,7 @@ class ElectrumV2EntropyGenerator extends EntropyGenerator { /// [bitLen]: The bit length to be checked. /// Returns true if the bit length is valid, otherwise false. static bool isValidEntropyBitLen(int bitLen) { - for (int entropyBitLen in ElectrumV2EntropyGeneratorConst.entropyBitLen) { + for (final entropyBitLen in ElectrumV2EntropyGeneratorConst.entropyBitLen) { if (entropyBitLen - ElectrumV2MnemonicConst.wordBitLen <= bitLen && bitLen <= entropyBitLen) { return true; diff --git a/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic.dart b/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic.dart index 16d8856..70fbc74 100644 --- a/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic.dart +++ b/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic.dart @@ -129,8 +129,8 @@ class ElectrumV2MnemonicConst { /// Electrum V2 mnemonic class, extending the Bip39Mnemonic class. class ElectrumV2Mnemonic extends Bip39Mnemonic { /// Constructs an Electrum V2 mnemonic from a string. - ElectrumV2Mnemonic.fromString(String mnemonic) : super.fromString(mnemonic); + ElectrumV2Mnemonic.fromString(super.mnemonic) : super.fromString(); /// Constructs an Electrum V2 mnemonic from a list of words. - ElectrumV2Mnemonic.fromList(List mnemonic) : super.fromList(mnemonic); + ElectrumV2Mnemonic.fromList(super.mnemonic) : super.fromList(); } 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 6eb6e92..15f24f2 100644 --- a/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_decoder.dart +++ b/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_decoder.dart @@ -3,7 +3,7 @@ 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'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_decoder_base.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// A class for decoding Electrum V2 mnemonics, extending the MnemonicDecoderBase class. class ElectrumV2MnemonicDecoder extends MnemonicDecoderBase { @@ -33,7 +33,7 @@ class ElectrumV2MnemonicDecoder extends MnemonicDecoderBase { /// mnemonic type, and detecting the language if it was not specified during construction. /// /// [mnemonic]: The Electrum V2 mnemonic to decode into entropy bytes. - /// Returns a List containing the decoded entropy bytes. + /// Returns a `List` containing the decoded entropy bytes. @override List decode(String mnemonic) { /// Parse the mnemonic string 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 f5beb54..fd400b3 100644 --- a/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_encoder.dart +++ b/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_encoder.dart @@ -5,7 +5,7 @@ import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic.d import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_utils.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_encoder_base.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// A class for encoding data into Electrum V2 mnemonics, extending the MnemonicEncoderBase class. class ElectrumV2MnemonicEncoder extends MnemonicEncoderBase { @@ -24,7 +24,7 @@ class ElectrumV2MnemonicEncoder extends MnemonicEncoderBase { /// Encodes entropy bytes into an Electrum V2 mnemonic. /// - /// This method takes a List of entropy bytes as input and encodes them into an Electrum V2 mnemonic. It ensures + /// This method takes a `List` of entropy bytes as input and encodes them into an Electrum V2 mnemonic. It ensures /// that the entropy bits are sufficient for generating a valid mnemonic, and that the resulting mnemonic is valid for /// the specified mnemonic type. The method performs the encoding by repeatedly dividing the entropy value by the number /// of words in the word list and adding the corresponding words to the mnemonic. 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 c9f2b37..da00506 100644 --- a/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_generator.dart +++ b/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_generator.dart @@ -3,7 +3,7 @@ import 'package:blockchain_utils/bip/electrum/mnemonic_v2/electrum_v2_entropy_ge 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'; import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Constants related to Electrum V2 mnemonic generation. class ElectrumV2MnemonicGeneratorConst { 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 dd5bc8f..2b650d2 100644 --- a/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_utils.dart +++ b/lib/bip/electrum/mnemonic_v2/electrum_v2_mnemonic_utils.dart @@ -55,7 +55,7 @@ class ElectrumV2MnemonicUtils { final h = BytesUtils.toHexString(QuickCrypto.hmacSha512Hash( ElectrumV2MnemonicUtilsConst.hmacKey, StringUtils.encode(mnemonic.toStr()))); - for (var mnemonicType in ElectrumV2MnemonicTypes.values) { + for (final mnemonicType in ElectrumV2MnemonicTypes.values) { if (h.startsWith(ElectrumV2MnemonicConst.typeToPrefix[mnemonicType]!)) { return true; } diff --git a/lib/bip/mnemonic/mnemonic.dart b/lib/bip/mnemonic/mnemonic.dart index dea2879..c693044 100644 --- a/lib/bip/mnemonic/mnemonic.dart +++ b/lib/bip/mnemonic/mnemonic.dart @@ -1,3 +1,5 @@ +import 'package:blockchain_utils/helper/extensions/extensions.dart'; + /// Represents a mnemonic phrase used for various cryptographic purposes. /// It encapsulates a list of mnemonic words and provides methods for working /// with these words. @@ -10,7 +12,7 @@ class Mnemonic { /// Creates a new Mnemonic instance from a mnemonic phrase provided as a string. /// The provided mnemonic string is normalized into a list of words. Mnemonic.fromString(String mnemonicStr) - : _mnemonicList = List.unmodifiable(_normalize(mnemonicStr)); + : _mnemonicList = _normalize(mnemonicStr); /// Creates a new Mnemonic instance from a list of mnemonic words. Mnemonic.fromList(List mnemonicList) @@ -23,7 +25,7 @@ class Mnemonic { /// Returns the mnemonic phrase as a list of words. List toList() { - return _mnemonicList; + return _mnemonicList.clone(); } /// Returns the mnemonic phrase as a string with words separated by spaces. @@ -34,11 +36,16 @@ class Mnemonic { /// Returns the mnemonic phrase as a string with words separated by spaces. @override String toString() { - return "${toStr().substring(0, toStr().length ~/ 3)}..."; + return "${_mnemonicList.sublist(0, _mnemonicList.length ~/ 3).join(",")}..."; } /// Normalizes a mnemonic string by splitting it into a list of words. static List _normalize(String mnemonic) { - return mnemonic.split(' '); + return mnemonic + .replaceAll(RegExp(r'\s+'), " ") + .split(" ") + .where((element) => element.isNotEmpty) + .toList() + .immutable; } } diff --git a/lib/bip/mnemonic/mnemonic_ex.dart b/lib/bip/mnemonic/mnemonic_ex.dart index 5b723e9..252e4d2 100644 --- a/lib/bip/mnemonic/mnemonic_ex.dart +++ b/lib/bip/mnemonic/mnemonic_ex.dart @@ -1,7 +1,6 @@ -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// An exception representing an error related to mnemonic. class MnemonicException extends BlockchainUtilsException { - const MnemonicException(String message, {Map? details}) - : super(message, details: details); + const MnemonicException(super.message, {super.details}); } diff --git a/lib/bip/mnemonic/mnemonic_utils.dart b/lib/bip/mnemonic/mnemonic_utils.dart index dd71331..6d721a2 100644 --- a/lib/bip/mnemonic/mnemonic_utils.dart +++ b/lib/bip/mnemonic/mnemonic_utils.dart @@ -1,7 +1,7 @@ import 'dart:typed_data'; import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; import 'package:blockchain_utils/utils/utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.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/monero/conf/monero_coin_conf.dart b/lib/bip/monero/conf/monero_coin_conf.dart index 6b338ae..f146396 100644 --- a/lib/bip/monero/conf/monero_coin_conf.dart +++ b/lib/bip/monero/conf/monero_coin_conf.dart @@ -1,6 +1,7 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_net_ver.dart'; import 'package:blockchain_utils/bip/bip/conf/core/coin_conf.dart'; -import 'package:blockchain_utils/bip/coin_conf/conf.dart'; +import 'package:blockchain_utils/bip/coin_conf/models/coin_conf.dart'; +import 'package:blockchain_utils/bip/coin_conf/models/coins_name.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; /// Configuration class for Monero-based cryptocurrencies, specifying various parameters @@ -18,16 +19,17 @@ class MoneroCoinConf implements CoinConfig { /// private constructor MoneroCoinConf._(this.coinNames, this.addrNetVer, this.intAddrNetVer, - this.subaddrNetVer, this.isTestnet); + this.subaddrNetVer, this.chainType); /// MoneroCoinConf from coinConf - factory MoneroCoinConf.fromCoinConf(CoinConf coinConf, {bool? isTestnet}) { + factory MoneroCoinConf.fromCoinConf( + {required CoinConf coinConf, required ChainType chainType}) { return MoneroCoinConf._( coinConf.coinName, coinConf.params.addrNetVer!, coinConf.params.addrIntNetVer!, coinConf.params.subaddrNetVer!, - isTestnet); + chainType); } @override @@ -37,7 +39,7 @@ class MoneroCoinConf implements CoinConfig { EllipticCurveTypes get type => EllipticCurveTypes.ed25519Monero; @override - final bool? isTestnet; + final ChainType chainType; @override bool get hasExtendedKeys => false; diff --git a/lib/bip/monero/conf/monero_conf.dart b/lib/bip/monero/conf/monero_conf.dart index 232de0b..73a9b70 100644 --- a/lib/bip/monero/conf/monero_conf.dart +++ b/lib/bip/monero/conf/monero_conf.dart @@ -1,3 +1,4 @@ +import 'package:blockchain_utils/bip/bip/conf/core/coin_conf.dart'; import 'package:blockchain_utils/bip/coin_conf/constant/coins_conf.dart'; import 'package:blockchain_utils/bip/monero/conf/monero_coin_conf.dart'; @@ -5,14 +6,14 @@ import 'package:blockchain_utils/bip/monero/conf/monero_coin_conf.dart'; /// maps each supported MoneroCoins to its corresponding BipCoinConfig. class MoneroConf { // Configuration for Monero main net - static final MoneroCoinConf mainNet = - MoneroCoinConf.fromCoinConf(CoinsConf.moneroMainNet); + static final MoneroCoinConf mainNet = MoneroCoinConf.fromCoinConf( + coinConf: CoinsConf.moneroMainNet, chainType: ChainType.mainnet); // Configuration for Monero stage net - static final MoneroCoinConf stageNet = - MoneroCoinConf.fromCoinConf(CoinsConf.moneroStageNet); + static final MoneroCoinConf stageNet = MoneroCoinConf.fromCoinConf( + coinConf: CoinsConf.moneroStageNet, chainType: ChainType.testnet); // Configuration for Monero test net - static final MoneroCoinConf testNet = - MoneroCoinConf.fromCoinConf(CoinsConf.moneroTestNet); + static final MoneroCoinConf testNet = MoneroCoinConf.fromCoinConf( + coinConf: CoinsConf.moneroTestNet, chainType: ChainType.testnet); } diff --git a/lib/bip/monero/mnemonic/monero_entropy_generator.dart b/lib/bip/monero/mnemonic/monero_entropy_generator.dart index 0ceac28..25120d8 100644 --- a/lib/bip/monero/mnemonic/monero_entropy_generator.dart +++ b/lib/bip/monero/mnemonic/monero_entropy_generator.dart @@ -1,5 +1,5 @@ import 'package:blockchain_utils/bip/mnemonic/entropy_generator.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Contains constants representing different bit lengths for generating entropy. class MoneroEntropyBitLen { @@ -15,7 +15,7 @@ class MoneroEntropyGeneratorConst { /// List of supported entropy bit lengths for Monero wallets. static final List entropyBitLen = [ MoneroEntropyBitLen.bitLen128, - MoneroEntropyBitLen.bitLen256, + MoneroEntropyBitLen.bitLen256 ]; } diff --git a/lib/bip/monero/mnemonic/monero_mnemonic.dart b/lib/bip/monero/mnemonic/monero_mnemonic.dart index d28e7c0..93619af 100644 --- a/lib/bip/monero/mnemonic/monero_mnemonic.dart +++ b/lib/bip/monero/mnemonic/monero_mnemonic.dart @@ -1,5 +1,6 @@ import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_utils.dart'; +import 'package:blockchain_utils/exception/const/const.dart'; import 'words_list/languages.dart' as languages; /// An enumeration representing the number of words in a Monero mnemonic. @@ -26,6 +27,19 @@ class MoneroWordsNum { /// Constructs a MoneroWordsNum with the specified integer value. const MoneroWordsNum._(this.value); + + static const List values = [ + wordsNum12, + wordsNum13, + wordsNum24, + wordsNum25 + ]; + + static MoneroWordsNum fromValue(int? value) { + return values.firstWhere((e) => e.value == value, + orElse: () => + throw ExceptionConst.itemNotFound(item: "Monero words number")); + } } /// An enumeration of Monero-supported languages for mnemonics. @@ -93,6 +107,12 @@ class MoneroLanguages implements MnemonicLanguages { spanish, russian, ]; + + static MoneroLanguages fromValue(String? value) { + return values.firstWhere((e) => e.name == value, + orElse: () => throw ExceptionConst.itemNotFound( + item: "Monero ${value ?? ''} language")); + } } /// A class containing constants related to Monero mnemonics. @@ -142,8 +162,8 @@ class MoneroMnemonicConst { /// list of mnemonic words. class MoneroMnemonic extends Mnemonic { /// Constructs a MoneroMnemonic from a mnemonic string. - MoneroMnemonic.fromString(String mnemonic) : super.fromString(mnemonic); + MoneroMnemonic.fromString(super.mnemonic) : super.fromString(); /// Constructs a MoneroMnemonic from a list of mnemonic words. - MoneroMnemonic.fromList(List mnemonic) : super.fromList(mnemonic); + MoneroMnemonic.fromList(super.mnemonic) : super.fromList(); } diff --git a/lib/bip/monero/mnemonic/monero_mnemonic_decoder.dart b/lib/bip/monero/mnemonic/monero_mnemonic_decoder.dart index 147ec20..c2ac27e 100644 --- a/lib/bip/monero/mnemonic/monero_mnemonic_decoder.dart +++ b/lib/bip/monero/mnemonic/monero_mnemonic_decoder.dart @@ -4,7 +4,7 @@ import 'package:blockchain_utils/bip/monero/mnemonic/monero_mnemonic.dart'; import 'package:blockchain_utils/bip/monero/mnemonic/monero_mnemonic_utils.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_decoder_base.dart'; import 'package:blockchain_utils/bip/mnemonic/mnemonic_utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import '../../mnemonic/mnemonic_ex.dart'; @@ -18,7 +18,7 @@ class MoneroMnemonicDecoder extends MnemonicDecoderBase { wordsListFinder: MoneroWordsListFinder(), wordsListGetter: MoneroWordsListGetter()); - /// Decodes a Monero mnemonic string into a List representing entropy. + /// Decodes a Monero mnemonic string into a `List` representing entropy. /// /// This method takes a Monero mnemonic string as input and processes it to obtain /// the corresponding entropy bytes. It validates the mnemonic's word count and detects @@ -27,7 +27,7 @@ class MoneroMnemonicDecoder extends MnemonicDecoderBase { /// /// Throws a StateError if the mnemonic words count is not valid. /// - /// Returns a List containing the decoded entropy bytes. + /// Returns a `List` containing the decoded entropy bytes. /// /// [mnemonic]: The Monero mnemonic string to decode. @override @@ -45,10 +45,10 @@ class MoneroMnemonicDecoder extends MnemonicDecoderBase { validateCheckSum(words, lang.item2 as MoneroLanguages); List entropyBytes = List.empty(); for (int i = 0; i < words.length ~/ 3; i++) { - String word1 = words[i * 3]; - String word2 = words[i * 3 + 1]; - String word3 = words[i * 3 + 2]; - List chunkBytes = MnemonicUtils.wordsToBytesChunk( + final String word1 = words[i * 3]; + final String word2 = words[i * 3 + 1]; + final String word3 = words[i * 3 + 2]; + final List chunkBytes = MnemonicUtils.wordsToBytesChunk( word1, word2, word3, lang.item1, endian: Endian.little); entropyBytes = List.from([...entropyBytes, ...chunkBytes]); diff --git a/lib/bip/monero/mnemonic/monero_mnemonic_encoder.dart b/lib/bip/monero/mnemonic/monero_mnemonic_encoder.dart index c79b992..805a1e1 100644 --- a/lib/bip/monero/mnemonic/monero_mnemonic_encoder.dart +++ b/lib/bip/monero/mnemonic/monero_mnemonic_encoder.dart @@ -26,7 +26,7 @@ abstract class MoneroMnemonicEncoderBase extends MnemonicEncoderBase { /// Encodes the provided entropy bytes into a list of Monero mnemonic words. /// - /// This method takes a List of entropy bytes as input and encodes it into + /// This method takes a `List` of entropy bytes as input and encodes it into /// a list of Monero mnemonic words. It validates the entropy byte length and /// converts the bytes into words using the specified Monero language. /// @@ -34,12 +34,12 @@ abstract class MoneroMnemonicEncoderBase extends MnemonicEncoderBase { /// /// [entropyBytes]: The entropy bytes to encode. List _encodeToList(List entropyBytes) { - int entropyByteLen = entropyBytes.length; + final int entropyByteLen = entropyBytes.length; if (!MoneroEntropyGenerator.isValidEntropyByteLen(entropyByteLen)) { throw ArgumentException( 'Entropy byte length ($entropyByteLen) is not valid'); } - List mnemonic = []; + final List mnemonic = []; for (int i = 0; i < entropyByteLen ~/ 4; i++) { mnemonic.addAll(MnemonicUtils.bytesChunkToWords( entropyBytes.sublist(i * 4, (i * 4) + 4), wordsList, @@ -61,9 +61,7 @@ class MoneroMnemonicNoChecksumEncoder extends MoneroMnemonicEncoderBase { /// /// [language]: The Monero language to use for encoding. Defaults to the language /// specified in the superclass. - MoneroMnemonicNoChecksumEncoder( - [MoneroLanguages language = MoneroLanguages.english]) - : super(language); + MoneroMnemonicNoChecksumEncoder([super.language]); /// Encodes the provided entropy bytes into a Monero mnemonic without a checksum. /// @@ -88,9 +86,7 @@ class MoneroMnemonicWithChecksumEncoder extends MoneroMnemonicEncoderBase { /// /// [language]: The Monero language to use for encoding. Defaults to the language /// specified in the superclass. - MoneroMnemonicWithChecksumEncoder( - [MoneroLanguages language = MoneroLanguages.english]) - : super(language); + MoneroMnemonicWithChecksumEncoder([super.language]); /// Encodes the provided entropy bytes into a Monero mnemonic with a checksum. /// @@ -100,8 +96,9 @@ class MoneroMnemonicWithChecksumEncoder extends MoneroMnemonicEncoderBase { /// [entropyBytes]: The entropy bytes to encode. @override Mnemonic encode(List entropyBytes) { - List words = _encodeToList(entropyBytes); - String checksumWord = MoneroMnemonicUtils.computeChecksum(words, language); + final List words = _encodeToList(entropyBytes); + final String checksumWord = + MoneroMnemonicUtils.computeChecksum(words, language); return Mnemonic.fromList([...words, checksumWord]); } diff --git a/lib/bip/monero/mnemonic/monero_mnemonic_generator.dart b/lib/bip/monero/mnemonic/monero_mnemonic_generator.dart index fd8d887..9307014 100644 --- a/lib/bip/monero/mnemonic/monero_mnemonic_generator.dart +++ b/lib/bip/monero/mnemonic/monero_mnemonic_generator.dart @@ -1,5 +1,5 @@ import 'package:blockchain_utils/bip/mnemonic/mnemonic.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'monero_entropy_generator.dart'; import 'monero_mnemonic.dart'; import 'monero_mnemonic_encoder.dart'; @@ -48,9 +48,10 @@ class MoneroMnemonicGenerator { 'Words number for mnemonic ($wordsNum) is not valid'); } - int entropyBitLen = + final int entropyBitLen = MoneroMnemonicGeneratorConst.wordsNumToEntropyLen[wordsNum]!; - List entropyBytes = MoneroEntropyGenerator(entropyBitLen).generate(); + final List entropyBytes = + MoneroEntropyGenerator(entropyBitLen).generate(); return wordsNum == MoneroWordsNum.wordsNum13 || wordsNum == MoneroWordsNum.wordsNum25 diff --git a/lib/bip/monero/mnemonic/monero_mnemonic_utils.dart b/lib/bip/monero/mnemonic/monero_mnemonic_utils.dart index ca7df8a..cc8cfcc 100644 --- a/lib/bip/monero/mnemonic/monero_mnemonic_utils.dart +++ b/lib/bip/monero/mnemonic/monero_mnemonic_utils.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/bip/monero/mnemonic/monero_mnemonic.dart'; 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/exception/exceptions.dart'; import 'package:blockchain_utils/utils/utils.dart'; /// A class that retrieves Monero mnemonic word lists by language. @@ -79,13 +79,24 @@ class MoneroMnemonicUtils { static String computeChecksum( List mnemonic, MnemonicLanguages language) { final uniqueLen = MoneroMnemonicConst.languageUniquePrefixLen[language]!; - String prefixes = mnemonic.map((word) { + final String prefixes = mnemonic.map((word) { final len = word.length >= uniqueLen ? uniqueLen : word.length; return word.substring(0, len); }).join(); - int index = + final int index = Crc32.quickIntDigest(StringUtils.encode(prefixes)) % mnemonic.length; return mnemonic[index]; } + + /// check if the string is valid mnemonic and has correct words length. + static bool isValidMnemonicLength(String? mnemonic) { + if (mnemonic == null) return false; + try { + final lenght = Mnemonic.fromString(mnemonic).toList().length; + return MoneroWordsNum.values.any((e) => e.value == lenght); + } catch (_) { + return false; + } + } } diff --git a/lib/bip/monero/mnemonic/monero_seed_generator.dart b/lib/bip/monero/mnemonic/monero_seed_generator.dart index c82a000..51bcb92 100644 --- a/lib/bip/monero/mnemonic/monero_seed_generator.dart +++ b/lib/bip/monero/mnemonic/monero_seed_generator.dart @@ -24,6 +24,6 @@ class MoneroSeedGenerator { /// This method generates a seed from the decoded entropy bytes obtained from the /// Monero mnemonic. The seed can be used for cryptographic purposes. /// - /// Returns a List containing the generated seed. + /// Returns a `List` containing the generated seed. List generate() => List.from(_entropyBytes); } diff --git a/lib/bip/monero/mnemonic/words_list/languages.dart b/lib/bip/monero/mnemonic/words_list/languages.dart index e47cbb7..afc2807 100644 --- a/lib/bip/monero/mnemonic/words_list/languages.dart +++ b/lib/bip/monero/mnemonic/words_list/languages.dart @@ -1,5 +1,5 @@ /// Library for Monero mnemonic language support. -library monero_mnemonic_languages; +library; import 'package:blockchain_utils/bip/monero/mnemonic/monero_mnemonic.dart'; diff --git a/lib/bip/monero/monero.dart b/lib/bip/monero/monero.dart index 217d003..92e3a2b 100644 --- a/lib/bip/monero/monero.dart +++ b/lib/bip/monero/monero.dart @@ -1,6 +1,6 @@ /// The 'monero' library provides tools for working with Monero cryptocurrency, including /// configuration data, mnemonic phrases, keys, and address generation. -library monero; +library; /// Export statement for Monero coin definitions and configuration. export 'conf/monero_coins.dart'; diff --git a/lib/bip/monero/monero_base.dart b/lib/bip/monero/monero_base.dart index d9c642d..68f1d4b 100644 --- a/lib/bip/monero/monero_base.dart +++ b/lib/bip/monero/monero_base.dart @@ -100,7 +100,7 @@ class MoneroAccount { /// with the associated keys and configurations. factory MoneroAccount.fromSeed(List seedBytes, {MoneroCoins coinType = MoneroCoins.moneroMainnet}) { - List privSkeyBytes = + final List privSkeyBytes = seedBytes.length == Ed25519KeysConst.privKeyByteLen ? seedBytes : QuickCrypto.keccack256Hash(seedBytes); @@ -115,9 +115,8 @@ class MoneroAccount { /// with the associated keys and configurations. factory MoneroAccount.fromBip44PrivateKey(List privKey, {MoneroCoins coinType = MoneroCoins.moneroMainnet}) { - return MoneroAccount.fromPrivateSpendKey( - Ed25519Utils.scalarReduce(QuickCrypto.keccack256Hash(privKey)), - coinType: coinType); + final key = MoneroPrivateKey.fromBip44(privKey); + return MoneroAccount.fromPrivateSpendKey(key.key, coinType: coinType); } /// Factory method to create a Monero instance from a private spend key. @@ -193,7 +192,7 @@ class MoneroAccount { /// Calculate and return the private view key from the private spend key. static MoneroPrivateKey _viewFromSpendKey(MoneroPrivateKey privSkey) { - List privVkeyBytes = + final List privVkeyBytes = Ed25519Utils.scalarReduce(QuickCrypto.keccack256Hash(privSkey.raw)); return MoneroPrivateKey.fromBytes(privVkeyBytes); } diff --git a/lib/bip/monero/monero_exc.dart b/lib/bip/monero/monero_exc.dart index 8ff20cc..a859ee8 100644 --- a/lib/bip/monero/monero_exc.dart +++ b/lib/bip/monero/monero_exc.dart @@ -1,9 +1,8 @@ -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// An exception class representing an error related to Monero keys. /// /// This exception class is used to represent errors and exceptions related to Monero keys. class MoneroKeyError extends BlockchainUtilsException { - const MoneroKeyError(String message, {Map? details}) - : super(message, details: details); + const MoneroKeyError(super.message, {super.details}); } diff --git a/lib/bip/monero/monero_subaddr.dart b/lib/bip/monero/monero_subaddr.dart index 14d2329..165dcef 100644 --- a/lib/bip/monero/monero_subaddr.dart +++ b/lib/bip/monero/monero_subaddr.dart @@ -1,6 +1,6 @@ import 'dart:typed_data'; import 'package:blockchain_utils/bip/ecc/keys/ed25519_monero_keys.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.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'; @@ -76,27 +76,28 @@ class MoneroSubaddress { pubSKey: pubSKey, pubVKey: pubVKey, privateKey: privVKey); } - List majorIdxBytes = IntUtils.toBytes(majorIndex, + final List majorIdxBytes = IntUtils.toBytes(majorIndex, length: MoneroSubaddressConst.subaddrIdxByteLen, byteOrder: Endian.little); - List minorIdxBytes = IntUtils.toBytes(minorIndex, + final List minorIdxBytes = IntUtils.toBytes(minorIndex, length: MoneroSubaddressConst.subaddrIdxByteLen, byteOrder: Endian.little); - List privVKeyBytes = privVKey.raw; + final List privVKeyBytes = privVKey.raw; - List mBytes = QuickCrypto.keccack256Hash(List.from([ + final List mBytes = QuickCrypto.keccack256Hash(List.from([ ...MoneroSubaddressConst.subaddrPrefix, ...privVKeyBytes, ...majorIdxBytes, ...minorIdxBytes ])); - List secretKey = Ed25519Utils.scalarReduce(mBytes); - BigInt mInt = BigintUtils.fromBytes(secretKey, byteOrder: Endian.little); + final List secretKey = Ed25519Utils.scalarReduce(mBytes); + final BigInt mInt = + BigintUtils.fromBytes(secretKey, byteOrder: Endian.little); final newPoint = pubSKey.point + (Curves.generatorED25519 * mInt); - MoneroPublicKey subaddrPubSKey = MoneroPublicKey.fromPoint(newPoint); - MoneroPublicKey subaddrPubVKey = MoneroPublicKey.fromPoint( + final MoneroPublicKey subaddrPubSKey = MoneroPublicKey.fromPoint(newPoint); + final MoneroPublicKey subaddrPubVKey = MoneroPublicKey.fromPoint( (subaddrPubSKey.point * BigintUtils.fromBytes(privVKey.raw, byteOrder: Endian.little))); final sKey = MoneroPrivateKey.fromBytes(secretKey); diff --git a/lib/bip/slip/slip.dart b/lib/bip/slip/slip.dart new file mode 100644 index 0000000..e2174ce --- /dev/null +++ b/lib/bip/slip/slip.dart @@ -0,0 +1,4 @@ +export 'slip173/slip173.dart'; +export 'slip32/slip32.dart'; +export 'slip32/slip32_key_net_ver.dart'; +export 'slip44/slip44.dart'; diff --git a/lib/bip/slip/slip173/slip173.dart b/lib/bip/slip/slip173/slip173.dart index 5663c52..e27401d 100644 --- a/lib/bip/slip/slip173/slip173.dart +++ b/lib/bip/slip/slip173/slip173.dart @@ -22,4 +22,6 @@ class Slip173 { static const String secretNetwork = "secret"; static const String terra = "terra"; static const String zilliqa = "zil"; + static const String electraProtocol = "ep"; + static const String electraProtocolTestnet = "te"; } diff --git a/lib/bip/slip/slip32/slip32.dart b/lib/bip/slip/slip32/slip32.dart index ffdb60f..30c2ed6 100644 --- a/lib/bip/slip/slip32/slip32.dart +++ b/lib/bip/slip/slip32/slip32.dart @@ -4,7 +4,7 @@ import 'package:blockchain_utils/bech32/bech32_base.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/bip/ecc/keys/i_keys.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'slip32_key_net_ver.dart'; @@ -31,8 +31,8 @@ class Slip32KeySerializer { Bip32ChainCode chainCodeOrBip32ChainCode, String keyNetVerStr, ) { - Bip32Path path = Bip32PathParser.parse(pathOrBip32Path); - Bip32ChainCode chainCode = chainCodeOrBip32ChainCode; + final Bip32Path path = Bip32PathParser.parse(pathOrBip32Path); + final Bip32ChainCode chainCode = chainCodeOrBip32ChainCode; // Serialize key final serKey = List.from([ @@ -145,15 +145,15 @@ class Slip32KeyDeserializer { String serKeyStr, Slip32KeyNetVersions keyNetVer, ) { - bool isPublic = _getIfPublic(serKeyStr, keyNetVer); - List serKeyBytes = Bech32Decoder.decode( + final bool isPublic = _getIfPublic(serKeyStr, keyNetVer); + final List serKeyBytes = Bech32Decoder.decode( isPublic ? keyNetVer.public : keyNetVer.private, serKeyStr); // Get parts back - List keyParts = _getPartsFromBytes(serKeyBytes, isPublic); - List keyBytes = keyParts[0]; - Bip32Path path = keyParts[1]; - Bip32ChainCode chainCode = keyParts[2]; + final List keyParts = _getPartsFromBytes(serKeyBytes, isPublic); + final List keyBytes = keyParts[0]; + final Bip32Path path = keyParts[1]; + final Bip32ChainCode chainCode = keyParts[2]; return Slip32DeserializedKey(keyBytes, path, chainCode, isPublic); } @@ -173,24 +173,24 @@ class Slip32KeyDeserializer { /// Extract key parts from serialized key bytes. static List _getPartsFromBytes( List serKeyBytes, bool isPublic) { - int depthIdx = 0; - int pathIdx = depthIdx + Bip32Depth.fixedLength(); + const int depthIdx = 0; + final int pathIdx = depthIdx + Bip32Depth.fixedLength(); // Get back depth and path - int depth = serKeyBytes[depthIdx]; + final int depth = serKeyBytes[depthIdx]; Bip32Path path = Bip32Path(); for (int i = 0; i < depth; i++) { - List keyIndexBytes = serKeyBytes.sublist( + final List keyIndexBytes = serKeyBytes.sublist( pathIdx + (i * Bip32KeyIndex.fixedLength()), pathIdx + ((i + 1) * Bip32KeyIndex.fixedLength())); path = path.addElem(Bip32KeyIndex.fromBytes(keyIndexBytes)); } // Get back chain code and key - int chainCodeIdx = pathIdx + (depth * Bip32KeyIndex.fixedLength()); - int keyIdx = chainCodeIdx + Bip32ChainCode.fixedLength(); + final int chainCodeIdx = pathIdx + (depth * Bip32KeyIndex.fixedLength()); + final int keyIdx = chainCodeIdx + Bip32ChainCode.fixedLength(); - List chainCodeBytes = serKeyBytes.sublist(chainCodeIdx, keyIdx); + final List chainCodeBytes = serKeyBytes.sublist(chainCodeIdx, keyIdx); List keyBytes = serKeyBytes.sublist(keyIdx); // If private key, the first byte shall be zero and shall be removed diff --git a/lib/bip/substrate/conf/substrate_coin_conf.dart b/lib/bip/substrate/conf/substrate_coin_conf.dart index 4b65d4f..ae5cd45 100644 --- a/lib/bip/substrate/conf/substrate_coin_conf.dart +++ b/lib/bip/substrate/conf/substrate_coin_conf.dart @@ -1,6 +1,7 @@ import 'package:blockchain_utils/bip/bip/bip32/bip32_key_net_ver.dart'; import 'package:blockchain_utils/bip/bip/conf/core/coin_conf.dart'; -import 'package:blockchain_utils/bip/coin_conf/conf.dart'; +import 'package:blockchain_utils/bip/coin_conf/models/coin_conf.dart'; +import 'package:blockchain_utils/bip/coin_conf/models/coins_name.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; /// A class representing the configuration for a Substrate-based cryptocurrency. @@ -22,22 +23,23 @@ class SubstrateCoinConf implements CoinConfig { required this.addressEncoder, required this.type, this.addrParams = const {}, - this.isTestnet}); + required this.chainType}); /// Factory method to create a SubstrateCoinConf from a generic CoinConf. /// /// This method takes a generic `CoinConf` instance and extracts the coin names /// and SS58 address format information to create a `SubstrateCoinConf`. - factory SubstrateCoinConf.fromCoinConf({ - required CoinConf coinConf, - required AddrEncoder addressEncode, - required EllipticCurveTypes type, - }) { + factory SubstrateCoinConf.fromCoinConf( + {required CoinConf coinConf, + required AddrEncoder addressEncode, + required EllipticCurveTypes type, + required ChainType chainType}) { return SubstrateCoinConf( coinNames: coinConf.coinName, ss58Format: coinConf.params.addrSs58Format!, addressEncoder: addressEncode, - type: type); + type: type, + chainType: chainType); } @override @@ -50,7 +52,7 @@ class SubstrateCoinConf implements CoinConfig { final Map addrParams; @override - final bool? isTestnet; + final ChainType chainType; @override bool get hasExtendedKeys => false; diff --git a/lib/bip/substrate/conf/substrate_conf.dart b/lib/bip/substrate/conf/substrate_conf.dart index 6cb5497..6f806d9 100644 --- a/lib/bip/substrate/conf/substrate_conf.dart +++ b/lib/bip/substrate/conf/substrate_conf.dart @@ -1,4 +1,5 @@ import 'package:blockchain_utils/bip/address/substrate_addr.dart'; +import 'package:blockchain_utils/bip/bip/conf/core/coin_conf.dart'; import 'package:blockchain_utils/bip/coin_conf/constant/coins_conf.dart'; import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; import 'substrate_coin_conf.dart'; @@ -9,222 +10,264 @@ class SubstrateConf { static final SubstrateCoinConf acalaEd25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.acala, addressEncode: ([kwargs]) => SubstrateEd25519AddrEncoder(), - type: EllipticCurveTypes.ed25519); + type: EllipticCurveTypes.ed25519, + chainType: ChainType.mainnet); // Configuration for Acala static final SubstrateCoinConf acalaSecp256k1 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.acala, addressEncode: ([kwargs]) => SubstrateSecp256k1AddrEncoder(), - type: EllipticCurveTypes.secp256k1); + type: EllipticCurveTypes.secp256k1, + chainType: ChainType.mainnet); static final SubstrateCoinConf acalaSr25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.acala, addressEncode: ([kwargs]) => SubstrateSr25519AddrEncoder(), - type: EllipticCurveTypes.sr25519); + type: EllipticCurveTypes.sr25519, + chainType: ChainType.mainnet); // Configuration for Bifrost static final SubstrateCoinConf bifrostEd25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.bifrost, addressEncode: ([kwargs]) => SubstrateEd25519AddrEncoder(), - type: EllipticCurveTypes.ed25519); + type: EllipticCurveTypes.ed25519, + chainType: ChainType.mainnet); static final SubstrateCoinConf bifrostSecp256k1 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.bifrost, addressEncode: ([kwargs]) => SubstrateSecp256k1AddrEncoder(), - type: EllipticCurveTypes.secp256k1); + type: EllipticCurveTypes.secp256k1, + chainType: ChainType.mainnet); static final SubstrateCoinConf bifrostSr25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.bifrost, addressEncode: ([kwargs]) => SubstrateSr25519AddrEncoder(), - type: EllipticCurveTypes.sr25519); + type: EllipticCurveTypes.sr25519, + chainType: ChainType.mainnet); // Configuration for ChainX static final SubstrateCoinConf chainXEd25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.chainX, addressEncode: ([kwargs]) => SubstrateEd25519AddrEncoder(), - type: EllipticCurveTypes.ed25519); + type: EllipticCurveTypes.ed25519, + chainType: ChainType.mainnet); static final SubstrateCoinConf chainXSecp256k1 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.chainX, addressEncode: ([kwargs]) => SubstrateSecp256k1AddrEncoder(), - type: EllipticCurveTypes.secp256k1); + type: EllipticCurveTypes.secp256k1, + chainType: ChainType.mainnet); static final SubstrateCoinConf chainXSr25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.chainX, addressEncode: ([kwargs]) => SubstrateSr25519AddrEncoder(), - type: EllipticCurveTypes.sr25519); + type: EllipticCurveTypes.sr25519, + chainType: ChainType.mainnet); // Configuration for Edgeware static final SubstrateCoinConf edgewareEd25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.edgeware, addressEncode: ([kwargs]) => SubstrateEd25519AddrEncoder(), - type: EllipticCurveTypes.ed25519); + type: EllipticCurveTypes.ed25519, + chainType: ChainType.mainnet); static final SubstrateCoinConf edgewareSecp256k1 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.edgeware, addressEncode: ([kwargs]) => SubstrateSecp256k1AddrEncoder(), - type: EllipticCurveTypes.secp256k1); + type: EllipticCurveTypes.secp256k1, + chainType: ChainType.mainnet); static final SubstrateCoinConf edgewareSr25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.edgeware, addressEncode: ([kwargs]) => SubstrateSr25519AddrEncoder(), - type: EllipticCurveTypes.sr25519); + type: EllipticCurveTypes.sr25519, + chainType: ChainType.mainnet); // Configuration for generic Substrate coin static final SubstrateCoinConf genericEd25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.genericSubstrate, addressEncode: ([kwargs]) => SubstrateEd25519AddrEncoder(), - type: EllipticCurveTypes.ed25519); + type: EllipticCurveTypes.ed25519, + chainType: ChainType.mainnet); static final SubstrateCoinConf genericSecp256k1 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.genericSubstrate, addressEncode: ([kwargs]) => SubstrateSecp256k1AddrEncoder(), - type: EllipticCurveTypes.secp256k1); + type: EllipticCurveTypes.secp256k1, + chainType: ChainType.mainnet); static final SubstrateCoinConf genericSr25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.genericSubstrate, addressEncode: ([kwargs]) => SubstrateSr25519AddrEncoder(), - type: EllipticCurveTypes.sr25519); + type: EllipticCurveTypes.sr25519, + chainType: ChainType.mainnet); // Configuration for Karura static final SubstrateCoinConf karuraEd25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.karura, addressEncode: ([kwargs]) => SubstrateEd25519AddrEncoder(), - type: EllipticCurveTypes.ed25519); + type: EllipticCurveTypes.ed25519, + chainType: ChainType.mainnet); static final SubstrateCoinConf karuraSecp256k1 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.karura, addressEncode: ([kwargs]) => SubstrateSecp256k1AddrEncoder(), - type: EllipticCurveTypes.secp256k1); + type: EllipticCurveTypes.secp256k1, + chainType: ChainType.mainnet); static final SubstrateCoinConf karuraSr25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.karura, addressEncode: ([kwargs]) => SubstrateSr25519AddrEncoder(), - type: EllipticCurveTypes.sr25519); + type: EllipticCurveTypes.sr25519, + chainType: ChainType.mainnet); // Configuration for Kusama static final SubstrateCoinConf kusamaEd25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.kusama, addressEncode: ([kwargs]) => SubstrateEd25519AddrEncoder(), - type: EllipticCurveTypes.ed25519); + type: EllipticCurveTypes.ed25519, + chainType: ChainType.mainnet); static final SubstrateCoinConf kusamaSecp256k1 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.kusama, addressEncode: ([kwargs]) => SubstrateSecp256k1AddrEncoder(), - type: EllipticCurveTypes.secp256k1); + type: EllipticCurveTypes.secp256k1, + chainType: ChainType.mainnet); static final SubstrateCoinConf kusamaSr25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.kusama, addressEncode: ([kwargs]) => SubstrateSr25519AddrEncoder(), - type: EllipticCurveTypes.sr25519); + type: EllipticCurveTypes.sr25519, + chainType: ChainType.mainnet); // Configuration for Moonbeam static final SubstrateCoinConf moonbeamEd25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.moonbeam, addressEncode: ([kwargs]) => SubstrateEd25519AddrEncoder(), - type: EllipticCurveTypes.ed25519); + type: EllipticCurveTypes.ed25519, + chainType: ChainType.mainnet); static final SubstrateCoinConf moonbeamSecp256k1 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.moonbeam, addressEncode: ([kwargs]) => SubstrateSecp256k1AddrEncoder(), - type: EllipticCurveTypes.secp256k1); + type: EllipticCurveTypes.secp256k1, + chainType: ChainType.mainnet); static final SubstrateCoinConf moonbeamSr25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.moonbeam, addressEncode: ([kwargs]) => SubstrateSr25519AddrEncoder(), - type: EllipticCurveTypes.sr25519); + type: EllipticCurveTypes.sr25519, + chainType: ChainType.mainnet); // Configuration for Moonriver static final SubstrateCoinConf moonriverEd25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.moonriver, addressEncode: ([kwargs]) => SubstrateEd25519AddrEncoder(), - type: EllipticCurveTypes.ed25519); + type: EllipticCurveTypes.ed25519, + chainType: ChainType.mainnet); static final SubstrateCoinConf moonriverSecp256k1 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.moonriver, addressEncode: ([kwargs]) => SubstrateSecp256k1AddrEncoder(), - type: EllipticCurveTypes.secp256k1); + type: EllipticCurveTypes.secp256k1, + chainType: ChainType.mainnet); static final SubstrateCoinConf moonriverSr25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.moonriver, addressEncode: ([kwargs]) => SubstrateSr25519AddrEncoder(), - type: EllipticCurveTypes.sr25519); + type: EllipticCurveTypes.sr25519, + chainType: ChainType.mainnet); // Configuration for Phala static final SubstrateCoinConf phalaEd25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.phala, addressEncode: ([kwargs]) => SubstrateEd25519AddrEncoder(), - type: EllipticCurveTypes.ed25519); + type: EllipticCurveTypes.ed25519, + chainType: ChainType.mainnet); static final SubstrateCoinConf phalaSecp256k1 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.phala, addressEncode: ([kwargs]) => SubstrateSecp256k1AddrEncoder(), - type: EllipticCurveTypes.secp256k1); + type: EllipticCurveTypes.secp256k1, + chainType: ChainType.mainnet); static final SubstrateCoinConf phalaSr25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.phala, addressEncode: ([kwargs]) => SubstrateSr25519AddrEncoder(), - type: EllipticCurveTypes.sr25519); + type: EllipticCurveTypes.sr25519, + chainType: ChainType.mainnet); // Configuration for Plasm static final SubstrateCoinConf plasmEd25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.plasm, addressEncode: ([kwargs]) => SubstrateEd25519AddrEncoder(), - type: EllipticCurveTypes.ed25519); + type: EllipticCurveTypes.ed25519, + chainType: ChainType.mainnet); static final SubstrateCoinConf plasmSecp256k1 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.plasm, addressEncode: ([kwargs]) => SubstrateSecp256k1AddrEncoder(), - type: EllipticCurveTypes.secp256k1); + type: EllipticCurveTypes.secp256k1, + chainType: ChainType.mainnet); static final SubstrateCoinConf plasmSr25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.plasm, addressEncode: ([kwargs]) => SubstrateSr25519AddrEncoder(), - type: EllipticCurveTypes.sr25519); + type: EllipticCurveTypes.sr25519, + chainType: ChainType.mainnet); // Configuration for Polkadot static final SubstrateCoinConf polkadotEd25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.polkadot, addressEncode: ([kwargs]) => SubstrateEd25519AddrEncoder(), - type: EllipticCurveTypes.ed25519); + type: EllipticCurveTypes.ed25519, + chainType: ChainType.mainnet); static final SubstrateCoinConf polkadotSecp256k1 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.polkadot, addressEncode: ([kwargs]) => SubstrateSecp256k1AddrEncoder(), - type: EllipticCurveTypes.secp256k1); + type: EllipticCurveTypes.secp256k1, + chainType: ChainType.mainnet); static final SubstrateCoinConf polkadotSr25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.polkadot, addressEncode: ([kwargs]) => SubstrateSr25519AddrEncoder(), - type: EllipticCurveTypes.sr25519); + type: EllipticCurveTypes.sr25519, + chainType: ChainType.mainnet); // Configuration for Sora static final SubstrateCoinConf soraEd25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.sora, addressEncode: ([kwargs]) => SubstrateEd25519AddrEncoder(), - type: EllipticCurveTypes.ed25519); + type: EllipticCurveTypes.ed25519, + chainType: ChainType.mainnet); static final SubstrateCoinConf soraSecp256k1 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.sora, addressEncode: ([kwargs]) => SubstrateSecp256k1AddrEncoder(), - type: EllipticCurveTypes.secp256k1); + type: EllipticCurveTypes.secp256k1, + chainType: ChainType.mainnet); static final SubstrateCoinConf soraSr25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.sora, addressEncode: ([kwargs]) => SubstrateSr25519AddrEncoder(), - type: EllipticCurveTypes.sr25519); + type: EllipticCurveTypes.sr25519, + chainType: ChainType.mainnet); // Configuration for Stafi static final SubstrateCoinConf stafiEd25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.stafi, addressEncode: ([kwargs]) => SubstrateEd25519AddrEncoder(), - type: EllipticCurveTypes.ed25519); + type: EllipticCurveTypes.ed25519, + chainType: ChainType.mainnet); static final SubstrateCoinConf stafiSecp256k1 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.stafi, addressEncode: ([kwargs]) => SubstrateSecp256k1AddrEncoder(), - type: EllipticCurveTypes.secp256k1); + type: EllipticCurveTypes.secp256k1, + chainType: ChainType.mainnet); static final SubstrateCoinConf stafiSr25519 = SubstrateCoinConf.fromCoinConf( coinConf: CoinsConf.stafi, addressEncode: ([kwargs]) => SubstrateSr25519AddrEncoder(), - type: EllipticCurveTypes.sr25519); + type: EllipticCurveTypes.sr25519, + chainType: ChainType.mainnet); } diff --git a/lib/bip/substrate/core/substrate_base.dart b/lib/bip/substrate/core/substrate_base.dart index 88e7506..90ebf2d 100644 --- a/lib/bip/substrate/core/substrate_base.dart +++ b/lib/bip/substrate/core/substrate_base.dart @@ -6,7 +6,7 @@ import 'package:blockchain_utils/bip/substrate/keys/substrate_keys.dart'; import 'package:blockchain_utils/bip/substrate/path/substrate_path.dart'; import 'package:blockchain_utils/crypto/crypto/schnorrkel/keys/keys.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Constants used in Substrate-related operations. class SubstrateConst { @@ -192,11 +192,8 @@ class Substrate { if (publicKey.coinConf.type == EllipticCurveTypes.sr25519) { return _ckdPrivSr25519(pathElem); } - // if (!pathElem.isHard) { - // throw const SubstrateKeyError( - // 'Public child derivation cannot be used to create a hardened child key'); - // } - List hdkd = publicKey.coinConf.type == EllipticCurveTypes.ed25519 + + final List hdkd = publicKey.coinConf.type == EllipticCurveTypes.ed25519 ? SubstrateConst.hdkd : SubstrateConst.secp256k1HDKD; final key = QuickCrypto.blake2b256Hash([ diff --git a/lib/bip/substrate/exception/substrate_ex.dart b/lib/bip/substrate/exception/substrate_ex.dart index c2e460b..89b9e3c 100644 --- a/lib/bip/substrate/exception/substrate_ex.dart +++ b/lib/bip/substrate/exception/substrate_ex.dart @@ -1,13 +1,11 @@ -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// An exception class representing an error related to Substrate keys. class SubstrateKeyError extends BlockchainUtilsException { - const SubstrateKeyError(String message, {Map? details}) - : super(message, details: details); + const SubstrateKeyError(super.message, {super.details}); } /// An exception class representing an error related to Substrate paths. class SubstratePathError extends BlockchainUtilsException { - const SubstratePathError(String message, {Map? details}) - : super(message, details: details); + const SubstratePathError(super.message, {super.details}); } diff --git a/lib/bip/substrate/keys/substrate_keys.dart b/lib/bip/substrate/keys/substrate_keys.dart index a650088..8b6687c 100644 --- a/lib/bip/substrate/keys/substrate_keys.dart +++ b/lib/bip/substrate/keys/substrate_keys.dart @@ -14,7 +14,7 @@ class SubstratePrvKey { return SubstratePrvKey._(_keyFromBytes(keyBytes, coinConf.type), coinConf); } - /// Gets the raw representation of the private key as a List. + /// Gets the raw representation of the private key as a `List`. List get raw { return privKey.raw; } diff --git a/lib/bip/substrate/scale/substrate_scale_enc_base.dart b/lib/bip/substrate/scale/substrate_scale_enc_base.dart index 8cecf4f..e5567d8 100644 --- a/lib/bip/substrate/scale/substrate_scale_enc_base.dart +++ b/lib/bip/substrate/scale/substrate_scale_enc_base.dart @@ -2,6 +2,6 @@ abstract class SubstrateScaleEncoderBase { const SubstrateScaleEncoderBase(); - /// Encode the provided [value] into a List in Substrate SCALE format. + /// Encode the provided [value] into a `List` in Substrate SCALE format. List encode(String value); } diff --git a/lib/bip/substrate/scale/substrate_scale_enc_bytes.dart b/lib/bip/substrate/scale/substrate_scale_enc_bytes.dart index 7326f34..78826ee 100644 --- a/lib/bip/substrate/scale/substrate_scale_enc_bytes.dart +++ b/lib/bip/substrate/scale/substrate_scale_enc_bytes.dart @@ -10,7 +10,7 @@ class SubstrateScaleBytesEncoder extends SubstrateScaleEncoderBase { @override List encode(String value) { final toBytes = StringUtils.encode(value); - List lengthBytes = + final List lengthBytes = const SubstrateScaleCUintEncoder().encode(toBytes.length.toString()); return List.from([...lengthBytes, ...toBytes]); } diff --git a/lib/bip/substrate/scale/substrate_scale_enc_cuint.dart b/lib/bip/substrate/scale/substrate_scale_enc_cuint.dart index 67d1b4e..07de161 100644 --- a/lib/bip/substrate/scale/substrate_scale_enc_cuint.dart +++ b/lib/bip/substrate/scale/substrate_scale_enc_cuint.dart @@ -25,7 +25,7 @@ class SubstrateScaleCUintEncoder extends SubstrateScaleEncoderBase { /// Encode the provided [value] as a Compact Uint (CUint) in Substrate SCALE format. /// /// This method takes an unsigned integer value [value], encodes it as a Compact Uint (CUint) - /// in Substrate SCALE format, and returns the encoded value as a List. + /// in Substrate SCALE format, and returns the encoded value as a `List`. @override List encode(String value) { final v = BigInt.parse(value); @@ -41,10 +41,12 @@ class SubstrateScaleCUintEncoder extends SubstrateScaleEncoderBase { length: 4, order: Endian.little); } if (v <= SubstrateScaleCUintEncoderConst.bigIntegerModeMaxVal) { - List valueBytes = BigintUtils.toBytes(v, + final List valueBytes = BigintUtils.toBytes(v, order: Endian.little, length: BigintUtils.orderLen(v)); - List lenBytes = IntUtils.toBytes((valueBytes.length - 4 << 2) | 0x03, - length: 1, byteOrder: Endian.little); + final List lenBytes = IntUtils.toBytes( + (valueBytes.length - 4 << 2) | 0x03, + length: 1, + byteOrder: Endian.little); return List.from([...lenBytes, ...valueBytes]); } diff --git a/lib/bip/substrate/scale/substrate_scale_enc_uint.dart b/lib/bip/substrate/scale/substrate_scale_enc_uint.dart index b44dd77..5217c10 100644 --- a/lib/bip/substrate/scale/substrate_scale_enc_uint.dart +++ b/lib/bip/substrate/scale/substrate_scale_enc_uint.dart @@ -1,5 +1,5 @@ import 'dart:typed_data'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/utils/utils.dart'; import 'substrate_scale_enc_base.dart'; diff --git a/lib/bip/substrate/substrate.dart b/lib/bip/substrate/substrate.dart index a014dfe..9784770 100644 --- a/lib/bip/substrate/substrate.dart +++ b/lib/bip/substrate/substrate.dart @@ -1,6 +1,6 @@ /// The 'substrate' library provides tools for working with the Substrate blockchain /// ecosystem, including coin definitions, configuration data, and encoding utilities. -library substrate; +library; /// Export statement for Substrate coin definitions and configuration. export 'conf/substrate_coins.dart'; diff --git a/lib/bip/ton/mnemonic/ton_entropy_generator.dart b/lib/bip/ton/mnemonic/ton_entropy_generator.dart index 902c523..f2000e3 100644 --- a/lib/bip/ton/mnemonic/ton_entropy_generator.dart +++ b/lib/bip/ton/mnemonic/ton_entropy_generator.dart @@ -52,7 +52,7 @@ class TonEntropyGeneratorUtils { /// 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); + TonMnemonicEntropyGenerator(super.bitLen); /// Validates if the given bit length for entropy is within the acceptable range (88 to 528 bits). static bool isValidEntropyBitLen(int bitLen) { diff --git a/lib/bip/ton/mnemonic/ton_mnemonic_encoder.dart b/lib/bip/ton/mnemonic/ton_mnemonic_encoder.dart index ee4ee9a..afb1145 100644 --- a/lib/bip/ton/mnemonic/ton_mnemonic_encoder.dart +++ b/lib/bip/ton/mnemonic/ton_mnemonic_encoder.dart @@ -31,7 +31,7 @@ class TonMnemonicEncoder extends MnemonicEncoderBase { BytesUtils.toBinary(entropyBytes, zeroPadBitLen: entropyByteLen * 8); /// Converts the binary string to a list of mnemonic words. - List mnemonic = []; + final List mnemonic = []; for (int i = 0; i < entropyBinStr.length; i += Bip39MnemonicConst.wordBitLen) { diff --git a/lib/bip/wif/wif.dart b/lib/bip/wif/wif.dart index b4fde9d..e2c1a6f 100644 --- a/lib/bip/wif/wif.dart +++ b/lib/bip/wif/wif.dart @@ -53,10 +53,10 @@ */ import 'package:blockchain_utils/base58/base58.dart'; -import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; +import 'package:blockchain_utils/bip/bip/types/types.dart'; import 'package:blockchain_utils/bip/ecc/keys/secp256k1_keys_ecdsa.dart'; import 'package:blockchain_utils/utils/utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Constants related to Wallet Import Format (WIF). class WifConst { diff --git a/lib/blockchain_utils.dart b/lib/blockchain_utils.dart index 101cf0e..a67c776 100644 --- a/lib/blockchain_utils.dart +++ b/lib/blockchain_utils.dart @@ -1,6 +1,6 @@ /// The `blockchain_utils` library provides a collection of utilities and tools /// for working with various aspects of blockchain and cryptocurrency technologies. -library blockchain_utils; +library; /// Export for Base32 encoding and decoding utilities. export 'base32/base32.dart'; @@ -32,46 +32,9 @@ export 'ss58/ss58.dart'; /// Export for UUID (Universally Unique Identifier) generation and manipulation. export 'uuid/uuid.dart'; -/// Export for cryptocurrency address encoding utilities. -export 'bip/address/encoders.dart'; - -/// Export for cryptocurrency address decoding utilities. -export 'bip/address/decoders.dart'; - -/// Export for Algorand blockchain-specific utilities. -export 'bip/algorand/algorand.dart'; - -/// Export for BIP (Bitcoin Improvement Proposals) utilities. -export 'bip/bip/bip.dart'; - -/// Export for Cardano blockchain-specific utilities. -export 'bip/cardano/cardano.dart'; - -/// Export for Electrum wallet and mnemonic utilities. -export 'bip/electrum/electrum.dart'; - -/// Export for Monero-specific utilities, including mnemonics. -export 'bip/monero/monero.dart'; - -/// Export for Substrate blockchain-specific utilities. -export 'bip/substrate/substrate.dart'; - -/// Export for Wallet Import Format (WIF) encoding and decoding utilities. -export 'bip/wif/wif.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 TON mnemonic. -export 'bip/ton/ton.dart'; - -export 'bip/coin_conf/conf.dart'; - -/// Exports utility functions related to mnemonic. -export 'bip/mnemonic/mnemonic.dart'; +export 'bip/bip.dart'; /// Exports utility functions related to numeric, bytes and strings. export 'utils/utils.dart'; @@ -87,3 +50,4 @@ export 'utils/compare/compare.dart'; export 'layout/layout.dart'; export 'helper/helper.dart'; +export 'service/service.dart'; diff --git a/lib/cbor/cbor.dart b/lib/cbor/cbor.dart index edfd53a..4d1dde5 100644 --- a/lib/cbor/cbor.dart +++ b/lib/cbor/cbor.dart @@ -1,5 +1,5 @@ /// Library for working with Concise Binary Object Representation (CBOR) data format. -library cbor; +library; /// Export statement for the core CBOR data types and decode functionality. export 'core/cbor.dart'; diff --git a/lib/cbor/core/cbor.dart b/lib/cbor/core/cbor.dart index 4c9c91a..2497450 100644 --- a/lib/cbor/core/cbor.dart +++ b/lib/cbor/core/cbor.dart @@ -1,4 +1,5 @@ import 'package:blockchain_utils/cbor/exception/exception.dart'; +import 'package:blockchain_utils/cbor/extention/extenton.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'; @@ -7,7 +8,7 @@ import 'package:blockchain_utils/cbor/utils/cbor_utils.dart'; /// CBOR objects can hold various data types and optional tags, providing a flexible way /// to represent structured data in a compact binary format. abstract class CborObject { - /// Encode the object's value to its CBOR representation and return it as a List. + /// Encode the object's value to its CBOR representation and return it as a `List`. List encode(); /// Convert the object's CBOR representation to a hexadecimal string. @@ -38,13 +39,15 @@ abstract class CborObject { return CborIntValue(value); } else if (value is double) { return CborFloatValue(value); + } else if (value is DateTime) { + return CborEpochFloatValue(value); } else if (value is BigInt) { return CborBigIntValue(value); } else if (value is String) { return CborStringValue(value); } else if (value is List) { return CborIndefiniteStringValue(value); - } else if (value is List) { + } else if (value is List && BytesUtils.isValidBytes(value)) { return CborBytesValue(value); } else if (value is List>) { return CborDynamicBytesValue(value); @@ -53,11 +56,15 @@ abstract class CborObject { for (final i in value.entries) CborObject.fromDynamic(i.key): CborObject.fromDynamic(i.value) }); - } else if (value is List) { + } else if (value is List) { return CborListValue.fixedLength( value.map((e) => CborObject.fromDynamic(e)).toList()); } - throw const CborException("does not supported"); + throw CborException("cbor encoder not found for type ${value.runtimeType}"); + } + + static T deserialize(List bytes) { + return CborObject.fromCbor(bytes).cast(); } } diff --git a/lib/cbor/exception/exception.dart b/lib/cbor/exception/exception.dart index c6f804c..d15aca1 100644 --- a/lib/cbor/exception/exception.dart +++ b/lib/cbor/exception/exception.dart @@ -1,6 +1,5 @@ import 'package:blockchain_utils/exception/exceptions.dart'; class CborException extends BlockchainUtilsException { - const CborException(String message, {Map? details}) - : super(message, details: details); + const CborException(super.message, {super.details}); } diff --git a/lib/cbor/extention/extenton.dart b/lib/cbor/extention/extenton.dart new file mode 100644 index 0000000..20dc6af --- /dev/null +++ b/lib/cbor/extention/extenton.dart @@ -0,0 +1,9 @@ +import 'package:blockchain_utils/blockchain_utils.dart'; + +extension QuickCastingCbor on CborObject { + T cast() { + if (this is T) return this as T; + throw CborException("cbor object casting faild", + details: {"excepted": "$T", "value": runtimeType.toString()}); + } +} diff --git a/lib/cbor/types/bytes.dart b/lib/cbor/types/bytes.dart index f7e070e..b209133 100644 --- a/lib/cbor/types/bytes.dart +++ b/lib/cbor/types/bytes.dart @@ -19,7 +19,7 @@ class CborBytesValue implements CborObject { final bytes = CborBytesTracker(); bytes.pushInt(MajorTags.byteString, value.length); bytes.pushBytes(value); - return bytes.toBytes(); + return bytes.buffer(); } /// Encode the value into CBOR bytes an then to hex @@ -39,6 +39,11 @@ class CborBytesValue implements CborObject { /// ovveride hash code @override int get hashCode => value.hashCode; + + @override + String toString() { + return BytesUtils.toHexString(value); + } } /// A class representing a CBOR (Concise Binary Object Representation) bytes value with indefinite tag. @@ -63,7 +68,7 @@ class CborDynamicBytesValue implements CborObject { bytes.pushBytes(v); } bytes.breakDynamic(); - return bytes.toBytes(); + return bytes.buffer(); } /// Returns the string representation of the value. diff --git a/lib/cbor/types/cbor_tag.dart b/lib/cbor/types/cbor_tag.dart index 1eb3e6c..27876e6 100644 --- a/lib/cbor/types/cbor_tag.dart +++ b/lib/cbor/types/cbor_tag.dart @@ -24,7 +24,7 @@ class CborTagValue implements CborObject { bytes.pushTags(tags); final obj = CborObject.fromDynamic(_value).encode(); bytes.pushBytes(obj); - return bytes.toBytes(); + return bytes.buffer(); } /// Encode the value into CBOR bytes an then to hex diff --git a/lib/cbor/types/string.dart b/lib/cbor/types/string.dart index d94f4d8..c6a64be 100644 --- a/lib/cbor/types/string.dart +++ b/lib/cbor/types/string.dart @@ -40,7 +40,7 @@ class CborStringValue extends CborString { final toBytes = StringUtils.encode(value); bytes.pushInt(MajorTags.utf8String, toBytes.length); bytes.pushBytes(toBytes); - return bytes.toBytes(); + return bytes.buffer(); } /// override equal operation @@ -53,12 +53,17 @@ class CborStringValue extends CborString { /// override hashcode @override int get hashCode => value.hashCode; + + @override + String toString() { + return value; + } } /// A class representing a CBOR (Concise Binary Object Representation) string value with indefinite tag length. class CborIndefiniteStringValue extends CborString { /// Constructor for creating a CborStringValue instance with the provided parameters. - /// It accepts a List value. + /// It accepts a `List` value. CborIndefiniteStringValue(List value) : value = value.immutable; @override diff --git a/lib/cbor/utils/cbor_utils.dart b/lib/cbor/utils/cbor_utils.dart index 97acb7f..d241964 100644 --- a/lib/cbor/utils/cbor_utils.dart +++ b/lib/cbor/utils/cbor_utils.dart @@ -6,11 +6,22 @@ import 'package:blockchain_utils/cbor/utils/float_utils.dart'; import 'package:blockchain_utils/cbor/core/tags.dart'; import 'package:blockchain_utils/utils/utils.dart'; +class _DecodeCborResult { + final T value; + final int consumed; + const _DecodeCborResult({required this.value, required this.consumed}); + _DecodeCborResult addConsumed(int consumed) { + return _DecodeCborResult(value: value, consumed: consumed + this.consumed); + } +} + class CborUtils { - /// Decode a CBOR (Concise Binary Object Representation) data stream represented by a List. + /// Decode a CBOR (Concise Binary Object Representation) data stream represented by a `List`. /// The method decodes the CBOR data and returns the resulting CborObject. static CborObject decodeCbor(List cborBytes) { - return _decode(cborBytes).item1; + final decode = _decode(cborBytes); + assert(decode.consumed == cborBytes.length, "cbor decoding faild."); + return decode.value; } /// Parse a datetime string in RFC3339 format and return a corresponding DateTime object. @@ -33,9 +44,11 @@ class CborUtils { } } - static Tuple _decode(List cborBytes) { + static _DecodeCborResult _decode(List cborBytes, + {int offset = 0}) { final List tags = []; - for (int i = 0; i < cborBytes.length;) { + int consumed = 0; + for (int i = offset; i < cborBytes.length;) { final int first = cborBytes[i]; final majorTag = first >> 5; @@ -43,28 +56,49 @@ class CborUtils { switch (majorTag) { case MajorTags.map: if (info == NumBytes.indefinite) { - return _decodeDynamicMap(cborBytes, i, info, tags); + return _decodeDynamicMap( + cborBytes: cborBytes, offset: i, info: info, tags: tags) + .addConsumed(consumed); } - return _decodeMap(cborBytes, i, info, tags); + return _decodeMap( + cborBytes: cborBytes, offset: i, info: info, tags: tags) + .addConsumed(consumed); case MajorTags.negInt: case MajorTags.posInt: - return _parseInt(majorTag, info, i, cborBytes, tags); + return _parseInt( + mt: majorTag, + info: info, + offset: i, + cborBytes: cborBytes, + tags: tags) + .addConsumed(consumed); case MajorTags.tag: - final data = _decodeLength(info, cborBytes.sublist(i)); - tags.add(data.item1); - i += data.item2; + final data = _decodeLength(info, cborBytes, i); + tags.add(data.value); + i += data.consumed; + consumed += data.consumed; continue; case MajorTags.byteString: - return _decodeBytesString(info, i, cborBytes, tags); + return _decodeBytesString( + info: info, offset: i, cborBytes: cborBytes, tags: tags) + .addConsumed(consumed); case MajorTags.utf8String: - return _decodeUtf8String(info, i, cborBytes, tags); + return _decodeUtf8String( + info: info, offset: i, cborBytes: cborBytes, tags: tags) + .addConsumed(consumed); case MajorTags.simpleOrFloat: - return _parseSimpleValue(i, info, cborBytes, tags); + return _parseSimpleValue( + offset: i, info: info, bytes: cborBytes, tags: tags) + .addConsumed(consumed); case MajorTags.array: if (info == NumBytes.indefinite) { - return _decodeDynamicArray(cborBytes, i, info, tags); + return _decodeDynamicArray( + cborBytes: cborBytes, offset: i, info: info, tags: tags) + .addConsumed(consumed); } - return _decodeArray(cborBytes, i, info, tags); + return _decodeArray( + cborBytes: cborBytes, offset: i, info: info, tags: tags) + .addConsumed(consumed); default: throw CborException( "invalid or unsuported cbor tag major: $majorTag "); @@ -73,52 +107,75 @@ class CborUtils { throw const CborException("invalid or unsuported cbor tag"); } - static Tuple, int> _parsBytes(int info, List cborBytes) { - final len = _decodeLength(info, cborBytes); - final int end = (len.item2 + len.item1 as int); - final bytes = cborBytes.sublist(len.item2, end); - return Tuple(bytes, end); + static _DecodeCborResult> _parsBytes( + {required int info, required List cborBytes, required int offset}) { + final len = _decodeLength(info, cborBytes, offset); + final int end = len.consumed + len.value; + final bytes = cborBytes.sublist(offset + len.consumed, offset + end); + return _DecodeCborResult(value: bytes, consumed: end); } - static Tuple _decodeLength(int info, List cborBytes) { + static _DecodeCborResult _decodeLength( + int info, List cborBytes, int offset) { + Object value; + int consumed = 1; if (info < 24) { - return Tuple(info, 1); - } - final int len = 1 << (info - 24); - List bytes = cborBytes.sublist(1, len + 1); - if (len <= 4) { - final decode = IntUtils.fromBytes(bytes); - return Tuple(decode, len + 1); - } else if (len <= 8) { - final decode = BigintUtils.fromBytes(bytes); - if (decode.isValidInt) { - return Tuple(decode.toInt(), len + 1); - } - return Tuple(decode, len + 1); + value = info; } else { - throw CborException('Invalid additional info for int: $info'); + offset++; + final int len = 1 << (info - 24); + final List bytes = cborBytes.sublist(offset, offset + len); + consumed = len + 1; + if (len <= 4) { + value = IntUtils.fromBytes(bytes); + } else if (len <= 8) { + final decode = BigintUtils.fromBytes(bytes); + if (decode.isValidInt) { + value = decode.toInt(); + } else { + if (0 is T) { + throw const CborException('Length is to large for type int.'); + } + value = decode; + } + } else { + throw CborException('Invalid additional info for int: $info'); + } } + if (value is! T) { + throw CborException("decode length casting faild.", + details: {"excepted": "$T", "value": value.runtimeType}); + } + return _DecodeCborResult(value: value as T, consumed: consumed); } - static Tuple _decodeUtf8String( - int info, int i, List cborBytes, List tags) { + static _DecodeCborResult _decodeUtf8String( + {required int info, + required int offset, + required List cborBytes, + required List tags}) { if (info == NumBytes.indefinite) { - final toList = _decodeDynamicArray(cborBytes, i, info, tags); - final stringList = (toList.item1 as CborListValue) + final toList = _decodeDynamicArray( + cborBytes: cborBytes, offset: offset, info: info, tags: tags); + final stringList = (toList.value as CborListValue) .value .whereType() .map((e) => e.value) .toList(); if (tags.isNotEmpty) { - return Tuple(CborTagValue(CborIndefiniteStringValue(stringList), tags), - toList.item2); + return _DecodeCborResult( + value: CborTagValue(CborIndefiniteStringValue(stringList), tags), + consumed: toList.consumed); } - return Tuple(CborIndefiniteStringValue(stringList), toList.item2); + return _DecodeCborResult( + value: CborIndefiniteStringValue(stringList), + consumed: toList.consumed); } - final bytes = _parsBytes(info, cborBytes.sublist(i)); + final bytes = _parsBytes(info: info, cborBytes: cborBytes, offset: offset); - return Tuple(_toStringObject(bytes.item1, tags), (bytes.item2 + i)); + return _DecodeCborResult( + value: _toStringObject(bytes.value, tags), consumed: bytes.consumed); } static CborObject _toStringObject(List utf8Bytes, List tags) { @@ -150,104 +207,138 @@ class CborUtils { return tags.isEmpty ? toObj : CborTagValue(toObj, tags); } - static Tuple _decodeBytesString( - int info, int i, List cborBytes, List tags) { + static _DecodeCborResult _decodeBytesString( + {required int info, + required int offset, + required List cborBytes, + required List tags}) { if (info == NumBytes.indefinite) { - final toList = _decodeDynamicArray(cborBytes, i, info, tags); - final bytesList = (toList.item1 as CborListValue) + final toList = _decodeDynamicArray( + cborBytes: cborBytes, offset: offset, info: info, tags: tags); + final bytesList = (toList.value as CborListValue) .value .whereType() .map((e) => e.value) .toList(); if (tags.isNotEmpty) { - return Tuple( - CborTagValue(CborDynamicBytesValue(bytesList), tags), toList.item2); + return _DecodeCborResult( + value: CborTagValue(CborDynamicBytesValue(bytesList), tags), + consumed: toList.consumed); } - return Tuple(CborDynamicBytesValue(bytesList), toList.item2); + return _DecodeCborResult( + value: CborDynamicBytesValue(bytesList), consumed: toList.consumed); } - final bytes = _parsBytes(info, cborBytes.sublist(i)); + final bytes = _parsBytes(info: info, cborBytes: cborBytes, offset: offset); CborObject? val; if (BytesUtils.bytesEqual(tags, CborTags.negBigInt) || BytesUtils.bytesEqual(tags, CborTags.posBigInt)) { - BigInt big = BigintUtils.fromBytes(bytes.item1); + BigInt big = BigintUtils.fromBytes(bytes.value); if (BytesUtils.bytesEqual(tags, CborTags.negBigInt)) { big = ~big; } tags.clear(); val = CborBigIntValue(big); } - val ??= CborBytesValue(bytes.item1); - return Tuple(tags.isEmpty ? val : CborTagValue(val, tags), bytes.item2 + i); + val ??= CborBytesValue(bytes.value); + return _DecodeCborResult( + value: tags.isEmpty ? val : CborTagValue(val, tags), + consumed: bytes.consumed); } - static Tuple _decodeMap( - List cborBytes, int offset, int info, List tags) { - final decodeLen = _decodeLength(info, cborBytes); - int index = offset + decodeLen.item2; - final int length = decodeLen.item1; - Map objects = {}; + static _DecodeCborResult _decodeMap( + {required List cborBytes, + required int offset, + required int info, + required List tags}) { + final decodeLen = _decodeLength(info, cborBytes, offset); + int consumed = decodeLen.consumed; + final int length = decodeLen.value; + final Map objects = {}; for (int lI = 0; lI < length; lI++) { - final decodeKey = _decode(cborBytes.sublist(index)); - index += decodeKey.item2; - final decodeValue = _decode(cborBytes.sublist(index)); - objects[decodeKey.item1] = decodeValue.item1; - index += decodeValue.item2; + final decodeKey = _decode(cborBytes, offset: consumed + offset); + consumed += decodeKey.consumed; + final decodeValue = _decode(cborBytes, offset: consumed + offset); + objects[decodeKey.value] = decodeValue.value; + consumed += decodeValue.consumed; } final toMap = CborMapValue.fixedLength(objects); - return Tuple(tags.isEmpty ? toMap : CborTagValue(toMap, tags), index); + return _DecodeCborResult( + value: tags.isEmpty ? toMap : CborTagValue(toMap, tags), + consumed: consumed); } - static Tuple _decodeDynamicMap( - List cborBytes, int offset, int info, List tags) { - int index = offset + 1; - Map objects = {}; - while (cborBytes[index] != 0xff) { - final decodeKey = _decode(cborBytes.sublist(index)); - index += decodeKey.item2; - final decodeValue = _decode(cborBytes.sublist(index)); - objects[decodeKey.item1] = decodeValue.item1; - index += decodeValue.item2; + static _DecodeCborResult _decodeDynamicMap( + {required List cborBytes, + required int offset, + required int info, + required List tags}) { + int consumed = 1; + final Map objects = {}; + while (cborBytes[offset + consumed] != 0xff) { + final decodeKey = _decode(cborBytes, offset: offset + consumed); + consumed += decodeKey.consumed; + final decodeValue = _decode(cborBytes, offset: offset + consumed); + objects[decodeKey.value] = decodeValue.value; + consumed += decodeValue.consumed; } + consumed++; final toMap = CborMapValue.dynamicLength(objects); - return Tuple(tags.isEmpty ? toMap : CborTagValue(toMap, tags), index + 1); + return _DecodeCborResult( + value: tags.isEmpty ? toMap : CborTagValue(toMap, tags), + consumed: consumed); } - static Tuple _decodeArray( - List cborBytes, int offset, int info, List tags) { - final decodeLen = _decodeLength(info, cborBytes); - int index = offset + decodeLen.item2; - final int length = decodeLen.item1; - List objects = []; + static _DecodeCborResult _decodeArray( + {required List cborBytes, + required int offset, + required int info, + required List tags}) { + final decodeLen = _decodeLength(info, cborBytes, offset); + int consumed = decodeLen.consumed; + final int length = decodeLen.value; + final List objects = []; for (int lI = 0; lI < length; lI++) { - final decodeData = _decode(cborBytes.sublist(index)); - objects.add(decodeData.item1); - index += decodeData.item2; - if (index == cborBytes.length) break; + final decodeData = _decode(cborBytes, offset: consumed + offset); + objects.add(decodeData.value); + consumed += decodeData.consumed; + if ((consumed + offset) == cborBytes.length) break; } if (BytesUtils.bytesEqual(tags, CborTags.bigFloat) || BytesUtils.bytesEqual(tags, CborTags.decimalFrac)) { - return Tuple(_decodeCborBigfloatOrDecimal(objects, tags), index); + return _DecodeCborResult( + value: _decodeCborBigfloatOrDecimal(objects, tags), + consumed: consumed); } if (BytesUtils.bytesEqual(tags, CborTags.set)) { tags.clear(); final toObj = CborSetValue(objects.toSet()); - return Tuple(tags.isEmpty ? toObj : CborTagValue(toObj, tags), index); + return _DecodeCborResult( + value: tags.isEmpty ? toObj : CborTagValue(toObj, tags), + consumed: consumed); } final toObj = CborListValue.fixedLength(objects); - return Tuple(tags.isEmpty ? toObj : CborTagValue(toObj, tags), index); + return _DecodeCborResult( + value: tags.isEmpty ? toObj : CborTagValue(toObj, tags), + consumed: consumed); } - static Tuple _decodeDynamicArray( - List cborBytes, int offset, int info, List tags) { - int index = offset + 1; - List objects = []; - while (cborBytes[index] != 0xff) { - final decodeData = _decode(cborBytes.sublist(index)); - objects.add(decodeData.item1); - index += decodeData.item2; + static _DecodeCborResult _decodeDynamicArray( + {required List cborBytes, + required int offset, + required int info, + required List tags}) { + int consomed = 1; + final List objects = []; + while (cborBytes[consomed + offset] != 0xff) { + final decodeData = _decode(cborBytes, offset: consomed + offset); + objects.add(decodeData.value); + consomed += decodeData.consumed; } + consomed++; final toObj = CborListValue.dynamicLength(objects); - return Tuple(tags.isEmpty ? toObj : CborTagValue(toObj, tags), index + 1); + return _DecodeCborResult( + value: tags.isEmpty ? toObj : CborTagValue(toObj, tags), + consumed: consomed); } static CborObject _decodeCborBigfloatOrDecimal( @@ -268,9 +359,11 @@ class CborUtils { return tags.isEmpty ? toObj : CborTagValue(toObj, tags); } - static Tuple _parseSimpleValue( - int i, int info, List bytes, List tags) { - int offset = i + 1; + static _DecodeCborResult _parseSimpleValue( + {required int offset, + required int info, + required List bytes, + required List tags}) { CborObject? obj; switch (info) { case SimpleTags.simpleFalse: @@ -289,21 +382,24 @@ class CborUtils { } if (obj != null) { if (tags.isEmpty) { - return Tuple(obj, offset); + return _DecodeCborResult(value: obj, consumed: 1); } - return Tuple(CborTagValue(obj, tags), offset); + return _DecodeCborResult(value: CborTagValue(obj, tags), consumed: 1); } - + int consumed = 1; + offset += 1; double val; switch (info) { case NumBytes.two: val = FloatUtils.floatFromBytes16(bytes.sublist(offset, offset + 2)); + consumed += 2; offset = offset + 2; break; case NumBytes.four: val = ByteData.view( Uint8List.fromList(bytes.sublist(offset, offset + 4)).buffer) .getFloat32(0, Endian.big); + consumed += 4; offset = offset + 4; break; case NumBytes.eight: @@ -311,6 +407,7 @@ class CborUtils { Uint8List.fromList(bytes.sublist(offset, offset + 8)).buffer) .getFloat64(0, Endian.big); offset = offset + 8; + consumed += 8; break; default: throw const CborException("Invalid simpleOrFloatTags"); @@ -321,16 +418,22 @@ class CborUtils { obj = CborEpochFloatValue(dt); } obj ??= CborFloatValue(val); - return Tuple(tags.isEmpty ? obj : CborTagValue(obj, tags), offset); + return _DecodeCborResult( + value: tags.isEmpty ? obj : CborTagValue(obj, tags), + consumed: consumed); } - static Tuple _parseInt( - int mt, int info, int i, List cborBytes, List tags) { - final data = _decodeLength(info, cborBytes.sublist(i)); - final numb = data.item1; + static _DecodeCborResult _parseInt( + {required int mt, + required int info, + required int offset, + required List cborBytes, + required List tags}) { + final data = _decodeLength(info, cborBytes, offset); + final numb = data.value; CborNumeric? numericValue; if (numb is BigInt || mt == MajorTags.negInt) { - BigInt val = numb is BigInt ? numb : BigInt.from(numb); + BigInt val = BigintUtils.parse(numb); if (mt == MajorTags.negInt) { val = ~val; } @@ -341,15 +444,17 @@ class CborUtils { } else { numericValue = CborIntValue(numb); } - final index = data.item2 + i; if (BytesUtils.bytesEqual(tags, CborTags.dateEpoch)) { final dt = DateTime.fromMillisecondsSinceEpoch(numericValue.toInt() * 1000); tags.clear(); final toObj = CborEpochIntValue(dt); - return Tuple(tags.isEmpty ? toObj : CborTagValue(toObj, tags), index); + return _DecodeCborResult( + value: tags.isEmpty ? toObj : CborTagValue(toObj, tags), + consumed: data.consumed); } - return Tuple( - tags.isEmpty ? numericValue : CborTagValue(numericValue, tags), index); + return _DecodeCborResult( + value: tags.isEmpty ? numericValue : CborTagValue(numericValue, tags), + consumed: data.consumed); } } diff --git a/lib/cbor/utils/dynamic_bytes.dart b/lib/cbor/utils/dynamic_bytes.dart index 4055c8d..3069e73 100644 --- a/lib/cbor/utils/dynamic_bytes.dart +++ b/lib/cbor/utils/dynamic_bytes.dart @@ -1,17 +1,22 @@ import 'package:blockchain_utils/cbor/core/tags.dart'; +import 'package:blockchain_utils/helper/helper.dart'; import 'package:blockchain_utils/utils/utils.dart'; -/// A class for tracking and building a sequence of bytes (List) for CBOR encoding. +/// A class for tracking and building a sequence of bytes (`List`) for CBOR encoding. class CborBytesTracker { /// Constructor for creating a CborBytesTracker instance. CborBytesTracker(); /// A buffer used to accumulate the bytes for CBOR encoding. - final DynamicByteTracker _buffer = DynamicByteTracker(); + final List _buffer = []; - /// Retrieve the accumulated bytes as a List from the buffer. + /// Retrieve the accumulated bytes as a `List` from the buffer. List toBytes() { - return _buffer.toBytes(); + return _buffer.asBytes; + } + + List buffer() { + return _buffer; } /// Append a single UInt8 value to the byte sequence in the buffer. @@ -21,13 +26,12 @@ class CborBytesTracker { /// Append a list of integer values (chunk) to the byte sequence in the buffer. void pushBytes(List chunk) { - BytesUtils.validateBytes(chunk); - _buffer.add(chunk); + _buffer.addAll(chunk); } /// Append a list of CBOR tags to the byte sequence in the buffer. void pushTags(List tags) { - for (int i in tags) { + for (final i in tags) { pushInt(MajorTags.tag, i); } } @@ -55,7 +59,7 @@ class CborBytesTracker { int value, ) { majorTag <<= 5; - int? length = bytesLength(value); + final int? length = bytesLength(value); pushUInt8(majorTag | (length ?? value)); if (length == null) return; final int len = 1 << (length - 24); diff --git a/lib/cbor/utils/extentions.dart b/lib/cbor/utils/extentions.dart index 31cbcf9..c75e5d7 100644 --- a/lib/cbor/utils/extentions.dart +++ b/lib/cbor/utils/extentions.dart @@ -2,25 +2,25 @@ extension RFC3339 on DateTime { /// Convert the DateTime to an RFC3339 formatted string with time zone information. String toRFC3339WithTimeZone() { - String year = this.year.toString().padLeft(4, '0'); - String month = this.month.toString().padLeft(2, '0'); - String day = this.day.toString().padLeft(2, '0'); - String hour = this.hour.toString().padLeft(2, '0'); - String minute = this.minute.toString().padLeft(2, '0'); - String second = this.second.toString().padLeft(2, '0'); - String millisecond = this + final String year = this.year.toString().padLeft(4, '0'); + final String month = this.month.toString().padLeft(2, '0'); + final String day = this.day.toString().padLeft(2, '0'); + final String hour = this.hour.toString().padLeft(2, '0'); + final String minute = this.minute.toString().padLeft(2, '0'); + final String second = this.second.toString().padLeft(2, '0'); + final String millisecond = this .millisecond .toString() .padLeft(3, '0') .replaceAll(RegExp(r'0*$'), ''); - Duration timeZoneOffset = isUtc ? Duration.zero : this.timeZoneOffset; + final Duration timeZoneOffset = isUtc ? Duration.zero : this.timeZoneOffset; - String timeZoneOffsetSign = timeZoneOffset.isNegative ? '-' : '+'; - int timeZoneOffsetHours = timeZoneOffset.inHours.abs(); - int timeZoneOffsetMinutes = timeZoneOffset.inMinutes.abs() % 60; + final String timeZoneOffsetSign = timeZoneOffset.isNegative ? '-' : '+'; + final int timeZoneOffsetHours = timeZoneOffset.inHours.abs(); + final int timeZoneOffsetMinutes = timeZoneOffset.inMinutes.abs() % 60; - String timeZoneOffsetFormatted = isUtc + final String timeZoneOffsetFormatted = isUtc ? "Z" : '$timeZoneOffsetSign${timeZoneOffsetHours.toString().padLeft(2, '0')}:${timeZoneOffsetMinutes.toString().padLeft(2, '0')}'; diff --git a/lib/cbor/utils/float_utils.dart b/lib/cbor/utils/float_utils.dart index 79756e3..796db5a 100644 --- a/lib/cbor/utils/float_utils.dart +++ b/lib/cbor/utils/float_utils.dart @@ -192,7 +192,7 @@ class FloatUtils { float16View[0] = sign << 15 | 0x1F << 10 | 0x000; } else { // Normalized number - int newExponent = exponent - 127 + 15; + final int newExponent = exponent - 127 + 15; if (newExponent < 0) { // Round to zero if exponent is too small for float16 float16View[0] = sign << 15; @@ -266,12 +266,12 @@ class FloatUtils { 'Input byte array must be exactly 2 bytes long for Float16'); } - ByteData byteData = ByteData.sublistView(Uint8List.fromList(bytes)); - int int16Bits = byteData.getInt16(0, Endian.big); + final ByteData byteData = ByteData.sublistView(Uint8List.fromList(bytes)); + final int int16Bits = byteData.getInt16(0, Endian.big); - int sign = (int16Bits >> 15) & 0x1; + final int sign = (int16Bits >> 15) & 0x1; int exponent = (int16Bits >> 10) & 0x1F; - int fraction = int16Bits & 0x3FF; + final int fraction = int16Bits & 0x3FF; double value; diff --git a/lib/crypto/crypto/aead/aead.dart b/lib/crypto/crypto/aead/aead.dart index a7e80c9..a45dd1c 100644 --- a/lib/crypto/crypto/aead/aead.dart +++ b/lib/crypto/crypto/aead/aead.dart @@ -12,10 +12,10 @@ /// - `tagLength`: Returns the length (in bytes) of the authentication tag produced by the AEAD algorithm. /// /// - `encrypt`: Encrypts the provided plaintext along with a nonce, and optional associated data. -/// Returns the ciphertext and may write the result into the `dst` List if provided. +/// Returns the ciphertext and may write the result into the `dst` `List` if provided. /// /// - `decrypt`: Decrypts the provided ciphertext along with a nonce, and optional associated data. -/// Returns the plaintext and may write the result into the `dst` List if provided. Returns `null` +/// Returns the plaintext and may write the result into the `dst` `List` if provided. Returns `null` /// if decryption fails due to authentication failure. /// /// - `clean`: Clears any sensitive information or states held by the AEAD instance, ensuring that @@ -28,12 +28,12 @@ abstract class AEAD { int get tagLength; /// Encrypts the provided plaintext along with a nonce, and optional associated data. - /// Returns the ciphertext and may write the result into the `dst` List if provided. + /// Returns the ciphertext and may write the result into the `dst` `List` if provided. List encrypt(List nonce, List plaintext, {List? associatedData, List? dst}); /// Decrypts the provided ciphertext along with a nonce, and optional associated data. - /// Returns the plaintext and may write the result into the `dst` List if provided. + /// Returns the plaintext and may write the result into the `dst` `List` if provided. /// Returns `null` if decryption fails due to authentication failure. List? decrypt(List nonce, List ciphertext, {List? associatedData, List? dst}); diff --git a/lib/crypto/crypto/aes/aes.dart b/lib/crypto/crypto/aes/aes.dart index d29629e..dcf590f 100644 --- a/lib/crypto/crypto/aes/aes.dart +++ b/lib/crypto/crypto/aes/aes.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/blockcipher/blockcipher.dart'; import 'package:blockchain_utils/utils/utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'aes_lib.dart' as aes_lib; /// Represents an Advanced Encryption Standard (AES) block cipher. @@ -57,7 +57,7 @@ class AES implements BlockCipher { /// expands the key into internal key schedules for encryption and decryption if required. /// /// Parameters: - /// - `key`: The encryption key as a List. It must be 16, 24, or 32 bytes in length + /// - `key`: The encryption key as a `List`. It must be 16, 24, or 32 bytes in length /// for AES-128, AES-192, or AES-256, respectively. /// - `noDecryption`: An optional boolean flag. If set to `true`, it disables decryption functionality /// by securely wiping the decryption key schedule. @@ -114,7 +114,7 @@ class AES implements BlockCipher { /// This method takes a source block of plaintext, encrypts it using the encryption key schedule, /// and returns the resulting ciphertext. Optionally, you can provide a destination block (`dst`) - /// to write the encrypted data into. If not provided, a new List is created to hold the result. + /// to write the encrypted data into. If not provided, a new `List` is created to hold the result. /// /// Parameters: /// - `src`: The source block of plaintext to be encrypted, which must have a length of 16 bytes. @@ -126,7 +126,7 @@ class AES implements BlockCipher { /// - `StateError` if the encryption key is not available, indicating that the instance is not properly initialized. /// /// Returns: - /// - The encrypted ciphertext block as a List. + /// - The encrypted ciphertext block as a `List`. @override List encryptBlock(List src, [List? dst]) { final out = dst ?? List.filled(blockSize, 0); @@ -147,7 +147,7 @@ class AES implements BlockCipher { /// This method takes a source block of ciphertext, decrypts it using the decryption key schedule, /// and returns the resulting plaintext. Optionally, you can provide a destination block (`dst`) - /// to write the decrypted data into. If not provided, a new List is created to hold the result. + /// to write the decrypted data into. If not provided, a new `List` is created to hold the result. /// /// Parameters: /// - `src`: The source block of ciphertext to be decrypted, which must have a length of 16 bytes. @@ -160,7 +160,7 @@ class AES implements BlockCipher { /// decryption is not supported by this instance. /// /// Returns: - /// - The decrypted plaintext block as a List. + /// - The decrypted plaintext block as a `List`. @override List decryptBlock(List src, [List? dst]) { final out = dst ?? List.filled(blockSize, 0); diff --git a/lib/crypto/crypto/aes/padding.dart b/lib/crypto/crypto/aes/padding.dart index 40f60d8..f586a79 100644 --- a/lib/crypto/crypto/aes/padding.dart +++ b/lib/crypto/crypto/aes/padding.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Enumeration representing various padding algorithms for block ciphers. enum PaddingAlgorithm { pkcs7, iso7816, x923 } @@ -19,7 +19,7 @@ class BlockCipherPadding { /// - A new `List` containing the input data with the added padding. static List pad(List dataToPad, int blockSize, {PaddingAlgorithm style = PaddingAlgorithm.pkcs7}) { - int paddingLen = blockSize - dataToPad.length % blockSize; + final int paddingLen = blockSize - dataToPad.length % blockSize; List padding; if (style == PaddingAlgorithm.pkcs7) { @@ -41,7 +41,7 @@ class BlockCipherPadding { } } - List result = List.filled(dataToPad.length + paddingLen, 0); + final List result = List.filled(dataToPad.length + paddingLen, 0); result.setAll(0, dataToPad); result.setAll(dataToPad.length, padding); @@ -64,7 +64,7 @@ class BlockCipherPadding { /// - `Exception` for various scenarios, such as incorrect padding or zero-length input. static List unpad(List paddedData, int blockSize, {PaddingAlgorithm style = PaddingAlgorithm.pkcs7}) { - int paddedDataLen = paddedData.length; + final int paddedDataLen = paddedData.length; if (paddedDataLen == 0) { throw const ArgumentException('Zero-length input cannot be unpadded'); @@ -96,7 +96,7 @@ class BlockCipherPadding { } } } else { - int index = paddedData.lastIndexOf(128); + final int index = paddedData.lastIndexOf(128); if (index < 0) { throw const ArgumentException('incorrect padding'); } diff --git a/lib/crypto/crypto/cdsa/cdsa.dart b/lib/crypto/crypto/cdsa/cdsa.dart index d9bac7b..bdab409 100644 --- a/lib/crypto/crypto/cdsa/cdsa.dart +++ b/lib/crypto/crypto/cdsa/cdsa.dart @@ -1,6 +1,6 @@ /// The 'cdsa' library provides tools and components for working with various cryptographic /// algorithms, including elliptic curve cryptography (ECDSA and EDDSA) and related functionality. -library cdsa; +library; /// Export statement for cryptographic curve definitions. export 'curve/curves.dart'; diff --git a/lib/crypto/crypto/cdsa/crypto_ops/exception/exception.dart b/lib/crypto/crypto/cdsa/crypto_ops/exception/exception.dart index 2d1dd02..1902ba6 100644 --- a/lib/crypto/crypto/cdsa/crypto_ops/exception/exception.dart +++ b/lib/crypto/crypto/cdsa/crypto_ops/exception/exception.dart @@ -1,6 +1,5 @@ -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; class CryptoOpsException extends BlockchainUtilsException { - const CryptoOpsException(String message, {Map? details}) - : super(message, details: details); + const CryptoOpsException(super.message, {super.details}); } diff --git a/lib/crypto/crypto/cdsa/crypto_ops/operations/ops.dart b/lib/crypto/crypto/cdsa/crypto_ops/operations/ops.dart index def5af4..2b0cbfc 100644 --- a/lib/crypto/crypto/cdsa/crypto_ops/operations/ops.dart +++ b/lib/crypto/crypto/cdsa/crypto_ops/operations/ops.dart @@ -86,14 +86,14 @@ class CryptoOps { static int scCheck(List s) { s.asMin32("scCheck"); - BigInt s0 = _load4(s, 0); - BigInt s1 = _load4(s, 4); - BigInt s2 = _load4(s, 8); - BigInt s3 = _load4(s, 12); - BigInt s4 = _load4(s, 16); - BigInt s5 = _load4(s, 20); - BigInt s6 = _load4(s, 24); - BigInt s7 = _load4(s, 28); + final BigInt s0 = _load4(s, 0); + final BigInt s1 = _load4(s, 4); + final BigInt s2 = _load4(s, 8); + final BigInt s3 = _load4(s, 12); + final BigInt s4 = _load4(s, 16); + final BigInt s5 = _load4(s, 20); + final BigInt s6 = _load4(s, 24); + final BigInt s7 = _load4(s, 28); final r = (signum(1559614444.toBig - s0) + (signum(1477600026.toBig - s1) << 1) + (signum(2734136534.toBig - s2) << 2) + @@ -305,36 +305,36 @@ class CryptoOps { } static void feAdd(FieldElement h, FieldElement f, FieldElement g) { - int f0 = f.h[0]; - int f1 = f.h[1]; - int f2 = f.h[2]; - int f3 = f.h[3]; - int f4 = f.h[4]; - int f5 = f.h[5]; - int f6 = f.h[6]; - int f7 = f.h[7]; - int f8 = f.h[8]; - int f9 = f.h[9]; - int g0 = g.h[0]; - int g1 = g.h[1]; - int g2 = g.h[2]; - int g3 = g.h[3]; - int g4 = g.h[4]; - int g5 = g.h[5]; - int g6 = g.h[6]; - int g7 = g.h[7]; - int g8 = g.h[8]; - int g9 = g.h[9]; - int h0 = f0 + g0; - int h1 = f1 + g1; - int h2 = f2 + g2; - int h3 = f3 + g3; - int h4 = f4 + g4; - int h5 = f5 + g5; - int h6 = f6 + g6; - int h7 = f7 + g7; - int h8 = f8 + g8; - int h9 = f9 + g9; + final int f0 = f.h[0]; + final int f1 = f.h[1]; + final int f2 = f.h[2]; + final int f3 = f.h[3]; + final int f4 = f.h[4]; + final int f5 = f.h[5]; + final int f6 = f.h[6]; + final int f7 = f.h[7]; + final int f8 = f.h[8]; + final int f9 = f.h[9]; + final int g0 = g.h[0]; + final int g1 = g.h[1]; + final int g2 = g.h[2]; + final int g3 = g.h[3]; + final int g4 = g.h[4]; + final int g5 = g.h[5]; + final int g6 = g.h[6]; + final int g7 = g.h[7]; + final int g8 = g.h[8]; + final int g9 = g.h[9]; + final int h0 = f0 + g0; + final int h1 = f1 + g1; + final int h2 = f2 + g2; + final int h3 = f3 + g3; + final int h4 = f4 + g4; + final int h5 = f5 + g5; + final int h6 = f6 + g6; + final int h7 = f7 + g7; + final int h8 = f8 + g8; + final int h9 = f9 + g9; h.h[0] = h0; h.h[1] = h1; h.h[2] = h2; @@ -355,26 +355,26 @@ class CryptoOps { static void feCmov(FieldElement f, FieldElement g, int b) { assert(b == 0 || b == 1, "b should be either 0 or 1."); - int f0 = f.h[0]; - int f1 = f.h[1]; - int f2 = f.h[2]; - int f3 = f.h[3]; - int f4 = f.h[4]; - int f5 = f.h[5]; - int f6 = f.h[6]; - int f7 = f.h[7]; - int f8 = f.h[8]; - int f9 = f.h[9]; - int g0 = g.h[0]; - int g1 = g.h[1]; - int g2 = g.h[2]; - int g3 = g.h[3]; - int g4 = g.h[4]; - int g5 = g.h[5]; - int g6 = g.h[6]; - int g7 = g.h[7]; - int g8 = g.h[8]; - int g9 = g.h[9]; + final int f0 = f.h[0]; + final int f1 = f.h[1]; + final int f2 = f.h[2]; + final int f3 = f.h[3]; + final int f4 = f.h[4]; + final int f5 = f.h[5]; + final int f6 = f.h[6]; + final int f7 = f.h[7]; + final int f8 = f.h[8]; + final int f9 = f.h[9]; + final int g0 = g.h[0]; + final int g1 = g.h[1]; + final int g2 = g.h[2]; + final int g3 = g.h[3]; + final int g4 = g.h[4]; + final int g5 = g.h[5]; + final int g6 = g.h[6]; + final int g7 = g.h[7]; + final int g8 = g.h[8]; + final int g9 = g.h[9]; int x0 = f0 ^ g0; int x1 = f1 ^ g1; int x2 = f2 ^ g2; @@ -409,16 +409,16 @@ class CryptoOps { } static void feCopy(FieldElement h, FieldElement f) { - int f0 = f.h[0]; - int f1 = f.h[1]; - int f2 = f.h[2]; - int f3 = f.h[3]; - int f4 = f.h[4]; - int f5 = f.h[5]; - int f6 = f.h[6]; - int f7 = f.h[7]; - int f8 = f.h[8]; - int f9 = f.h[9]; + final int f0 = f.h[0]; + final int f1 = f.h[1]; + final int f2 = f.h[2]; + final int f3 = f.h[3]; + final int f4 = f.h[4]; + final int f5 = f.h[5]; + final int f6 = f.h[6]; + final int f7 = f.h[7]; + final int f8 = f.h[8]; + final int f9 = f.h[9]; h.h[0] = f0; h.h[1] = f1; h.h[2] = f2; @@ -432,85 +432,85 @@ class CryptoOps { } static void feSq(FieldElement h, FieldElement f) { - int f0 = f.h[0]; - int f1 = f.h[1]; - int f2 = f.h[2]; - int f3 = f.h[3]; - int f4 = f.h[4]; - int f5 = f.h[5]; - int f6 = f.h[6]; - int f7 = f.h[7]; - int f8 = f.h[8]; - int f9 = f.h[9]; - int f0_2 = (2 * f0).toInt32; - int f1_2 = (2 * f1).toInt32; - int f2_2 = (2 * f2).toInt32; - int f3_2 = (2 * f3).toInt32; - int f4_2 = (2 * f4).toInt32; - int f5_2 = (2 * f5).toInt32; - int f6_2 = (2 * f6).toInt32; - int f7_2 = (2 * f7).toInt32; - int f5_38 = (38 * f5).toInt32; /* 1.959375*2^30 */ - int f6_19 = (19 * f6).toInt32; /* 1.959375*2^30 */ - int f7_38 = (38 * f7).toInt32; /* 1.959375*2^30 */ - int f8_19 = (19 * f8).toInt32; /* 1.959375*2^30 */ - int f9_38 = (38 * f9).toInt32; /* 1.959375*2^30 */ - - BigInt f0f0 = f0.toBig * f0.toBig; - BigInt f0f1_2 = f0_2.toBig * f1.toBig; - BigInt f0f2_2 = f0_2.toBig * f2.toBig; - BigInt f0f3_2 = f0_2.toBig * f3.toBig; - BigInt f0f4_2 = f0_2.toBig * f4.toBig; - BigInt f0f5_2 = f0_2.toBig * f5.toBig; - BigInt f0f6_2 = f0_2.toBig * f6.toBig; - BigInt f0f7_2 = f0_2.toBig * f7.toBig; - BigInt f0f8_2 = f0_2.toBig * f8.toBig; - BigInt f0f9_2 = f0_2.toBig * f9.toBig; - BigInt f1f1_2 = f1_2.toBig * f1.toBig; - BigInt f1f2_2 = f1_2.toBig * f2.toBig; - BigInt f1f3_4 = f1_2.toBig * f3_2.toBig; - BigInt f1f4_2 = f1_2.toBig * f4.toBig; - BigInt f1f5_4 = f1_2.toBig * f5_2.toBig; - BigInt f1f6_2 = f1_2.toBig * f6.toBig; - BigInt f1f7_4 = f1_2.toBig * f7_2.toBig; - BigInt f1f8_2 = f1_2.toBig * f8.toBig; - BigInt f1f9_76 = f1_2.toBig * f9_38.toBig; - BigInt f2f2 = f2.toBig * f2.toBig; - BigInt f2f3_2 = f2_2.toBig * f3.toBig; - BigInt f2f4_2 = f2_2.toBig * f4.toBig; - BigInt f2f5_2 = f2_2.toBig * f5.toBig; - BigInt f2f6_2 = f2_2.toBig * f6.toBig; - BigInt f2f7_2 = f2_2.toBig * f7.toBig; - BigInt f2f8_38 = f2_2.toBig * f8_19.toBig; - BigInt f2f9_38 = f2.toBig * f9_38.toBig; - BigInt f3f3_2 = f3_2.toBig * f3.toBig; - BigInt f3f4_2 = f3_2.toBig * f4.toBig; - BigInt f3f5_4 = f3_2.toBig * f5_2.toBig; - BigInt f3f6_2 = f3_2.toBig * f6.toBig; - BigInt f3f7_76 = f3_2.toBig * f7_38.toBig; - BigInt f3f8_38 = f3_2.toBig * f8_19.toBig; - BigInt f3f9_76 = f3_2.toBig * f9_38.toBig; - BigInt f4f4 = f4.toBig * f4.toBig; - BigInt f4f5_2 = f4_2.toBig * f5.toBig; - BigInt f4f6_38 = f4_2.toBig * f6_19.toBig; - BigInt f4f7_38 = f4.toBig * f7_38.toBig; - BigInt f4f8_38 = f4_2.toBig * f8_19.toBig; - BigInt f4f9_38 = f4.toBig * f9_38.toBig; - BigInt f5f5_38 = f5.toBig * f5_38.toBig; - BigInt f5f6_38 = f5_2.toBig * f6_19.toBig; - BigInt f5f7_76 = f5_2.toBig * f7_38.toBig; - BigInt f5f8_38 = f5_2.toBig * f8_19.toBig; - BigInt f5f9_76 = f5_2.toBig * f9_38.toBig; - BigInt f6f6_19 = f6.toBig * f6_19.toBig; - BigInt f6f7_38 = f6.toBig * f7_38.toBig; - BigInt f6f8_38 = f6_2.toBig * f8_19.toBig; - BigInt f6f9_38 = f6.toBig * f9_38.toBig; - BigInt f7f7_38 = f7.toBig * f7_38.toBig; - BigInt f7f8_38 = f7_2.toBig * f8_19.toBig; - BigInt f7f9_76 = f7_2.toBig * f9_38.toBig; - BigInt f8f8_19 = f8.toBig * f8_19.toBig; - BigInt f8f9_38 = f8.toBig * f9_38.toBig; - BigInt f9f9_38 = f9.toBig * f9_38.toBig; + final int f0 = f.h[0]; + final int f1 = f.h[1]; + final int f2 = f.h[2]; + final int f3 = f.h[3]; + final int f4 = f.h[4]; + final int f5 = f.h[5]; + final int f6 = f.h[6]; + final int f7 = f.h[7]; + final int f8 = f.h[8]; + final int f9 = f.h[9]; + final int f0_2 = (2 * f0).toInt32; + final int f1_2 = (2 * f1).toInt32; + final int f2_2 = (2 * f2).toInt32; + final int f3_2 = (2 * f3).toInt32; + final int f4_2 = (2 * f4).toInt32; + final int f5_2 = (2 * f5).toInt32; + final int f6_2 = (2 * f6).toInt32; + final int f7_2 = (2 * f7).toInt32; + final int f5_38 = (38 * f5).toInt32; /* 1.959375*2^30 */ + final int f6_19 = (19 * f6).toInt32; /* 1.959375*2^30 */ + final int f7_38 = (38 * f7).toInt32; /* 1.959375*2^30 */ + final int f8_19 = (19 * f8).toInt32; /* 1.959375*2^30 */ + final int f9_38 = (38 * f9).toInt32; /* 1.959375*2^30 */ + + final BigInt f0f0 = f0.toBig * f0.toBig; + final BigInt f0f1_2 = f0_2.toBig * f1.toBig; + final BigInt f0f2_2 = f0_2.toBig * f2.toBig; + final BigInt f0f3_2 = f0_2.toBig * f3.toBig; + final BigInt f0f4_2 = f0_2.toBig * f4.toBig; + final BigInt f0f5_2 = f0_2.toBig * f5.toBig; + final BigInt f0f6_2 = f0_2.toBig * f6.toBig; + final BigInt f0f7_2 = f0_2.toBig * f7.toBig; + final BigInt f0f8_2 = f0_2.toBig * f8.toBig; + final BigInt f0f9_2 = f0_2.toBig * f9.toBig; + final BigInt f1f1_2 = f1_2.toBig * f1.toBig; + final BigInt f1f2_2 = f1_2.toBig * f2.toBig; + final BigInt f1f3_4 = f1_2.toBig * f3_2.toBig; + final BigInt f1f4_2 = f1_2.toBig * f4.toBig; + final BigInt f1f5_4 = f1_2.toBig * f5_2.toBig; + final BigInt f1f6_2 = f1_2.toBig * f6.toBig; + final BigInt f1f7_4 = f1_2.toBig * f7_2.toBig; + final BigInt f1f8_2 = f1_2.toBig * f8.toBig; + final BigInt f1f9_76 = f1_2.toBig * f9_38.toBig; + final BigInt f2f2 = f2.toBig * f2.toBig; + final BigInt f2f3_2 = f2_2.toBig * f3.toBig; + final BigInt f2f4_2 = f2_2.toBig * f4.toBig; + final BigInt f2f5_2 = f2_2.toBig * f5.toBig; + final BigInt f2f6_2 = f2_2.toBig * f6.toBig; + final BigInt f2f7_2 = f2_2.toBig * f7.toBig; + final BigInt f2f8_38 = f2_2.toBig * f8_19.toBig; + final BigInt f2f9_38 = f2.toBig * f9_38.toBig; + final BigInt f3f3_2 = f3_2.toBig * f3.toBig; + final BigInt f3f4_2 = f3_2.toBig * f4.toBig; + final BigInt f3f5_4 = f3_2.toBig * f5_2.toBig; + final BigInt f3f6_2 = f3_2.toBig * f6.toBig; + final BigInt f3f7_76 = f3_2.toBig * f7_38.toBig; + final BigInt f3f8_38 = f3_2.toBig * f8_19.toBig; + final BigInt f3f9_76 = f3_2.toBig * f9_38.toBig; + final BigInt f4f4 = f4.toBig * f4.toBig; + final BigInt f4f5_2 = f4_2.toBig * f5.toBig; + final BigInt f4f6_38 = f4_2.toBig * f6_19.toBig; + final BigInt f4f7_38 = f4.toBig * f7_38.toBig; + final BigInt f4f8_38 = f4_2.toBig * f8_19.toBig; + final BigInt f4f9_38 = f4.toBig * f9_38.toBig; + final BigInt f5f5_38 = f5.toBig * f5_38.toBig; + final BigInt f5f6_38 = f5_2.toBig * f6_19.toBig; + final BigInt f5f7_76 = f5_2.toBig * f7_38.toBig; + final BigInt f5f8_38 = f5_2.toBig * f8_19.toBig; + final BigInt f5f9_76 = f5_2.toBig * f9_38.toBig; + final BigInt f6f6_19 = f6.toBig * f6_19.toBig; + final BigInt f6f7_38 = f6.toBig * f7_38.toBig; + final BigInt f6f8_38 = f6_2.toBig * f8_19.toBig; + final BigInt f6f9_38 = f6.toBig * f9_38.toBig; + final BigInt f7f7_38 = f7.toBig * f7_38.toBig; + final BigInt f7f8_38 = f7_2.toBig * f8_19.toBig; + final BigInt f7f9_76 = f7_2.toBig * f9_38.toBig; + final BigInt f8f8_19 = f8.toBig * f8_19.toBig; + final BigInt f8f9_38 = f8.toBig * f9_38.toBig; + final BigInt f9f9_38 = f9.toBig * f9_38.toBig; BigInt h0 = f0f0 + f1f9_76 + f2f8_38 + f3f7_76 + f4f6_38 + f5f5_38; BigInt h1 = f0f1_2 + f2f9_38 + f3f8_38 + f4f7_38 + f5f6_38; BigInt h2 = f0f2_2 + f1f1_2 + f3f9_76 + f4f8_38 + f5f7_76 + f6f6_19; @@ -588,85 +588,85 @@ class CryptoOps { } static void feSq2(FieldElement h, FieldElement f) { - int f0 = f.h[0]; - int f1 = f.h[1]; - int f2 = f.h[2]; - int f3 = f.h[3]; - int f4 = f.h[4]; - int f5 = f.h[5]; - int f6 = f.h[6]; - int f7 = f.h[7]; - int f8 = f.h[8]; - int f9 = f.h[9]; - int f0_2 = (2 * f0).toInt32; - int f1_2 = (2 * f1).toInt32; - int f2_2 = (2 * f2).toInt32; - int f3_2 = (2 * f3).toInt32; - int f4_2 = (2 * f4).toInt32; - int f5_2 = (2 * f5).toInt32; - int f6_2 = (2 * f6).toInt32; - int f7_2 = (2 * f7).toInt32; - int f5_38 = (38 * f5).toInt32; /* 1.959375*2^30 */ - int f6_19 = (19 * f6).toInt32; /* 1.959375*2^30 */ - int f7_38 = (38 * f7).toInt32; /* 1.959375*2^30 */ - int f8_19 = (19 * f8).toInt32; /* 1.959375*2^30 */ - int f9_38 = (38 * f9).toInt32; /* 1.959375*2^30 */ - BigInt f0f0 = f0.toBig * f0.toBig; - - BigInt f0f1_2 = f0_2.toBig * f1.toBig; - BigInt f0f2_2 = f0_2.toBig * f2.toBig; - BigInt f0f3_2 = f0_2.toBig * f3.toBig; - BigInt f0f4_2 = f0_2.toBig * f4.toBig; - BigInt f0f5_2 = f0_2.toBig * f5.toBig; - BigInt f0f6_2 = f0_2.toBig * f6.toBig; - BigInt f0f7_2 = f0_2.toBig * f7.toBig; - BigInt f0f8_2 = f0_2.toBig * f8.toBig; - BigInt f0f9_2 = f0_2.toBig * f9.toBig; - BigInt f1f1_2 = f1_2.toBig * f1.toBig; - BigInt f1f2_2 = f1_2.toBig * f2.toBig; - BigInt f1f3_4 = f1_2.toBig * f3_2.toBig; - BigInt f1f4_2 = f1_2.toBig * f4.toBig; - BigInt f1f5_4 = f1_2.toBig * f5_2.toBig; - BigInt f1f6_2 = f1_2.toBig * f6.toBig; - BigInt f1f7_4 = f1_2.toBig * f7_2.toBig; - BigInt f1f8_2 = f1_2.toBig * f8.toBig; - BigInt f1f9_76 = f1_2.toBig * f9_38.toBig; - BigInt f2f2 = f2.toBig * f2.toBig; - BigInt f2f3_2 = f2_2.toBig * f3.toBig; - BigInt f2f4_2 = f2_2.toBig * f4.toBig; - BigInt f2f5_2 = f2_2.toBig * f5.toBig; - BigInt f2f6_2 = f2_2.toBig * f6.toBig; - BigInt f2f7_2 = f2_2.toBig * f7.toBig; - BigInt f2f8_38 = f2_2.toBig * f8_19.toBig; - BigInt f2f9_38 = f2.toBig * f9_38.toBig; - BigInt f3f3_2 = f3_2.toBig * f3.toBig; - BigInt f3f4_2 = f3_2.toBig * f4.toBig; - BigInt f3f5_4 = f3_2.toBig * f5_2.toBig; - BigInt f3f6_2 = f3_2.toBig * f6.toBig; - BigInt f3f7_76 = f3_2.toBig * f7_38.toBig; - BigInt f3f8_38 = f3_2.toBig * f8_19.toBig; - BigInt f3f9_76 = f3_2.toBig * f9_38.toBig; - BigInt f4f4 = f4.toBig * f4.toBig; - BigInt f4f5_2 = f4_2.toBig * f5.toBig; - BigInt f4f6_38 = f4_2.toBig * f6_19.toBig; - BigInt f4f7_38 = f4.toBig * f7_38.toBig; - BigInt f4f8_38 = f4_2.toBig * f8_19.toBig; - BigInt f4f9_38 = f4.toBig * f9_38.toBig; - BigInt f5f5_38 = f5.toBig * f5_38.toBig; - BigInt f5f6_38 = f5_2.toBig * f6_19.toBig; - BigInt f5f7_76 = f5_2.toBig * f7_38.toBig; - BigInt f5f8_38 = f5_2.toBig * f8_19.toBig; - BigInt f5f9_76 = f5_2.toBig * f9_38.toBig; - BigInt f6f6_19 = f6.toBig * f6_19.toBig; - BigInt f6f7_38 = f6.toBig * f7_38.toBig; - BigInt f6f8_38 = f6_2.toBig * f8_19.toBig; - BigInt f6f9_38 = f6.toBig * f9_38.toBig; - BigInt f7f7_38 = f7.toBig * f7_38.toBig; - BigInt f7f8_38 = f7_2.toBig * f8_19.toBig; - BigInt f7f9_76 = f7_2.toBig * f9_38.toBig; - BigInt f8f8_19 = f8.toBig * f8_19.toBig; - BigInt f8f9_38 = f8.toBig * f9_38.toBig; - BigInt f9f9_38 = f9.toBig * f9_38.toBig; + final int f0 = f.h[0]; + final int f1 = f.h[1]; + final int f2 = f.h[2]; + final int f3 = f.h[3]; + final int f4 = f.h[4]; + final int f5 = f.h[5]; + final int f6 = f.h[6]; + final int f7 = f.h[7]; + final int f8 = f.h[8]; + final int f9 = f.h[9]; + final int f0_2 = (2 * f0).toInt32; + final int f1_2 = (2 * f1).toInt32; + final int f2_2 = (2 * f2).toInt32; + final int f3_2 = (2 * f3).toInt32; + final int f4_2 = (2 * f4).toInt32; + final int f5_2 = (2 * f5).toInt32; + final int f6_2 = (2 * f6).toInt32; + final int f7_2 = (2 * f7).toInt32; + final int f5_38 = (38 * f5).toInt32; /* 1.959375*2^30 */ + final int f6_19 = (19 * f6).toInt32; /* 1.959375*2^30 */ + final int f7_38 = (38 * f7).toInt32; /* 1.959375*2^30 */ + final int f8_19 = (19 * f8).toInt32; /* 1.959375*2^30 */ + final int f9_38 = (38 * f9).toInt32; /* 1.959375*2^30 */ + final BigInt f0f0 = f0.toBig * f0.toBig; + + final BigInt f0f1_2 = f0_2.toBig * f1.toBig; + final BigInt f0f2_2 = f0_2.toBig * f2.toBig; + final BigInt f0f3_2 = f0_2.toBig * f3.toBig; + final BigInt f0f4_2 = f0_2.toBig * f4.toBig; + final BigInt f0f5_2 = f0_2.toBig * f5.toBig; + final BigInt f0f6_2 = f0_2.toBig * f6.toBig; + final BigInt f0f7_2 = f0_2.toBig * f7.toBig; + final BigInt f0f8_2 = f0_2.toBig * f8.toBig; + final BigInt f0f9_2 = f0_2.toBig * f9.toBig; + final BigInt f1f1_2 = f1_2.toBig * f1.toBig; + final BigInt f1f2_2 = f1_2.toBig * f2.toBig; + final BigInt f1f3_4 = f1_2.toBig * f3_2.toBig; + final BigInt f1f4_2 = f1_2.toBig * f4.toBig; + final BigInt f1f5_4 = f1_2.toBig * f5_2.toBig; + final BigInt f1f6_2 = f1_2.toBig * f6.toBig; + final BigInt f1f7_4 = f1_2.toBig * f7_2.toBig; + final BigInt f1f8_2 = f1_2.toBig * f8.toBig; + final BigInt f1f9_76 = f1_2.toBig * f9_38.toBig; + final BigInt f2f2 = f2.toBig * f2.toBig; + final BigInt f2f3_2 = f2_2.toBig * f3.toBig; + final BigInt f2f4_2 = f2_2.toBig * f4.toBig; + final BigInt f2f5_2 = f2_2.toBig * f5.toBig; + final BigInt f2f6_2 = f2_2.toBig * f6.toBig; + final BigInt f2f7_2 = f2_2.toBig * f7.toBig; + final BigInt f2f8_38 = f2_2.toBig * f8_19.toBig; + final BigInt f2f9_38 = f2.toBig * f9_38.toBig; + final BigInt f3f3_2 = f3_2.toBig * f3.toBig; + final BigInt f3f4_2 = f3_2.toBig * f4.toBig; + final BigInt f3f5_4 = f3_2.toBig * f5_2.toBig; + final BigInt f3f6_2 = f3_2.toBig * f6.toBig; + final BigInt f3f7_76 = f3_2.toBig * f7_38.toBig; + final BigInt f3f8_38 = f3_2.toBig * f8_19.toBig; + final BigInt f3f9_76 = f3_2.toBig * f9_38.toBig; + final BigInt f4f4 = f4.toBig * f4.toBig; + final BigInt f4f5_2 = f4_2.toBig * f5.toBig; + final BigInt f4f6_38 = f4_2.toBig * f6_19.toBig; + final BigInt f4f7_38 = f4.toBig * f7_38.toBig; + final BigInt f4f8_38 = f4_2.toBig * f8_19.toBig; + final BigInt f4f9_38 = f4.toBig * f9_38.toBig; + final BigInt f5f5_38 = f5.toBig * f5_38.toBig; + final BigInt f5f6_38 = f5_2.toBig * f6_19.toBig; + final BigInt f5f7_76 = f5_2.toBig * f7_38.toBig; + final BigInt f5f8_38 = f5_2.toBig * f8_19.toBig; + final BigInt f5f9_76 = f5_2.toBig * f9_38.toBig; + final BigInt f6f6_19 = f6.toBig * f6_19.toBig; + final BigInt f6f7_38 = f6.toBig * f7_38.toBig; + final BigInt f6f8_38 = f6_2.toBig * f8_19.toBig; + final BigInt f6f9_38 = f6.toBig * f9_38.toBig; + final BigInt f7f7_38 = f7.toBig * f7_38.toBig; + final BigInt f7f8_38 = f7_2.toBig * f8_19.toBig; + final BigInt f7f9_76 = f7_2.toBig * f9_38.toBig; + final BigInt f8f8_19 = f8.toBig * f8_19.toBig; + final BigInt f8f9_38 = f8.toBig * f9_38.toBig; + final BigInt f9f9_38 = f9.toBig * f9_38.toBig; BigInt h0 = f0f0 + f1f9_76 + f2f8_38 + f3f7_76 + f4f6_38 + f5f5_38; BigInt h1 = f0f1_2 + f2f9_38 + f3f8_38 + f4f7_38 + f5f6_38; BigInt h2 = f0f2_2 + f1f1_2 + f3f9_76 + f4f8_38 + f5f7_76 + f6f6_19; @@ -755,36 +755,36 @@ class CryptoOps { } static void feSub(FieldElement h, FieldElement f, FieldElement g) { - int f0 = f.h[0]; - int f1 = f.h[1]; - int f2 = f.h[2]; - int f3 = f.h[3]; - int f4 = f.h[4]; - int f5 = f.h[5]; - int f6 = f.h[6]; - int f7 = f.h[7]; - int f8 = f.h[8]; - int f9 = f.h[9]; - int g0 = g.h[0]; - int g1 = g.h[1]; - int g2 = g.h[2]; - int g3 = g.h[3]; - int g4 = g.h[4]; - int g5 = g.h[5]; - int g6 = g.h[6]; - int g7 = g.h[7]; - int g8 = g.h[8]; - int g9 = g.h[9]; - int h0 = f0 - g0; - int h1 = f1 - g1; - int h2 = f2 - g2; - int h3 = f3 - g3; - int h4 = f4 - g4; - int h5 = f5 - g5; - int h6 = f6 - g6; - int h7 = f7 - g7; - int h8 = f8 - g8; - int h9 = f9 - g9; + final int f0 = f.h[0]; + final int f1 = f.h[1]; + final int f2 = f.h[2]; + final int f3 = f.h[3]; + final int f4 = f.h[4]; + final int f5 = f.h[5]; + final int f6 = f.h[6]; + final int f7 = f.h[7]; + final int f8 = f.h[8]; + final int f9 = f.h[9]; + final int g0 = g.h[0]; + final int g1 = g.h[1]; + final int g2 = g.h[2]; + final int g3 = g.h[3]; + final int g4 = g.h[4]; + final int g5 = g.h[5]; + final int g6 = g.h[6]; + final int g7 = g.h[7]; + final int g8 = g.h[8]; + final int g9 = g.h[9]; + final int h0 = f0 - g0; + final int h1 = f1 - g1; + final int h2 = f2 - g2; + final int h3 = f3 - g3; + final int h4 = f4 - g4; + final int h5 = f5 - g5; + final int h6 = f6 - g6; + final int h7 = f7 - g7; + final int h8 = f8 - g8; + final int h9 = f9 - g9; h.h[0] = h0; h.h[1] = h1; h.h[2] = h2; @@ -873,7 +873,7 @@ class CryptoOps { evidently 2^255 h10-2^255 q = 0. Goal: Output h0+...+2^230 h9. */ - List sBig = List.filled(32, BigInt.zero); + final List sBig = List.filled(32, BigInt.zero); sBig[0] = h0 >> 0; sBig[1] = h0 >> 8; sBig[2] = h0 >> 16; @@ -912,141 +912,141 @@ class CryptoOps { } static void feMul(FieldElement h, FieldElement f, FieldElement g) { - int f0 = f.h[0]; - int f1 = f.h[1]; - int f2 = f.h[2]; - int f3 = f.h[3]; - int f4 = f.h[4]; - int f5 = f.h[5]; - int f6 = f.h[6]; - int f7 = f.h[7]; - int f8 = f.h[8]; - int f9 = f.h[9]; - int g0 = g.h[0]; - int g1 = g.h[1]; - int g2 = g.h[2]; - int g3 = g.h[3]; - int g4 = g.h[4]; - int g5 = g.h[5]; - int g6 = g.h[6]; - int g7 = g.h[7]; - int g8 = g.h[8]; - int g9 = g.h[9]; - int g1_19 = (19 * g1).toInt32; /* 1.959375*2^29 */ - int g2_19 = (19 * g2).toInt32; /* 1.959375*2^30; still ok */ - int g3_19 = (19 * g3).toInt32; - int g4_19 = (19 * g4).toInt32; - int g5_19 = (19 * g5).toInt32; - int g6_19 = (19 * g6).toInt32; - int g7_19 = (19 * g7).toInt32; - int g8_19 = (19 * g8).toInt32; - int g9_19 = (19 * g9).toInt32; - int f1_2 = (2 * f1).toInt32; - int f3_2 = (2 * f3).toInt32; - int f5_2 = (2 * f5).toInt32; - int f7_2 = (2 * f7).toInt32; - int f9_2 = (2 * f9).toInt32; - - BigInt f0g0 = f0.toBig * g0.toBig; - BigInt f0g1 = f0.toBig * g1.toBig; - BigInt f0g2 = f0.toBig * g2.toBig; - BigInt f0g3 = f0.toBig * g3.toBig; - BigInt f0g4 = f0.toBig * g4.toBig; - BigInt f0g5 = f0.toBig * g5.toBig; - BigInt f0g6 = f0.toBig * g6.toBig; - BigInt f0g7 = f0.toBig * g7.toBig; - BigInt f0g8 = f0.toBig * g8.toBig; - BigInt f0g9 = f0.toBig * g9.toBig; - BigInt f1g0 = f1.toBig * g0.toBig; - BigInt f1g1_2 = f1_2.toBig * g1.toBig; - BigInt f1g2 = f1.toBig * g2.toBig; - BigInt f1g3_2 = f1_2.toBig * g3.toBig; - BigInt f1g4 = f1.toBig * g4.toBig; - BigInt f1g5_2 = f1_2.toBig * g5.toBig; - BigInt f1g6 = f1.toBig * g6.toBig; - BigInt f1g7_2 = f1_2.toBig * g7.toBig; - BigInt f1g8 = f1.toBig * g8.toBig; - BigInt f1g9_38 = f1_2.toBig * g9_19.toBig; - BigInt f2g0 = f2.toBig * g0.toBig; - BigInt f2g1 = f2.toBig * g1.toBig; - BigInt f2g2 = f2.toBig * g2.toBig; - BigInt f2g3 = f2.toBig * g3.toBig; - BigInt f2g4 = f2.toBig * g4.toBig; - BigInt f2g5 = f2.toBig * g5.toBig; - BigInt f2g6 = f2.toBig * g6.toBig; - BigInt f2g7 = f2.toBig * g7.toBig; - BigInt f2g8_19 = f2.toBig * g8_19.toBig; - BigInt f2g9_19 = f2.toBig * g9_19.toBig; - BigInt f3g0 = f3.toBig * g0.toBig; - BigInt f3g1_2 = f3_2.toBig * g1.toBig; - BigInt f3g2 = f3.toBig * g2.toBig; - BigInt f3g3_2 = f3_2.toBig * g3.toBig; - BigInt f3g4 = f3.toBig * g4.toBig; - BigInt f3g5_2 = f3_2.toBig * g5.toBig; - BigInt f3g6 = f3.toBig * g6.toBig; - BigInt f3g7_38 = f3_2.toBig * g7_19.toBig; - BigInt f3g8_19 = f3.toBig * g8_19.toBig; - BigInt f3g9_38 = f3_2.toBig * g9_19.toBig; - BigInt f4g0 = f4.toBig * g0.toBig; - BigInt f4g1 = f4.toBig * g1.toBig; - BigInt f4g2 = f4.toBig * g2.toBig; - BigInt f4g3 = f4.toBig * g3.toBig; - BigInt f4g4 = f4.toBig * g4.toBig; - BigInt f4g5 = f4.toBig * g5.toBig; - BigInt f4g6_19 = f4.toBig * g6_19.toBig; - BigInt f4g7_19 = f4.toBig * g7_19.toBig; - BigInt f4g8_19 = f4.toBig * g8_19.toBig; - BigInt f4g9_19 = f4.toBig * g9_19.toBig; - BigInt f5g0 = f5.toBig * g0.toBig; - BigInt f5g1_2 = f5_2.toBig * g1.toBig; - BigInt f5g2 = f5.toBig * g2.toBig; - BigInt f5g3_2 = f5_2.toBig * g3.toBig; - BigInt f5g4 = f5.toBig * g4.toBig; - BigInt f5g5_38 = f5_2.toBig * g5_19.toBig; - BigInt f5g6_19 = f5.toBig * g6_19.toBig; - BigInt f5g7_38 = f5_2.toBig * g7_19.toBig; - BigInt f5g8_19 = f5.toBig * g8_19.toBig; - BigInt f5g9_38 = f5_2.toBig * g9_19.toBig; - BigInt f6g0 = f6.toBig * g0.toBig; - BigInt f6g1 = f6.toBig * g1.toBig; - BigInt f6g2 = f6.toBig * g2.toBig; - BigInt f6g3 = f6.toBig * g3.toBig; - BigInt f6g4_19 = f6.toBig * g4_19.toBig; - BigInt f6g5_19 = f6.toBig * g5_19.toBig; - BigInt f6g6_19 = f6.toBig * g6_19.toBig; - BigInt f6g7_19 = f6.toBig * g7_19.toBig; - BigInt f6g8_19 = f6.toBig * g8_19.toBig; - BigInt f6g9_19 = f6.toBig * g9_19.toBig; - BigInt f7g0 = f7.toBig * g0.toBig; - BigInt f7g1_2 = f7_2.toBig * g1.toBig; - BigInt f7g2 = f7.toBig * g2.toBig; - BigInt f7g3_38 = f7_2.toBig * g3_19.toBig; - BigInt f7g4_19 = f7.toBig * g4_19.toBig; - BigInt f7g5_38 = f7_2.toBig * g5_19.toBig; - BigInt f7g6_19 = f7.toBig * g6_19.toBig; - BigInt f7g7_38 = f7_2.toBig * g7_19.toBig; - BigInt f7g8_19 = f7.toBig * g8_19.toBig; - BigInt f7g9_38 = f7_2.toBig * g9_19.toBig; - BigInt f8g0 = f8.toBig * g0.toBig; - BigInt f8g1 = f8.toBig * g1.toBig; - BigInt f8g2_19 = f8.toBig * g2_19.toBig; - BigInt f8g3_19 = f8.toBig * g3_19.toBig; - BigInt f8g4_19 = f8.toBig * g4_19.toBig; - BigInt f8g5_19 = f8.toBig * g5_19.toBig; - BigInt f8g6_19 = f8.toBig * g6_19.toBig; - BigInt f8g7_19 = f8.toBig * g7_19.toBig; - BigInt f8g8_19 = f8.toBig * g8_19.toBig; - BigInt f8g9_19 = f8.toBig * g9_19.toBig; - BigInt f9g0 = f9.toBig * g0.toBig; - BigInt f9g1_38 = f9_2.toBig * g1_19.toBig; - BigInt f9g2_19 = f9.toBig * g2_19.toBig; - BigInt f9g3_38 = f9_2.toBig * g3_19.toBig; - BigInt f9g4_19 = f9.toBig * g4_19.toBig; - BigInt f9g5_38 = f9_2.toBig * g5_19.toBig; - BigInt f9g6_19 = f9.toBig * g6_19.toBig; - BigInt f9g7_38 = f9_2.toBig * g7_19.toBig; - BigInt f9g8_19 = f9.toBig * g8_19.toBig; - BigInt f9g9_38 = f9_2.toBig * g9_19.toBig; + final int f0 = f.h[0]; + final int f1 = f.h[1]; + final int f2 = f.h[2]; + final int f3 = f.h[3]; + final int f4 = f.h[4]; + final int f5 = f.h[5]; + final int f6 = f.h[6]; + final int f7 = f.h[7]; + final int f8 = f.h[8]; + final int f9 = f.h[9]; + final int g0 = g.h[0]; + final int g1 = g.h[1]; + final int g2 = g.h[2]; + final int g3 = g.h[3]; + final int g4 = g.h[4]; + final int g5 = g.h[5]; + final int g6 = g.h[6]; + final int g7 = g.h[7]; + final int g8 = g.h[8]; + final int g9 = g.h[9]; + final int g1_19 = (19 * g1).toInt32; /* 1.959375*2^29 */ + final int g2_19 = (19 * g2).toInt32; /* 1.959375*2^30; still ok */ + final int g3_19 = (19 * g3).toInt32; + final int g4_19 = (19 * g4).toInt32; + final int g5_19 = (19 * g5).toInt32; + final int g6_19 = (19 * g6).toInt32; + final int g7_19 = (19 * g7).toInt32; + final int g8_19 = (19 * g8).toInt32; + final int g9_19 = (19 * g9).toInt32; + final int f1_2 = (2 * f1).toInt32; + final int f3_2 = (2 * f3).toInt32; + final int f5_2 = (2 * f5).toInt32; + final int f7_2 = (2 * f7).toInt32; + final int f9_2 = (2 * f9).toInt32; + + final BigInt f0g0 = f0.toBig * g0.toBig; + final BigInt f0g1 = f0.toBig * g1.toBig; + final BigInt f0g2 = f0.toBig * g2.toBig; + final BigInt f0g3 = f0.toBig * g3.toBig; + final BigInt f0g4 = f0.toBig * g4.toBig; + final BigInt f0g5 = f0.toBig * g5.toBig; + final BigInt f0g6 = f0.toBig * g6.toBig; + final BigInt f0g7 = f0.toBig * g7.toBig; + final BigInt f0g8 = f0.toBig * g8.toBig; + final BigInt f0g9 = f0.toBig * g9.toBig; + final BigInt f1g0 = f1.toBig * g0.toBig; + final BigInt f1g1_2 = f1_2.toBig * g1.toBig; + final BigInt f1g2 = f1.toBig * g2.toBig; + final BigInt f1g3_2 = f1_2.toBig * g3.toBig; + final BigInt f1g4 = f1.toBig * g4.toBig; + final BigInt f1g5_2 = f1_2.toBig * g5.toBig; + final BigInt f1g6 = f1.toBig * g6.toBig; + final BigInt f1g7_2 = f1_2.toBig * g7.toBig; + final BigInt f1g8 = f1.toBig * g8.toBig; + final BigInt f1g9_38 = f1_2.toBig * g9_19.toBig; + final BigInt f2g0 = f2.toBig * g0.toBig; + final BigInt f2g1 = f2.toBig * g1.toBig; + final BigInt f2g2 = f2.toBig * g2.toBig; + final BigInt f2g3 = f2.toBig * g3.toBig; + final BigInt f2g4 = f2.toBig * g4.toBig; + final BigInt f2g5 = f2.toBig * g5.toBig; + final BigInt f2g6 = f2.toBig * g6.toBig; + final BigInt f2g7 = f2.toBig * g7.toBig; + final BigInt f2g8_19 = f2.toBig * g8_19.toBig; + final BigInt f2g9_19 = f2.toBig * g9_19.toBig; + final BigInt f3g0 = f3.toBig * g0.toBig; + final BigInt f3g1_2 = f3_2.toBig * g1.toBig; + final BigInt f3g2 = f3.toBig * g2.toBig; + final BigInt f3g3_2 = f3_2.toBig * g3.toBig; + final BigInt f3g4 = f3.toBig * g4.toBig; + final BigInt f3g5_2 = f3_2.toBig * g5.toBig; + final BigInt f3g6 = f3.toBig * g6.toBig; + final BigInt f3g7_38 = f3_2.toBig * g7_19.toBig; + final BigInt f3g8_19 = f3.toBig * g8_19.toBig; + final BigInt f3g9_38 = f3_2.toBig * g9_19.toBig; + final BigInt f4g0 = f4.toBig * g0.toBig; + final BigInt f4g1 = f4.toBig * g1.toBig; + final BigInt f4g2 = f4.toBig * g2.toBig; + final BigInt f4g3 = f4.toBig * g3.toBig; + final BigInt f4g4 = f4.toBig * g4.toBig; + final BigInt f4g5 = f4.toBig * g5.toBig; + final BigInt f4g6_19 = f4.toBig * g6_19.toBig; + final BigInt f4g7_19 = f4.toBig * g7_19.toBig; + final BigInt f4g8_19 = f4.toBig * g8_19.toBig; + final BigInt f4g9_19 = f4.toBig * g9_19.toBig; + final BigInt f5g0 = f5.toBig * g0.toBig; + final BigInt f5g1_2 = f5_2.toBig * g1.toBig; + final BigInt f5g2 = f5.toBig * g2.toBig; + final BigInt f5g3_2 = f5_2.toBig * g3.toBig; + final BigInt f5g4 = f5.toBig * g4.toBig; + final BigInt f5g5_38 = f5_2.toBig * g5_19.toBig; + final BigInt f5g6_19 = f5.toBig * g6_19.toBig; + final BigInt f5g7_38 = f5_2.toBig * g7_19.toBig; + final BigInt f5g8_19 = f5.toBig * g8_19.toBig; + final BigInt f5g9_38 = f5_2.toBig * g9_19.toBig; + final BigInt f6g0 = f6.toBig * g0.toBig; + final BigInt f6g1 = f6.toBig * g1.toBig; + final BigInt f6g2 = f6.toBig * g2.toBig; + final BigInt f6g3 = f6.toBig * g3.toBig; + final BigInt f6g4_19 = f6.toBig * g4_19.toBig; + final BigInt f6g5_19 = f6.toBig * g5_19.toBig; + final BigInt f6g6_19 = f6.toBig * g6_19.toBig; + final BigInt f6g7_19 = f6.toBig * g7_19.toBig; + final BigInt f6g8_19 = f6.toBig * g8_19.toBig; + final BigInt f6g9_19 = f6.toBig * g9_19.toBig; + final BigInt f7g0 = f7.toBig * g0.toBig; + final BigInt f7g1_2 = f7_2.toBig * g1.toBig; + final BigInt f7g2 = f7.toBig * g2.toBig; + final BigInt f7g3_38 = f7_2.toBig * g3_19.toBig; + final BigInt f7g4_19 = f7.toBig * g4_19.toBig; + final BigInt f7g5_38 = f7_2.toBig * g5_19.toBig; + final BigInt f7g6_19 = f7.toBig * g6_19.toBig; + final BigInt f7g7_38 = f7_2.toBig * g7_19.toBig; + final BigInt f7g8_19 = f7.toBig * g8_19.toBig; + final BigInt f7g9_38 = f7_2.toBig * g9_19.toBig; + final BigInt f8g0 = f8.toBig * g0.toBig; + final BigInt f8g1 = f8.toBig * g1.toBig; + final BigInt f8g2_19 = f8.toBig * g2_19.toBig; + final BigInt f8g3_19 = f8.toBig * g3_19.toBig; + final BigInt f8g4_19 = f8.toBig * g4_19.toBig; + final BigInt f8g5_19 = f8.toBig * g5_19.toBig; + final BigInt f8g6_19 = f8.toBig * g6_19.toBig; + final BigInt f8g7_19 = f8.toBig * g7_19.toBig; + final BigInt f8g8_19 = f8.toBig * g8_19.toBig; + final BigInt f8g9_19 = f8.toBig * g9_19.toBig; + final BigInt f9g0 = f9.toBig * g0.toBig; + final BigInt f9g1_38 = f9_2.toBig * g1_19.toBig; + final BigInt f9g2_19 = f9.toBig * g2_19.toBig; + final BigInt f9g3_38 = f9_2.toBig * g3_19.toBig; + final BigInt f9g4_19 = f9.toBig * g4_19.toBig; + final BigInt f9g5_38 = f9_2.toBig * g5_19.toBig; + final BigInt f9g6_19 = f9.toBig * g6_19.toBig; + final BigInt f9g7_38 = f9_2.toBig * g7_19.toBig; + final BigInt f9g8_19 = f9.toBig * g8_19.toBig; + final BigInt f9g9_38 = f9_2.toBig * g9_19.toBig; BigInt h0 = f0g0 + f1g9_38 + f2g8_19 + @@ -1237,7 +1237,7 @@ class CryptoOps { } static void feDivpowm1(FieldElement r, FieldElement u, FieldElement v) { - FieldElement v3 = FieldElement(), + final FieldElement v3 = FieldElement(), uv7 = FieldElement(), t0 = FieldElement(), t1 = FieldElement(), @@ -1307,7 +1307,7 @@ class CryptoOps { static int feIsnonzero(FieldElement f) { final List s = List.filled(32, 0); feTobytes(s, f); - for (int byte in s) { + for (final byte in s) { if (byte != 0) { return 1; // Found a non-zero byte } @@ -1316,10 +1316,10 @@ class CryptoOps { } static void feInvert(FieldElement out, FieldElement z) { - FieldElement t0 = FieldElement(); - FieldElement t1 = FieldElement(); - FieldElement t2 = FieldElement(); - FieldElement t3 = FieldElement(); + final FieldElement t0 = FieldElement(); + final FieldElement t1 = FieldElement(); + final FieldElement t2 = FieldElement(); + final FieldElement t3 = FieldElement(); int i; feSq(t0, z); @@ -1380,9 +1380,9 @@ class CryptoOps { } static void geToBytes(List s, GroupElementP2 h) { - FieldElement recip = FieldElement(); - FieldElement x = FieldElement(); - FieldElement y = FieldElement(); + final FieldElement recip = FieldElement(); + final FieldElement x = FieldElement(); + final FieldElement y = FieldElement(); feInvert(recip, h.z); feMul(x, h.x, recip); feMul(y, h.y, recip); @@ -1392,7 +1392,7 @@ class CryptoOps { static void geSub( GroupElementP1P1 r, GroupElementP3 p, GroupElementCached q) { - FieldElement t0 = FieldElement(); + final FieldElement t0 = FieldElement(); feAdd(r.x, p.y, p.x); feSub(r.y, p.y, p.x); feMul(r.z, r.x, q.yMinusX); @@ -1410,30 +1410,30 @@ class CryptoOps { s.asMin32("scMul"); a.asMin32("scMul"); b.asMin32("scMul"); - BigInt a0 = _b2097151 & _load3(a, 0); - BigInt a1 = _b2097151 & (_load4(a, 2) >> 5); - BigInt a2 = _b2097151 & (_load3(a, 5) >> 2); - BigInt a3 = _b2097151 & (_load4(a, 7) >> 7); - BigInt a4 = _b2097151 & (_load4(a, 10) >> 4); - BigInt a5 = _b2097151 & (_load3(a, 13) >> 1); - BigInt a6 = _b2097151 & (_load4(a, 15) >> 6); - BigInt a7 = _b2097151 & (_load3(a, 18) >> 3); - BigInt a8 = _b2097151 & _load3(a, 21); - BigInt a9 = _b2097151 & (_load4(a, 23) >> 5); - BigInt a10 = _b2097151 & (_load3(a, 26) >> 2); - BigInt a11 = (_load4(a, 28) >> 7); - BigInt b0 = _b2097151 & _load3(b, 0); - BigInt b1 = _b2097151 & (_load4(b, 2) >> 5); - BigInt b2 = _b2097151 & (_load3(b, 5) >> 2); - BigInt b3 = _b2097151 & (_load4(b, 7) >> 7); - BigInt b4 = _b2097151 & (_load4(b, 10) >> 4); - BigInt b5 = _b2097151 & (_load3(b, 13) >> 1); - BigInt b6 = _b2097151 & (_load4(b, 15) >> 6); - BigInt b7 = _b2097151 & (_load3(b, 18) >> 3); - BigInt b8 = _b2097151 & _load3(b, 21); - BigInt b9 = _b2097151 & (_load4(b, 23) >> 5); - BigInt b10 = _b2097151 & (_load3(b, 26) >> 2); - BigInt b11 = (_load4(b, 28) >> 7); + final BigInt a0 = _b2097151 & _load3(a, 0); + final BigInt a1 = _b2097151 & (_load4(a, 2) >> 5); + final BigInt a2 = _b2097151 & (_load3(a, 5) >> 2); + final BigInt a3 = _b2097151 & (_load4(a, 7) >> 7); + final BigInt a4 = _b2097151 & (_load4(a, 10) >> 4); + final BigInt a5 = _b2097151 & (_load3(a, 13) >> 1); + final BigInt a6 = _b2097151 & (_load4(a, 15) >> 6); + final BigInt a7 = _b2097151 & (_load3(a, 18) >> 3); + final BigInt a8 = _b2097151 & _load3(a, 21); + final BigInt a9 = _b2097151 & (_load4(a, 23) >> 5); + final BigInt a10 = _b2097151 & (_load3(a, 26) >> 2); + final BigInt a11 = (_load4(a, 28) >> 7); + final BigInt b0 = _b2097151 & _load3(b, 0); + final BigInt b1 = _b2097151 & (_load4(b, 2) >> 5); + final BigInt b2 = _b2097151 & (_load3(b, 5) >> 2); + final BigInt b3 = _b2097151 & (_load4(b, 7) >> 7); + final BigInt b4 = _b2097151 & (_load4(b, 10) >> 4); + final BigInt b5 = _b2097151 & (_load3(b, 13) >> 1); + final BigInt b6 = _b2097151 & (_load4(b, 15) >> 6); + final BigInt b7 = _b2097151 & (_load3(b, 18) >> 3); + final BigInt b8 = _b2097151 & _load3(b, 21); + final BigInt b9 = _b2097151 & (_load4(b, 23) >> 5); + final BigInt b10 = _b2097151 & (_load3(b, 26) >> 2); + final BigInt b11 = (_load4(b, 28) >> 7); BigInt s0; BigInt s1; BigInt s2; @@ -1906,7 +1906,7 @@ class CryptoOps { carry10 = s10 >> 21; s11 += carry10; s10 -= carry10 << 21; - List sBig = List.filled(32, BigInt.zero); + final List sBig = List.filled(32, BigInt.zero); sBig[0] = s0 >> 0; sBig[1] = s0 >> 8; sBig[2] = (s0 >> 16) | (s1 << 5); @@ -1956,42 +1956,42 @@ class CryptoOps { a.asMin32("scMulAdd"); b.asMin32("scMulAdd"); c.asMin32("scMulAdd"); - BigInt a0 = _b2097151 & _load3(a, 0); - BigInt a1 = _b2097151 & (_load4(a, 2) >> 5); - BigInt a2 = _b2097151 & (_load3(a, 5) >> 2); - BigInt a3 = _b2097151 & (_load4(a, 7) >> 7); - BigInt a4 = _b2097151 & (_load4(a, 10) >> 4); - BigInt a5 = _b2097151 & (_load3(a, 13) >> 1); - BigInt a6 = _b2097151 & (_load4(a, 15) >> 6); - BigInt a7 = _b2097151 & (_load3(a, 18) >> 3); - BigInt a8 = _b2097151 & _load3(a, 21); - BigInt a9 = _b2097151 & (_load4(a, 23) >> 5); - BigInt a10 = _b2097151 & (_load3(a, 26) >> 2); - BigInt a11 = (_load4(a, 28) >> 7); - BigInt b0 = _b2097151 & _load3(b, 0); - BigInt b1 = _b2097151 & (_load4(b, 2) >> 5); - BigInt b2 = _b2097151 & (_load3(b, 5) >> 2); - BigInt b3 = _b2097151 & (_load4(b, 7) >> 7); - BigInt b4 = _b2097151 & (_load4(b, 10) >> 4); - BigInt b5 = _b2097151 & (_load3(b, 13) >> 1); - BigInt b6 = _b2097151 & (_load4(b, 15) >> 6); - BigInt b7 = _b2097151 & (_load3(b, 18) >> 3); - BigInt b8 = _b2097151 & _load3(b, 21); - BigInt b9 = _b2097151 & (_load4(b, 23) >> 5); - BigInt b10 = _b2097151 & (_load3(b, 26) >> 2); - BigInt b11 = (_load4(b, 28) >> 7); - BigInt c0 = _b2097151 & _load3(c, 0); - BigInt c1 = _b2097151 & (_load4(c, 2) >> 5); - BigInt c2 = _b2097151 & (_load3(c, 5) >> 2); - BigInt c3 = _b2097151 & (_load4(c, 7) >> 7); - BigInt c4 = _b2097151 & (_load4(c, 10) >> 4); - BigInt c5 = _b2097151 & (_load3(c, 13) >> 1); - BigInt c6 = _b2097151 & (_load4(c, 15) >> 6); - BigInt c7 = _b2097151 & (_load3(c, 18) >> 3); - BigInt c8 = _b2097151 & _load3(c, 21); - BigInt c9 = _b2097151 & (_load4(c, 23) >> 5); - BigInt c10 = _b2097151 & (_load3(c, 26) >> 2); - BigInt c11 = (_load4(c, 28) >> 7); + final BigInt a0 = _b2097151 & _load3(a, 0); + final BigInt a1 = _b2097151 & (_load4(a, 2) >> 5); + final BigInt a2 = _b2097151 & (_load3(a, 5) >> 2); + final BigInt a3 = _b2097151 & (_load4(a, 7) >> 7); + final BigInt a4 = _b2097151 & (_load4(a, 10) >> 4); + final BigInt a5 = _b2097151 & (_load3(a, 13) >> 1); + final BigInt a6 = _b2097151 & (_load4(a, 15) >> 6); + final BigInt a7 = _b2097151 & (_load3(a, 18) >> 3); + final BigInt a8 = _b2097151 & _load3(a, 21); + final BigInt a9 = _b2097151 & (_load4(a, 23) >> 5); + final BigInt a10 = _b2097151 & (_load3(a, 26) >> 2); + final BigInt a11 = (_load4(a, 28) >> 7); + final BigInt b0 = _b2097151 & _load3(b, 0); + final BigInt b1 = _b2097151 & (_load4(b, 2) >> 5); + final BigInt b2 = _b2097151 & (_load3(b, 5) >> 2); + final BigInt b3 = _b2097151 & (_load4(b, 7) >> 7); + final BigInt b4 = _b2097151 & (_load4(b, 10) >> 4); + final BigInt b5 = _b2097151 & (_load3(b, 13) >> 1); + final BigInt b6 = _b2097151 & (_load4(b, 15) >> 6); + final BigInt b7 = _b2097151 & (_load3(b, 18) >> 3); + final BigInt b8 = _b2097151 & _load3(b, 21); + final BigInt b9 = _b2097151 & (_load4(b, 23) >> 5); + final BigInt b10 = _b2097151 & (_load3(b, 26) >> 2); + final BigInt b11 = (_load4(b, 28) >> 7); + final BigInt c0 = _b2097151 & _load3(c, 0); + final BigInt c1 = _b2097151 & (_load4(c, 2) >> 5); + final BigInt c2 = _b2097151 & (_load3(c, 5) >> 2); + final BigInt c3 = _b2097151 & (_load4(c, 7) >> 7); + final BigInt c4 = _b2097151 & (_load4(c, 10) >> 4); + final BigInt c5 = _b2097151 & (_load3(c, 13) >> 1); + final BigInt c6 = _b2097151 & (_load4(c, 15) >> 6); + final BigInt c7 = _b2097151 & (_load3(c, 18) >> 3); + final BigInt c8 = _b2097151 & _load3(c, 21); + final BigInt c9 = _b2097151 & (_load4(c, 23) >> 5); + final BigInt c10 = _b2097151 & (_load3(c, 26) >> 2); + final BigInt c11 = (_load4(c, 28) >> 7); BigInt s0; BigInt s1; BigInt s2; @@ -2470,7 +2470,7 @@ class CryptoOps { carry10 = s10 >> 21; s11 += carry10; s10 -= carry10 << 21; - List sBig = List.filled(32, BigInt.zero); + final List sBig = List.filled(32, BigInt.zero); sBig[0] = s0 >> 0; sBig[1] = s0 >> 8; sBig[2] = (s0 >> 16) | (s1 << 5); @@ -2509,9 +2509,9 @@ class CryptoOps { } static void geDsmPrecomp(List r, GroupElementP3 s) { - GroupElementP1P1 t = GroupElementP1P1(); - GroupElementP3 s2 = GroupElementP3(); - GroupElementP3 u = GroupElementP3(); + final GroupElementP1P1 t = GroupElementP1P1(); + final GroupElementP3 s2 = GroupElementP3(); + final GroupElementP3 u = GroupElementP3(); geP3ToCached(r[0], s); geP3Dbl(t, s); @@ -2577,7 +2577,7 @@ class CryptoOps { static void geMsub( GroupElementP1P1 r, GroupElementP3 p, GroupElementPrecomp q) { - FieldElement t0 = FieldElement(); + final FieldElement t0 = FieldElement(); feAdd(r.x, p.y, p.x); feSub(r.y, p.y, p.x); feMul(r.z, r.x, q.yminusx); @@ -2595,10 +2595,10 @@ class CryptoOps { b.asMin32("geDoubleScalarMultBaseVartimeP3"); final List aslide = List.filled(256, 0); final List bslide = List.filled(256, 0); - List aI = GroupElementCached.dsmp; - GroupElementP1P1 t = GroupElementP1P1(); - GroupElementP3 u = GroupElementP3(); - GroupElementP2 r = GroupElementP2(); + final List aI = GroupElementCached.dsmp; + final GroupElementP1P1 t = GroupElementP1P1(); + final GroupElementP3 u = GroupElementP3(); + final GroupElementP2 r = GroupElementP2(); int i; slide(aslide, a); @@ -2645,7 +2645,7 @@ class CryptoOps { b.asMin32("geDoubleScalarMultBaseVartime"); final List aslide = List.filled(256, 0); final List bslide = List.filled(256, 0); - List aI = GroupElementCached.dsmp; + final List aI = GroupElementCached.dsmp; final GroupElementP1P1 t = GroupElementP1P1(); final GroupElementP3 u = GroupElementP3(); int i; @@ -2686,7 +2686,7 @@ class CryptoOps { static void geFromfeFrombytesVartime(GroupElementP2 r, List s) { s.asMin32("geFromfeFrombytesVartime"); - FieldElement u = FieldElement(), + final FieldElement u = FieldElement(), v = FieldElement(), w = FieldElement(), x = FieldElement(), @@ -2813,9 +2813,9 @@ class CryptoOps { static List geP3Tobytes_(GroupElementP3 h) { final List s = List.filled(32, 0); - FieldElement recip = FieldElement(); - FieldElement x = FieldElement(); - FieldElement y = FieldElement(); + final FieldElement recip = FieldElement(); + final FieldElement x = FieldElement(); + final FieldElement y = FieldElement(); feInvert(recip, h.z); feMul(x, h.x, recip); @@ -2826,9 +2826,9 @@ class CryptoOps { } static void geP3Tobytes(List s, GroupElementP3 h) { - FieldElement recip = FieldElement(); - FieldElement x = FieldElement(); - FieldElement y = FieldElement(); + final FieldElement recip = FieldElement(); + final FieldElement x = FieldElement(); + final FieldElement y = FieldElement(); feInvert(recip, h.z); feMul(x, h.x, recip); @@ -2839,7 +2839,7 @@ class CryptoOps { static void geAdd( GroupElementP1P1 r, GroupElementP3 p, GroupElementCached q) { - FieldElement t0 = FieldElement(); + final FieldElement t0 = FieldElement(); feAdd(r.x, p.y, p.x); feSub(r.y, p.y, p.x); feMul(r.z, r.x, q.yPlusX); @@ -2867,9 +2867,9 @@ class CryptoOps { } static int equal(int b, int c) { - int ub = b & 0xFF; - int uc = c & 0xFF; - int x = ub ^ uc; + final int ub = b & 0xFF; + final int uc = c & 0xFF; + final int x = ub ^ uc; BigInt y = BigInt.from(x) & BigInt.from(0xFFFFFFFF); y = y - BigInt.one; y = y >> 31; @@ -2891,7 +2891,7 @@ class CryptoOps { static void geMadd( GroupElementP1P1 r, GroupElementP3 p, GroupElementPrecomp q) { - FieldElement t0 = FieldElement(); + final FieldElement t0 = FieldElement(); feAdd(r.x, p.y, p.x); feSub(r.y, p.y, p.x); feMul(r.z, r.x, q.yplusx); @@ -2905,7 +2905,7 @@ class CryptoOps { } static void geP3Dbl(GroupElementP1P1 r, GroupElementP3 p) { - GroupElementP2 q = GroupElementP2(); + final GroupElementP2 q = GroupElementP2(); geP3ToP2(q, p); geP2Dbl(r, q); } @@ -2930,9 +2930,9 @@ class CryptoOps { } static void select(GroupElementPrecomp t, int pos, int b) { - GroupElementPrecomp minust = GroupElementPrecomp(); - int bnegative = negative(b); - int babs = b - (((-bnegative) & b) << 1); + final GroupElementPrecomp minust = GroupElementPrecomp(); + final int bnegative = negative(b); + final int babs = b - (((-bnegative) & b) << 1); gePrecompZero(t); gePrecompCmov(t, CryptoOpsConst.geBase[pos][0], equal(babs, 1)); @@ -2957,11 +2957,11 @@ class CryptoOps { static void geScalarMultBase(GroupElementP3 h, List a) { a.asMin32("geScalarMultBase"); - List e = List.filled(64, 0); + final List e = List.filled(64, 0); int carry; - GroupElementP1P1 r = GroupElementP1P1(); - GroupElementP2 s = GroupElementP2(); - GroupElementPrecomp t = GroupElementPrecomp(); + final GroupElementP1P1 r = GroupElementP1P1(); + final GroupElementP2 s = GroupElementP2(); + final GroupElementPrecomp t = GroupElementPrecomp(); int i; for (i = 0; i < 32; ++i) { @@ -3003,12 +3003,12 @@ class CryptoOps { static void geScalarMult(GroupElementP2 r, List a, GroupElementP3 gA) { a.asMin32("geScalarMultBase"); - List e = List.filled(64, 0); + final List e = List.filled(64, 0); int carry, carry2, i; - List aI = + final List aI = GroupElementCached.dsmp; /* 1 * A, 2 * A, ..., 8 * A */ - GroupElementP1P1 t = GroupElementP1P1(); - GroupElementP3 u = GroupElementP3(); + final GroupElementP1P1 t = GroupElementP1P1(); + final GroupElementP3 u = GroupElementP3(); carry = 0; /* 0..1 */ for (i = 0; i < 31; i++) { @@ -3032,10 +3032,10 @@ class CryptoOps { geP2Zero(r); for (i = 63; i >= 0; i--) { - int b = e[i]; - int bnegative = negative(b); - int babs = b - (((-bnegative) & b) << 1); - GroupElementCached cur = GroupElementCached(), + final int b = e[i]; + final int bnegative = negative(b); + final int babs = b - (((-bnegative) & b) << 1); + final GroupElementCached cur = GroupElementCached(), minuscur = GroupElementCached(); geP2Dbl(t, r); geP1P1ToP2(r, t); @@ -3078,32 +3078,32 @@ class CryptoOps { } static int feIsnegative(FieldElement f) { - List s = List.filled(32, 0); + final List s = List.filled(32, 0); feTobytes(s, f); return s[0] & 1; } static void feNeg(FieldElement h, FieldElement f) { - int f0 = f.h[0]; - int f1 = f.h[1]; - int f2 = f.h[2]; - int f3 = f.h[3]; - int f4 = f.h[4]; - int f5 = f.h[5]; - int f6 = f.h[6]; - int f7 = f.h[7]; - int f8 = f.h[8]; - int f9 = f.h[9]; - int h0 = -f0; - int h1 = -f1; - int h2 = -f2; - int h3 = -f3; - int h4 = -f4; - int h5 = -f5; - int h6 = -f6; - int h7 = -f7; - int h8 = -f8; - int h9 = -f9; + final int f0 = f.h[0]; + final int f1 = f.h[1]; + final int f2 = f.h[2]; + final int f3 = f.h[3]; + final int f4 = f.h[4]; + final int f5 = f.h[5]; + final int f6 = f.h[6]; + final int f7 = f.h[7]; + final int f8 = f.h[8]; + final int f9 = f.h[9]; + final int h0 = -f0; + final int h1 = -f1; + final int h2 = -f2; + final int h3 = -f3; + final int h4 = -f4; + final int h5 = -f5; + final int h6 = -f6; + final int h7 = -f7; + final int h8 = -f8; + final int h9 = -f9; h.h[0] = h0; h.h[1] = h1; h.h[2] = h2; @@ -3121,42 +3121,42 @@ class CryptoOps { a.asMin32("scMulSub"); b.asMin32("scMulSub"); c.asMin32("scMulSub"); - BigInt a0 = _b2097151 & _load3(a, 0); - BigInt a1 = _b2097151 & (_load4(a, 2) >> 5); - BigInt a2 = _b2097151 & (_load3(a, 5) >> 2); - BigInt a3 = _b2097151 & (_load4(a, 7) >> 7); - BigInt a4 = _b2097151 & (_load4(a, 10) >> 4); - BigInt a5 = _b2097151 & (_load3(a, 13) >> 1); - BigInt a6 = _b2097151 & (_load4(a, 15) >> 6); - BigInt a7 = _b2097151 & (_load3(a, 18) >> 3); - BigInt a8 = _b2097151 & _load3(a, 21); - BigInt a9 = _b2097151 & (_load4(a, 23) >> 5); - BigInt a10 = _b2097151 & (_load3(a, 26) >> 2); - BigInt a11 = (_load4(a, 28) >> 7); - BigInt b0 = _b2097151 & _load3(b, 0); - BigInt b1 = _b2097151 & (_load4(b, 2) >> 5); - BigInt b2 = _b2097151 & (_load3(b, 5) >> 2); - BigInt b3 = _b2097151 & (_load4(b, 7) >> 7); - BigInt b4 = _b2097151 & (_load4(b, 10) >> 4); - BigInt b5 = _b2097151 & (_load3(b, 13) >> 1); - BigInt b6 = _b2097151 & (_load4(b, 15) >> 6); - BigInt b7 = _b2097151 & (_load3(b, 18) >> 3); - BigInt b8 = _b2097151 & _load3(b, 21); - BigInt b9 = _b2097151 & (_load4(b, 23) >> 5); - BigInt b10 = _b2097151 & (_load3(b, 26) >> 2); - BigInt b11 = (_load4(b, 28) >> 7); - BigInt c0 = _b2097151 & _load3(c, 0); - BigInt c1 = _b2097151 & (_load4(c, 2) >> 5); - BigInt c2 = _b2097151 & (_load3(c, 5) >> 2); - BigInt c3 = _b2097151 & (_load4(c, 7) >> 7); - BigInt c4 = _b2097151 & (_load4(c, 10) >> 4); - BigInt c5 = _b2097151 & (_load3(c, 13) >> 1); - BigInt c6 = _b2097151 & (_load4(c, 15) >> 6); - BigInt c7 = _b2097151 & (_load3(c, 18) >> 3); - BigInt c8 = _b2097151 & _load3(c, 21); - BigInt c9 = _b2097151 & (_load4(c, 23) >> 5); - BigInt c10 = _b2097151 & (_load3(c, 26) >> 2); - BigInt c11 = (_load4(c, 28) >> 7); + final BigInt a0 = _b2097151 & _load3(a, 0); + final BigInt a1 = _b2097151 & (_load4(a, 2) >> 5); + final BigInt a2 = _b2097151 & (_load3(a, 5) >> 2); + final BigInt a3 = _b2097151 & (_load4(a, 7) >> 7); + final BigInt a4 = _b2097151 & (_load4(a, 10) >> 4); + final BigInt a5 = _b2097151 & (_load3(a, 13) >> 1); + final BigInt a6 = _b2097151 & (_load4(a, 15) >> 6); + final BigInt a7 = _b2097151 & (_load3(a, 18) >> 3); + final BigInt a8 = _b2097151 & _load3(a, 21); + final BigInt a9 = _b2097151 & (_load4(a, 23) >> 5); + final BigInt a10 = _b2097151 & (_load3(a, 26) >> 2); + final BigInt a11 = (_load4(a, 28) >> 7); + final BigInt b0 = _b2097151 & _load3(b, 0); + final BigInt b1 = _b2097151 & (_load4(b, 2) >> 5); + final BigInt b2 = _b2097151 & (_load3(b, 5) >> 2); + final BigInt b3 = _b2097151 & (_load4(b, 7) >> 7); + final BigInt b4 = _b2097151 & (_load4(b, 10) >> 4); + final BigInt b5 = _b2097151 & (_load3(b, 13) >> 1); + final BigInt b6 = _b2097151 & (_load4(b, 15) >> 6); + final BigInt b7 = _b2097151 & (_load3(b, 18) >> 3); + final BigInt b8 = _b2097151 & _load3(b, 21); + final BigInt b9 = _b2097151 & (_load4(b, 23) >> 5); + final BigInt b10 = _b2097151 & (_load3(b, 26) >> 2); + final BigInt b11 = (_load4(b, 28) >> 7); + final BigInt c0 = _b2097151 & _load3(c, 0); + final BigInt c1 = _b2097151 & (_load4(c, 2) >> 5); + final BigInt c2 = _b2097151 & (_load3(c, 5) >> 2); + final BigInt c3 = _b2097151 & (_load4(c, 7) >> 7); + final BigInt c4 = _b2097151 & (_load4(c, 10) >> 4); + final BigInt c5 = _b2097151 & (_load3(c, 13) >> 1); + final BigInt c6 = _b2097151 & (_load4(c, 15) >> 6); + final BigInt c7 = _b2097151 & (_load3(c, 18) >> 3); + final BigInt c8 = _b2097151 & _load3(c, 21); + final BigInt c9 = _b2097151 & (_load4(c, 23) >> 5); + final BigInt c10 = _b2097151 & (_load3(c, 26) >> 2); + final BigInt c11 = (_load4(c, 28) >> 7); BigInt s0; BigInt s1; BigInt s2; @@ -3635,7 +3635,7 @@ class CryptoOps { carry10 = s10 >> 21; s11 += carry10; s10 -= carry10 << 21; - List sBig = List.filled(32, BigInt.zero); + final List sBig = List.filled(32, BigInt.zero); sBig[0] = s0 >> 0; sBig[1] = s0 >> 8; sBig[2] = (s0 >> 16) | (s1 << 5); @@ -3677,30 +3677,30 @@ class CryptoOps { s.asMin32("scSub"); a.asMin32("scSub"); b.asMin32("scSub"); - BigInt a0 = _b2097151 & _load3(a, 0); - BigInt a1 = _b2097151 & (_load4(a, 2) >> 5); - BigInt a2 = _b2097151 & (_load3(a, 5) >> 2); - BigInt a3 = _b2097151 & (_load4(a, 7) >> 7); - BigInt a4 = _b2097151 & (_load4(a, 10) >> 4); - BigInt a5 = _b2097151 & (_load3(a, 13) >> 1); - BigInt a6 = _b2097151 & (_load4(a, 15) >> 6); - BigInt a7 = _b2097151 & (_load3(a, 18) >> 3); - BigInt a8 = _b2097151 & _load3(a, 21); - BigInt a9 = _b2097151 & (_load4(a, 23) >> 5); - BigInt a10 = _b2097151 & (_load3(a, 26) >> 2); - BigInt a11 = (_load4(a, 28) >> 7); - BigInt b0 = _b2097151 & _load3(b, 0); - BigInt b1 = _b2097151 & (_load4(b, 2) >> 5); - BigInt b2 = _b2097151 & (_load3(b, 5) >> 2); - BigInt b3 = _b2097151 & (_load4(b, 7) >> 7); - BigInt b4 = _b2097151 & (_load4(b, 10) >> 4); - BigInt b5 = _b2097151 & (_load3(b, 13) >> 1); - BigInt b6 = _b2097151 & (_load4(b, 15) >> 6); - BigInt b7 = _b2097151 & (_load3(b, 18) >> 3); - BigInt b8 = _b2097151 & _load3(b, 21); - BigInt b9 = _b2097151 & (_load4(b, 23) >> 5); - BigInt b10 = _b2097151 & (_load3(b, 26) >> 2); - BigInt b11 = (_load4(b, 28) >> 7); + final BigInt a0 = _b2097151 & _load3(a, 0); + final BigInt a1 = _b2097151 & (_load4(a, 2) >> 5); + final BigInt a2 = _b2097151 & (_load3(a, 5) >> 2); + final BigInt a3 = _b2097151 & (_load4(a, 7) >> 7); + final BigInt a4 = _b2097151 & (_load4(a, 10) >> 4); + final BigInt a5 = _b2097151 & (_load3(a, 13) >> 1); + final BigInt a6 = _b2097151 & (_load4(a, 15) >> 6); + final BigInt a7 = _b2097151 & (_load3(a, 18) >> 3); + final BigInt a8 = _b2097151 & _load3(a, 21); + final BigInt a9 = _b2097151 & (_load4(a, 23) >> 5); + final BigInt a10 = _b2097151 & (_load3(a, 26) >> 2); + final BigInt a11 = (_load4(a, 28) >> 7); + final BigInt b0 = _b2097151 & _load3(b, 0); + final BigInt b1 = _b2097151 & (_load4(b, 2) >> 5); + final BigInt b2 = _b2097151 & (_load3(b, 5) >> 2); + final BigInt b3 = _b2097151 & (_load4(b, 7) >> 7); + final BigInt b4 = _b2097151 & (_load4(b, 10) >> 4); + final BigInt b5 = _b2097151 & (_load3(b, 13) >> 1); + final BigInt b6 = _b2097151 & (_load4(b, 15) >> 6); + final BigInt b7 = _b2097151 & (_load3(b, 18) >> 3); + final BigInt b8 = _b2097151 & _load3(b, 21); + final BigInt b9 = _b2097151 & (_load4(b, 23) >> 5); + final BigInt b10 = _b2097151 & (_load3(b, 26) >> 2); + final BigInt b11 = (_load4(b, 28) >> 7); BigInt s0 = a0 - b0; BigInt s1 = a1 - b1; BigInt s2 = a2 - b2; @@ -3850,7 +3850,7 @@ class CryptoOps { carry10 = s10 >> 21; s11 += carry10; s10 -= carry10 << 21; - List sBig = List.filled(32, BigInt.zero); + final List sBig = List.filled(32, BigInt.zero); sBig[0] = s0 >> 0; sBig[1] = s0 >> 8; sBig[2] = (s0 >> 16) | (s1 << 5); @@ -3912,7 +3912,7 @@ class CryptoOps { } static void geP2Dbl(GroupElementP1P1 r, GroupElementP2 p) { - FieldElement t0 = FieldElement(); + final FieldElement t0 = FieldElement(); feSq(r.x, p.x); feSq(r.z, p.y); feSq2(r.t, p.z); @@ -3925,7 +3925,7 @@ class CryptoOps { } static void geMul8(GroupElementP1P1 r, GroupElementP2 t) { - GroupElementP2 u = GroupElementP2(); + final GroupElementP2 u = GroupElementP2(); geP2Dbl(r, t); geP1P1ToP2(u, r); geP2Dbl(r, u); @@ -3944,30 +3944,30 @@ class CryptoOps { s.asMin32("scAdd"); a.asMin32("scAdd"); b.asMin32("scAdd"); - BigInt a0 = _b2097151 & _load3(a, 0); - BigInt a1 = _b2097151 & (_load4(a, 2) >> 5); - BigInt a2 = _b2097151 & (_load3(a, 5) >> 2); - BigInt a3 = _b2097151 & (_load4(a, 7) >> 7); - BigInt a4 = _b2097151 & (_load4(a, 10) >> 4); - BigInt a5 = _b2097151 & (_load3(a, 13) >> 1); - BigInt a6 = _b2097151 & (_load4(a, 15) >> 6); - BigInt a7 = _b2097151 & (_load3(a, 18) >> 3); - BigInt a8 = _b2097151 & _load3(a, 21); - BigInt a9 = _b2097151 & (_load4(a, 23) >> 5); - BigInt a10 = _b2097151 & (_load3(a, 26) >> 2); - BigInt a11 = (_load4(a, 28) >> 7); - BigInt b0 = _b2097151 & _load3(b, 0); - BigInt b1 = _b2097151 & (_load4(b, 2) >> 5); - BigInt b2 = _b2097151 & (_load3(b, 5) >> 2); - BigInt b3 = _b2097151 & (_load4(b, 7) >> 7); - BigInt b4 = _b2097151 & (_load4(b, 10) >> 4); - BigInt b5 = _b2097151 & (_load3(b, 13) >> 1); - BigInt b6 = _b2097151 & (_load4(b, 15) >> 6); - BigInt b7 = _b2097151 & (_load3(b, 18) >> 3); - BigInt b8 = _b2097151 & _load3(b, 21); - BigInt b9 = _b2097151 & (_load4(b, 23) >> 5); - BigInt b10 = _b2097151 & (_load3(b, 26) >> 2); - BigInt b11 = (_load4(b, 28) >> 7); + final BigInt a0 = _b2097151 & _load3(a, 0); + final BigInt a1 = _b2097151 & (_load4(a, 2) >> 5); + final BigInt a2 = _b2097151 & (_load3(a, 5) >> 2); + final BigInt a3 = _b2097151 & (_load4(a, 7) >> 7); + final BigInt a4 = _b2097151 & (_load4(a, 10) >> 4); + final BigInt a5 = _b2097151 & (_load3(a, 13) >> 1); + final BigInt a6 = _b2097151 & (_load4(a, 15) >> 6); + final BigInt a7 = _b2097151 & (_load3(a, 18) >> 3); + final BigInt a8 = _b2097151 & _load3(a, 21); + final BigInt a9 = _b2097151 & (_load4(a, 23) >> 5); + final BigInt a10 = _b2097151 & (_load3(a, 26) >> 2); + final BigInt a11 = (_load4(a, 28) >> 7); + final BigInt b0 = _b2097151 & _load3(b, 0); + final BigInt b1 = _b2097151 & (_load4(b, 2) >> 5); + final BigInt b2 = _b2097151 & (_load3(b, 5) >> 2); + final BigInt b3 = _b2097151 & (_load4(b, 7) >> 7); + final BigInt b4 = _b2097151 & (_load4(b, 10) >> 4); + final BigInt b5 = _b2097151 & (_load3(b, 13) >> 1); + final BigInt b6 = _b2097151 & (_load4(b, 15) >> 6); + final BigInt b7 = _b2097151 & (_load3(b, 18) >> 3); + final BigInt b8 = _b2097151 & _load3(b, 21); + final BigInt b9 = _b2097151 & (_load4(b, 23) >> 5); + final BigInt b10 = _b2097151 & (_load3(b, 26) >> 2); + final BigInt b11 = (_load4(b, 28) >> 7); BigInt s0 = a0 + b0; BigInt s1 = a1 + b1; BigInt s2 = a2 + b2; @@ -4117,7 +4117,7 @@ class CryptoOps { carry10 = s10 >> 21; s11 += carry10; s10 -= carry10 << 21; - List sBig = List.filled(32, BigInt.zero); + final List sBig = List.filled(32, BigInt.zero); sBig[0] = s0 >> 0; sBig[1] = s0 >> 8; sBig[2] = (s0 >> 16) | (s1 << 5); @@ -4306,7 +4306,7 @@ class CryptoOps { carry10 = s10 >> 21; s11 += carry10; s10 -= carry10 << 21; - List sBig = List.filled(32, BigInt.zero); + final List sBig = List.filled(32, BigInt.zero); sBig[0] = s0 >> 0; sBig[1] = s0 >> 8; sBig[2] = (s0 >> 16) | (s1 << 5); @@ -4370,10 +4370,10 @@ class CryptoOps { static int geFromBytesVartime_(GroupElementP3 h, List s) { s.asMin32("geFromBytesVartime"); - FieldElement u = FieldElement(); - FieldElement v = FieldElement(); - FieldElement vxx = FieldElement(); - FieldElement check = FieldElement(); + final FieldElement u = FieldElement(); + final FieldElement v = FieldElement(); + final FieldElement vxx = FieldElement(); + final FieldElement check = FieldElement(); /* From fe_frombytes.c */ @@ -4492,7 +4492,7 @@ class CryptoOps { GroupElementP3 A, List b, List bI) { a.asMin32("geDoubleScalarMultPrecompVartime"); b.asMin32("geDoubleScalarMultPrecompVartime"); - List aI = GroupElementCached.dsmp; + final List aI = GroupElementCached.dsmp; geDsmPrecomp(aI, A); geDoubleScalarMultPrecompVartime2(r, a, aI, b, bI); } @@ -4501,11 +4501,11 @@ class CryptoOps { List aI, List b, List bI) { a.asMin32("geDoubleScalarMultPrecompVartime2"); b.asMin32("geDoubleScalarMultPrecompVartime2"); - List aslide = List.filled(256, 0); - List bslide = List.filled(256, 0); + final List aslide = List.filled(256, 0); + final List bslide = List.filled(256, 0); - GroupElementP1P1 t = GroupElementP1P1(); - GroupElementP3 u = GroupElementP3(); + final GroupElementP1P1 t = GroupElementP1P1(); + final GroupElementP3 u = GroupElementP3(); int i; slide(aslide, a); @@ -4550,9 +4550,9 @@ class CryptoOps { a.asMin32("geDoubleScalarMultPrecompVartime2P3"); final List aslide = List.filled(256, 0); final List bslide = List.filled(256, 0); - GroupElementP1P1 t = GroupElementP1P1(); - GroupElementP3 u = GroupElementP3(); - GroupElementP2 r = GroupElementP2(); + final GroupElementP1P1 t = GroupElementP1P1(); + final GroupElementP3 u = GroupElementP3(); + final GroupElementP2 r = GroupElementP2(); int i = 0; slide(aslide, a); @@ -4602,8 +4602,8 @@ class CryptoOps { final List bslide = List.filled(256, 0); final List cslide = List.filled(256, 0); - GroupElementP1P1 t = GroupElementP1P1(); - GroupElementP3 u = GroupElementP3(); + final GroupElementP1P1 t = GroupElementP1P1(); + final GroupElementP3 u = GroupElementP3(); int i; slide(aslide, a); @@ -4663,8 +4663,8 @@ class CryptoOps { final List aslide = List.filled(256, 0); final List bslide = List.filled(256, 0); final List cslide = List.filled(256, 0); - GroupElementP1P1 t = GroupElementP1P1(); - GroupElementP3 u = GroupElementP3(); + final GroupElementP1P1 t = GroupElementP1P1(); + final GroupElementP3 u = GroupElementP3(); int i; slide(aslide, a); diff --git a/lib/crypto/crypto/cdsa/curve/curve.dart b/lib/crypto/crypto/cdsa/curve/curve.dart index 2ad219b..378ff39 100644 --- a/lib/crypto/crypto/cdsa/curve/curve.dart +++ b/lib/crypto/crypto/cdsa/curve/curve.dart @@ -24,7 +24,7 @@ class CurveFp extends Curve { /// Check if a given point (x, y) lies on the curve bool containsPoint(BigInt x, BigInt y) { - BigInt leftSide = (y * y - ((x * x + a) * x + b)) % p; + final BigInt leftSide = (y * y - ((x * x + a) * x + b)) % p; return leftSide == BigInt.zero; } @@ -79,7 +79,8 @@ class CurveED extends Curve { /// Check if a given point (x, y) lies on the curve bool containsPoint(BigInt x, BigInt y) { - BigInt leftSide = (a * x * x + y * y - BigInt.one - d * x * x * y * y) % p; + final BigInt leftSide = + (a * x * x + y * y - BigInt.one - d * x * x * y * y) % p; return leftSide == BigInt.zero; } diff --git a/lib/crypto/crypto/cdsa/ecdsa/private_key.dart b/lib/crypto/crypto/cdsa/ecdsa/private_key.dart index d6fe50a..a257027 100644 --- a/lib/crypto/crypto/cdsa/ecdsa/private_key.dart +++ b/lib/crypto/crypto/cdsa/ecdsa/private_key.dart @@ -1,5 +1,5 @@ import 'dart:typed_data'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.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'; @@ -39,10 +39,10 @@ class ECDSAPrivateKey { /// An ECDSA signature. /// ECDSASignature sign(BigInt hash, BigInt randomK) { - BigInt n = publicKey.generator.order!; - BigInt k = randomK % n; - BigInt ks = k + n; - BigInt kt = ks + n; + final BigInt n = publicKey.generator.order!; + final BigInt k = randomK % n; + final BigInt ks = k + n; + final BigInt kt = ks + n; BigInt r; if (ks.bitLength == n.bitLength) { @@ -55,7 +55,7 @@ class ECDSAPrivateKey { throw const MessageException("unlucky random number r"); } - BigInt s = + final BigInt s = (BigintUtils.inverseMod(k, n) * (hash + (secretMultiplier * r) % n)) % n; diff --git a/lib/crypto/crypto/cdsa/ecdsa/public_key.dart b/lib/crypto/crypto/cdsa/ecdsa/public_key.dart index 736c5a4..7775c64 100644 --- a/lib/crypto/crypto/cdsa/ecdsa/public_key.dart +++ b/lib/crypto/crypto/cdsa/ecdsa/public_key.dart @@ -2,7 +2,7 @@ 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'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Represents an ECDSA (Elliptic Curve Digital Signature Algorithm) public key. class ECDSAPublicKey { diff --git a/lib/crypto/crypto/cdsa/ecdsa/signature.dart b/lib/crypto/crypto/cdsa/ecdsa/signature.dart index f85504c..36c2de2 100644 --- a/lib/crypto/crypto/cdsa/ecdsa/signature.dart +++ b/lib/crypto/crypto/cdsa/ecdsa/signature.dart @@ -1,7 +1,7 @@ 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/exception/exceptions.dart'; import 'package:blockchain_utils/utils/utils.dart'; /// Represents an ECDSA (Elliptic Curve Digital Signature Algorithm) signature diff --git a/lib/crypto/crypto/cdsa/eddsa/keys/privatekey.dart b/lib/crypto/crypto/cdsa/eddsa/keys/privatekey.dart index 0e77be5..4e4f7be 100644 --- a/lib/crypto/crypto/cdsa/eddsa/keys/privatekey.dart +++ b/lib/crypto/crypto/cdsa/eddsa/keys/privatekey.dart @@ -6,7 +6,7 @@ import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curves.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/eddsa/keys/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/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/utils/numbers/utils/bigint_utils.dart'; /// Represents an EdDSA private key and provides methods for key operations. diff --git a/lib/crypto/crypto/cdsa/eddsa/keys/publickey.dart b/lib/crypto/crypto/cdsa/eddsa/keys/publickey.dart index 03b5802..4b11d4e 100644 --- a/lib/crypto/crypto/cdsa/eddsa/keys/publickey.dart +++ b/lib/crypto/crypto/cdsa/eddsa/keys/publickey.dart @@ -3,7 +3,7 @@ import 'package:blockchain_utils/helper/helper.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/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/utils/utils.dart'; /// Represents an EdDSA public key in the Edwards curve format. diff --git a/lib/crypto/crypto/cdsa/point/base.dart b/lib/crypto/crypto/cdsa/point/base.dart index cc67dc6..68f91ce 100644 --- a/lib/crypto/crypto/cdsa/point/base.dart +++ b/lib/crypto/crypto/cdsa/point/base.dart @@ -3,7 +3,7 @@ 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/exception/exceptions.dart'; /// An enumeration representing different types of encoding for elliptic curve points. enum EncodeType { comprossed, hybrid, raw, uncompressed } @@ -58,7 +58,7 @@ abstract class AbstractPoint { prefix = List.from([0x06]); } - List result = List.filled(prefix.length + raw.length, 0); + final List result = List.filled(prefix.length + raw.length, 0); result.setAll(0, prefix); result.setAll(prefix.length, raw); @@ -67,7 +67,7 @@ abstract class AbstractPoint { /// Internal method to encode an elliptic curve point in compressed form. List _compressedEncode() { - List xStr = + final List xStr = BigintUtils.toBytes(x, length: BigintUtils.orderLen(curve.p)); List prefix; if (y & BigInt.one != BigInt.zero) { @@ -76,7 +76,7 @@ abstract class AbstractPoint { prefix = List.from([0x02]); } - List result = List.filled(prefix.length + xStr.length, 0); + final List result = List.filled(prefix.length + xStr.length, 0); result.setAll(0, prefix); result.setAll(prefix.length, xStr); diff --git a/lib/crypto/crypto/cdsa/point/ec_projective_point.dart b/lib/crypto/crypto/cdsa/point/ec_projective_point.dart index f66476f..54c5ddc 100644 --- a/lib/crypto/crypto/cdsa/point/ec_projective_point.dart +++ b/lib/crypto/crypto/cdsa/point/ec_projective_point.dart @@ -27,7 +27,7 @@ import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/curve/curve.dart'; import 'base.dart'; import 'point.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Represents a point in projective coordinates on an elliptic curve. class ProjectiveECCPoint extends AbstractPoint { @@ -118,15 +118,15 @@ class ProjectiveECCPoint extends AbstractPoint { BigInt newOrder = order!; // Initialize a list to store precomputed values. - List> precomputedPoints = []; + final List> precomputedPoints = []; BigInt i = BigInt.one; newOrder *= BigInt.two; // Extract projective coordinates. - BigInt xCoord = _coords[0]; - BigInt yCoord = _coords[1]; - BigInt zCoord = _coords[2]; + final BigInt xCoord = _coords[0]; + final BigInt yCoord = _coords[1]; + final BigInt zCoord = _coords[2]; // Create a projective point for doubling. ProjectiveECCPoint doubler = @@ -363,10 +363,10 @@ class ProjectiveECCPoint extends AbstractPoint { /// Doubles a point List _doubleWithZ1(BigInt x1, BigInt y1, BigInt p, BigInt a) { // Calculate x-coordinate squared - BigInt xSquared = (x1 * x1) % p; + final BigInt xSquared = (x1 * x1) % p; // Calculate y-coordinate squared - BigInt ySquared = (y1 * y1) % p; + final BigInt ySquared = (y1 * y1) % p; // Check if y-coordinate squared is zero if (ySquared == BigInt.zero) { @@ -375,22 +375,22 @@ class ProjectiveECCPoint extends AbstractPoint { } // Calculate y-coordinate squared squared - BigInt ySquaredSquared = (ySquared * ySquared) % p; + final BigInt ySquaredSquared = (ySquared * ySquared) % p; // Calculate 's' value - BigInt s = (BigInt.two * + final BigInt s = (BigInt.two * ((x1 + ySquared) * (x1 + ySquared) - xSquared - ySquaredSquared)) % p; // Calculate 'm' value - BigInt m = (BigInt.from(3) * xSquared + a) % p; + final BigInt m = (BigInt.from(3) * xSquared + a) % p; // Calculate 't' value - BigInt t = (m * m - BigInt.from(2) * s) % p; + final BigInt t = (m * m - BigInt.from(2) * s) % p; // Calculate y-coordinate of the result and update Z-coordinate - BigInt yResult = (m * (s - t) - BigInt.from(8) * ySquaredSquared) % p; - BigInt zResult = (BigInt.two * y1) % p; + final BigInt yResult = (m * (s - t) - BigInt.from(8) * ySquaredSquared) % p; + final BigInt zResult = (BigInt.two * y1) % p; return [t, yResult, zResult]; } @@ -408,10 +408,10 @@ class ProjectiveECCPoint extends AbstractPoint { } // Calculate x-coordinate squared - BigInt xSquared = (x1 * x1) % p; + final BigInt xSquared = (x1 * x1) % p; // Calculate y-coordinate squared - BigInt ySquared = (y1 * y1) % p; + final BigInt ySquared = (y1 * y1) % p; // Check if y-coordinate squared is zero if (ySquared == BigInt.zero) { @@ -420,27 +420,28 @@ class ProjectiveECCPoint extends AbstractPoint { } // Calculate y-coordinate squared squared - BigInt ySquaredSquared = (ySquared * ySquared) % p; + final BigInt ySquaredSquared = (ySquared * ySquared) % p; // Calculate z-coordinate squared - BigInt zSquared = (z1 * z1) % p; + final BigInt zSquared = (z1 * z1) % p; // Calculate 's' value - BigInt s = (BigInt.two * + final BigInt s = (BigInt.two * ((x1 + ySquared) * (x1 + ySquared) - xSquared - ySquaredSquared)) % p; // Calculate 'm' value - BigInt m = ((BigInt.from(3) * xSquared + a * zSquared * zSquared) % p); + final BigInt m = + ((BigInt.from(3) * xSquared + a * zSquared * zSquared) % p); // Calculate 't' value - BigInt t = (m * m - BigInt.from(2) * s) % p; + final BigInt t = (m * m - BigInt.from(2) * s) % p; // Calculate y-coordinate of the result - BigInt yResult = (m * (s - t) - BigInt.from(8) * ySquaredSquared) % p; + final BigInt yResult = (m * (s - t) - BigInt.from(8) * ySquaredSquared) % p; // Calculate z-coordinate of the result - BigInt zResult = ((y1 + z1) * (y1 + z1) - ySquared - zSquared) % p; + final BigInt zResult = ((y1 + z1) * (y1 + z1) - ySquared - zSquared) % p; return [t, yResult, zResult]; } @@ -448,19 +449,19 @@ class ProjectiveECCPoint extends AbstractPoint { /// Doubles a point in projective coordinates on an elliptic curve and returns the result. @override ProjectiveECCPoint doublePoint() { - BigInt x1 = _coords[0]; - BigInt y1 = _coords[1]; - BigInt z1 = _coords[2]; + final BigInt x1 = _coords[0]; + final BigInt y1 = _coords[1]; + final BigInt z1 = _coords[2]; if (y1 == BigInt.zero) { // If y-coordinate is zero, the result is the point at infinity return ProjectiveECCPoint.infinity(curve); } - BigInt primeField = curve.p; - BigInt curveA = curve.a; + final BigInt primeField = curve.p; + final BigInt curveA = curve.a; - List result = _double(x1, y1, z1, primeField, curveA); + final List result = _double(x1, y1, z1, primeField, curveA); if (result[1] == BigInt.zero || result[2] == BigInt.zero) { // If the y-coordinate or z-coordinate of the result is zero, return the point at infinity @@ -476,15 +477,15 @@ class ProjectiveECCPoint extends AbstractPoint { List _addPointsWithZ1( BigInt x1, BigInt y1, BigInt x2, BigInt y2, BigInt p) { // Calculate the difference and its square - BigInt diff = x2 - x1; - BigInt diffSquare = diff * diff; + final BigInt diff = x2 - x1; + final BigInt diffSquare = diff * diff; // Calculate intermediate values I and J - BigInt I = (diffSquare * BigInt.from(4)) % p; - BigInt J = diff * I; + final BigInt I = (diffSquare * BigInt.from(4)) % p; + final BigInt J = diff * I; // Calculate the y-coordinate difference scaled by 2 - BigInt scaledYDifference = (y2 - y1) * BigInt.from(2); + final BigInt scaledYDifference = (y2 - y1) * BigInt.from(2); if (diff == BigInt.zero && scaledYDifference == BigInt.zero) { // If the difference and scaled y-coordinate difference are both zero, @@ -493,13 +494,14 @@ class ProjectiveECCPoint extends AbstractPoint { } // Calculate intermediate value V - BigInt V = x1 * I; + final BigInt V = x1 * I; // Calculate the x, y, and z coordinates of the result - BigInt x3 = + final BigInt x3 = (scaledYDifference * scaledYDifference - J - V * BigInt.from(2)) % p; - BigInt y3 = (scaledYDifference * (V - x3) - y1 * J * BigInt.from(2)) % p; - BigInt z3 = diff * BigInt.from(2) % p; + final BigInt y3 = + (scaledYDifference * (V - x3) - y1 * J * BigInt.from(2)) % p; + final BigInt z3 = diff * BigInt.from(2) % p; return [x3, y3, z3]; } @@ -509,10 +511,10 @@ class ProjectiveECCPoint extends AbstractPoint { List _addPointsWithCommonZ( BigInt x1, BigInt y1, BigInt z1, BigInt x2, BigInt y2, BigInt p) { // Calculate intermediate values A, B, C, and D - BigInt A = (x2 - x1).modPow(BigInt.from(2), p); - BigInt B = (x1 * A) % p; - BigInt C = x2 * A; - BigInt D = (y2 - y1).modPow(BigInt.from(2), p); + final BigInt A = (x2 - x1).modPow(BigInt.from(2), p); + final BigInt B = (x1 * A) % p; + final BigInt C = x2 * A; + final BigInt D = (y2 - y1).modPow(BigInt.from(2), p); if (A == BigInt.zero && D == BigInt.zero) { // If A and D are both zero, perform a doubling operation @@ -520,9 +522,9 @@ class ProjectiveECCPoint extends AbstractPoint { } // Calculate the x, y, and z coordinates of the result - BigInt x3 = (D - B - C) % p; - BigInt y3 = ((y2 - y1) * (B - x3) - y1 * (C - B)) % p; - BigInt z3 = (z1 * (x2 - x1)) % p; + final BigInt x3 = (D - B - C) % p; + final BigInt y3 = ((y2 - y1) * (B - x3) - y1 * (C - B)) % p; + final BigInt z3 = (z1 * (x2 - x1)) % p; return [x3, y3, z3]; } @@ -532,16 +534,16 @@ class ProjectiveECCPoint extends AbstractPoint { List _addPointsWithZ2EqualOne( BigInt x1, BigInt y1, BigInt z1, BigInt x2, BigInt y2, BigInt p) { // Calculate Z1Z1, U2, and S2 - BigInt z1z1 = (z1 * z1) % p; - BigInt u2 = (x2 * z1z1) % p; - BigInt s2 = (y2 * z1 * z1z1) % p; + final BigInt z1z1 = (z1 * z1) % p; + final BigInt u2 = (x2 * z1z1) % p; + final BigInt s2 = (y2 * z1 * z1z1) % p; // Calculate H, HH, I, and J - BigInt h = (u2 - x1) % p; - BigInt hh = (h * h) % p; - BigInt i = (BigInt.from(4) * hh) % p; - BigInt j = (h * i) % p; - BigInt r = (BigInt.from(2) * (s2 - y1)) % p; + final BigInt h = (u2 - x1) % p; + final BigInt hh = (h * h) % p; + final BigInt i = (BigInt.from(4) * hh) % p; + final BigInt j = (h * i) % p; + final BigInt r = (BigInt.from(2) * (s2 - y1)) % p; if (r == BigInt.zero && h == BigInt.zero) { // If r and h are both zero, perform a doubling operation @@ -549,10 +551,10 @@ class ProjectiveECCPoint extends AbstractPoint { } // Calculate the x, y, and z coordinates of the result - BigInt v = (x1 * i) % p; - BigInt x3 = (r * r - j - BigInt.from(2) * v) % p; - BigInt y3 = (r * (v - x3) - BigInt.from(2) * y1 * j) % p; - BigInt z3 = (((z1 + h).modPow(BigInt.from(2), p) - z1z1) - hh) % p; + final BigInt v = (x1 * i) % p; + final BigInt x3 = (r * r - j - BigInt.from(2) * v) % p; + final BigInt y3 = (r * (v - x3) - BigInt.from(2) * y1 * j) % p; + final BigInt z3 = (((z1 + h).modPow(BigInt.from(2), p) - z1z1) - hh) % p; return [x3, y3, z3]; } @@ -562,18 +564,18 @@ class ProjectiveECCPoint extends AbstractPoint { List _addPointsWithZNotEqual(BigInt x1, BigInt y1, BigInt z1, BigInt x2, BigInt y2, BigInt z2, BigInt p) { // Calculate Z1Z1, Z2Z2, U1, U2, S1, S2 - BigInt z1z1 = (z1 * z1) % p; - BigInt z2z2 = (z2 * z2) % p; - BigInt u1 = (x1 * z2z2) % p; - BigInt u2 = (x2 * z1z1) % p; - BigInt s1 = (y1 * z2 * z2z2) % p; - BigInt s2 = (y2 * z1 * z1z1) % p; + final BigInt z1z1 = (z1 * z1) % p; + final BigInt z2z2 = (z2 * z2) % p; + final BigInt u1 = (x1 * z2z2) % p; + final BigInt u2 = (x2 * z1z1) % p; + final BigInt s1 = (y1 * z2 * z2z2) % p; + final BigInt s2 = (y2 * z1 * z1z1) % p; // Calculate H, I, J, and r - BigInt h = (u2 - u1) % p; - BigInt i = (BigInt.from(4) * h * h) % p; - BigInt j = (h * i) % p; - BigInt r = (BigInt.from(2) * (s2 - s1)) % p; + final BigInt h = (u2 - u1) % p; + final BigInt i = (BigInt.from(4) * h * h) % p; + final BigInt j = (h * i) % p; + final BigInt r = (BigInt.from(2) * (s2 - s1)) % p; if (h == BigInt.zero && r == BigInt.zero) { // If h and r are both zero, perform a doubling operation @@ -581,10 +583,11 @@ class ProjectiveECCPoint extends AbstractPoint { } // Calculate the x, y, and z coordinates of the result - BigInt v = (u1 * i) % p; - BigInt x3 = (r * r - j - BigInt.from(2) * v) % p; - BigInt y3 = (r * (v - x3) - BigInt.from(2) * s1 * j) % p; - BigInt z3 = (((z1 + z2).modPow(BigInt.from(2), p) - z1z1 - z2z2) * h) % p; + final BigInt v = (u1 * i) % p; + final BigInt x3 = (r * r - j - BigInt.from(2) * v) % p; + final BigInt y3 = (r * (v - x3) - BigInt.from(2) * s1 * j) % p; + final BigInt z3 = + (((z1 + z2).modPow(BigInt.from(2), p) - z1z1 - z2z2) * h) % p; return [x3, y3, z3]; } @@ -637,24 +640,24 @@ class ProjectiveECCPoint extends AbstractPoint { other as ProjectiveECCPoint; // Get the prime field value - BigInt primeField = curve.p; + final BigInt primeField = curve.p; // Extract coordinates of the first point - BigInt x1 = _coords[0]; - BigInt y1 = _coords[1]; - BigInt z1 = _coords[2]; + final BigInt x1 = _coords[0]; + final BigInt y1 = _coords[1]; + final BigInt z1 = _coords[2]; // Extract coordinates of the second point - BigInt x2 = other._coords[0]; - BigInt y2 = other._coords[1]; - BigInt z2 = other._coords[2]; + final BigInt x2 = other._coords[0]; + final BigInt y2 = other._coords[1]; + final BigInt z2 = other._coords[2]; // Perform point addition - List result = _addPoints(x1, y1, z1, x2, y2, z2, primeField); + final List result = _addPoints(x1, y1, z1, x2, y2, z2, primeField); - BigInt x3 = result[0]; - BigInt y3 = result[1]; - BigInt z3 = result[2]; + final BigInt x3 = result[0]; + final BigInt y3 = result[1]; + final BigInt z3 = result[2]; if (y3 == BigInt.zero || z3 == BigInt.zero) { return ProjectiveECCPoint.infinity(curve); @@ -681,23 +684,23 @@ class ProjectiveECCPoint extends AbstractPoint { resultY = BigInt.zero, resultZ = BigInt.one, primeField = curve.p; - List> precompute = List.from(_precompute); + final List> precompute = List.from(_precompute); for (int i = 0; i < precompute.length; i++) { - BigInt x2 = precompute[i][0]; - BigInt y2 = precompute[i][1]; + final BigInt x2 = precompute[i][0]; + final BigInt y2 = precompute[i][1]; if (scalar.isOdd) { if (scalar.isOdd && scalar.isEven) { scalar = (scalar + BigInt.one) ~/ BigInt.two; - List addResult = _addPoints( + final List addResult = _addPoints( resultX, resultY, resultZ, x2, -y2, BigInt.one, primeField); resultX = addResult[0]; resultY = addResult[1]; resultZ = addResult[2]; } else { scalar = (scalar - BigInt.one) ~/ BigInt.two; - List addResult = _addPoints( + final List addResult = _addPoints( resultX, resultY, resultZ, x2, y2, BigInt.one, primeField); resultX = addResult[0]; resultY = addResult[1]; @@ -748,19 +751,19 @@ class ProjectiveECCPoint extends AbstractPoint { scale(); // Initialize point coordinates - BigInt x2 = _coords[0]; - BigInt y2 = _coords[1]; + final BigInt x2 = _coords[0]; + final BigInt y2 = _coords[1]; BigInt x3 = BigInt.zero; BigInt y3 = BigInt.zero; BigInt z3 = BigInt.one; - BigInt primeField = curve.p; - BigInt curveA = curve.a; + final BigInt primeField = curve.p; + final BigInt curveA = curve.a; // Since adding points when at least one of them is scaled // is quicker, reverse the NAF order - List nafList = BigintUtils.computeNAF(scalar); + final List nafList = BigintUtils.computeNAF(scalar); for (int i = nafList.length - 1; i >= 0; i--) { final List double = _double(x3, y3, z3, primeField, curveA); x3 = double[0]; @@ -826,28 +829,28 @@ class ProjectiveECCPoint extends AbstractPoint { BigInt x3 = BigInt.zero; BigInt y3 = BigInt.zero; BigInt z3 = BigInt.one; - BigInt p = curve.p; - BigInt a = curve.a; + final BigInt p = curve.p; + final BigInt a = curve.a; scale(); - BigInt x1 = _coords[0]; - BigInt y1 = _coords[1]; - BigInt z1 = _coords[2]; + final BigInt x1 = _coords[0]; + final BigInt y1 = _coords[1]; + final BigInt z1 = _coords[2]; other.scale(); - BigInt x2 = other._coords[0]; - BigInt y2 = other._coords[1]; - BigInt z2 = other._coords[2]; + final BigInt x2 = other._coords[0]; + final BigInt y2 = other._coords[1]; + final BigInt z2 = other._coords[2]; // with NAF we have 3 options: no add, subtract, add // so with 2 points, we have 9 combinations: // 0, -A, +A, -B, -A-B, +A-B, +B, -A+B, +A+B // so we need 4 combined points: - List mAmB = _addPoints(x1, -y1, z1, x2, -y2, z2, p); + final List mAmB = _addPoints(x1, -y1, z1, x2, -y2, z2, p); - List pAmB = _addPoints(x1, y1, z1, x2, -y2, z2, p); + final List pAmB = _addPoints(x1, y1, z1, x2, -y2, z2, p); - List mApB = [pAmB[0], -pAmB[1], pAmB[2]]; - List pApB = [mAmB[0], -mAmB[1], mAmB[2]]; + final List mApB = [pAmB[0], -pAmB[1], pAmB[2]]; + final List pApB = [mAmB[0], -mAmB[1], mAmB[2]]; if (pApB[1] == BigInt.zero || pApB[2] == BigInt.zero) { return (this * selfMul + other * otherMul) as ProjectiveECCPoint; @@ -865,8 +868,8 @@ class ProjectiveECCPoint extends AbstractPoint { } for (int i = 0; i < selfNaf.length; i++) { - BigInt A = selfNaf[i]; - BigInt B = otherNaf[i]; + final BigInt A = selfNaf[i]; + final BigInt B = otherNaf[i]; List result = _double(x3, y3, z3, p, a); diff --git a/lib/crypto/crypto/cdsa/point/edwards.dart b/lib/crypto/crypto/cdsa/point/edwards.dart index 446effe..dbf3a5b 100644 --- a/lib/crypto/crypto/cdsa/point/edwards.dart +++ b/lib/crypto/crypto/cdsa/point/edwards.dart @@ -26,7 +26,7 @@ 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'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// A class representing a point on an Edwards curve, extending the abstract [AbstractPoint] class. class EDPoint extends AbstractPoint { @@ -148,10 +148,10 @@ class EDPoint extends AbstractPoint { BigInt newOrder = order!; /// Initialize a list to store computed values. - List> compute = []; + final List> compute = []; BigInt i = BigInt.one; newOrder *= BigInt.from(2); - List coordsList = getCoords(); + final List coordsList = getCoords(); /// Create a temporary point for doubling. EDPoint doubler = EDPoint._(curve, getCoords(), order: newOrder); @@ -188,8 +188,8 @@ class EDPoint extends AbstractPoint { /// - The x-coordinate of the point. @override BigInt get x { - BigInt x1 = _coords[0]; - BigInt z1 = _coords[2]; + final BigInt x1 = _coords[0]; + final BigInt z1 = _coords[2]; /// If the z-coordinate is 1, return x1 directly. if (z1 == BigInt.one) { @@ -197,10 +197,10 @@ class EDPoint extends AbstractPoint { } /// Retrieve the prime value (p) of the curve. - BigInt p = curve.p; + final BigInt p = curve.p; /// Compute the inverse of z1 modulo p. - BigInt zInv = BigintUtils.inverseMod(z1, p); + final BigInt zInv = BigintUtils.inverseMod(z1, p); /// Calculate and return the x-coordinate modulo p. return (x1 * zInv) % p; @@ -217,8 +217,8 @@ class EDPoint extends AbstractPoint { BigInt get y { /// Create a new list to avoid modifying the original coordinates. - BigInt y1 = _coords[1]; - BigInt z1 = _coords[2]; + final BigInt y1 = _coords[1]; + final BigInt z1 = _coords[2]; /// If the z-coordinate is 1, return y1 directly. if (z1 == BigInt.one) { @@ -226,10 +226,10 @@ class EDPoint extends AbstractPoint { } /// Retrieve the prime value (p) of the curve. - BigInt p = curve.p; + final BigInt p = curve.p; /// Compute the inverse of z1 modulo p. - BigInt zInv = BigintUtils.inverseMod(z1, p); + final BigInt zInv = BigintUtils.inverseMod(z1, p); /// Calculate and return the y-coordinate modulo p. return (y1 * zInv) % p; @@ -243,23 +243,23 @@ class EDPoint extends AbstractPoint { /// Returns: /// - A reference to the scaled Edwards curve point. EDPoint scale() { - BigInt z1 = _coords[2]; + final BigInt z1 = _coords[2]; /// If the z-coordinate is already 1, the point is already in projective form, and no scaling is required. if (z1 == BigInt.one) { return this; } - BigInt x1 = _coords[0]; - BigInt y1 = _coords[1]; + final BigInt x1 = _coords[0]; + final BigInt y1 = _coords[1]; /// Retrieve the prime value (p) of the curve. - BigInt p = curve.p; + final BigInt p = curve.p; /// Compute the inverse of z1 modulo p. - BigInt zInv = BigintUtils.inverseMod(z1, p); - BigInt x = (x1 * zInv) % p; - BigInt y = (y1 * zInv) % p; - BigInt t = (x * y) % p; + final BigInt zInv = BigintUtils.inverseMod(z1, p); + final BigInt x = (x1 * zInv) % p; + final BigInt y = (y1 * zInv) % p; + final BigInt t = (x * y) % p; /// Update the coordinates to their scaled values and set z-coordinate to 1 (projective form). _coords[0] = x; @@ -284,18 +284,18 @@ class EDPoint extends AbstractPoint { if (other is EDPoint) { /// Create new coordinate lists to avoid modifying the original coordinates. - List otherCoords = other.getCoords(); + final List otherCoords = other.getCoords(); /// Extract coordinates of the current point. - BigInt x1 = _coords[0]; - BigInt y1 = _coords[1]; - BigInt z1 = _coords[2]; - BigInt t1 = _coords[3]; + final BigInt x1 = _coords[0]; + final BigInt y1 = _coords[1]; + final BigInt z1 = _coords[2]; + final BigInt t1 = _coords[3]; /// Extract coordinates of the other point. - BigInt x2 = otherCoords[0]; - BigInt y2 = otherCoords[1]; - BigInt z2 = otherCoords[2]; + final BigInt x2 = otherCoords[0]; + final BigInt y2 = otherCoords[1]; + final BigInt z2 = otherCoords[2]; /// If the other point is infinity, check specific conditions. if (other.isInfinity) { @@ -308,13 +308,13 @@ class EDPoint extends AbstractPoint { } /// Retrieve the prime value (p) of the curve. - BigInt p = curve.p; + final BigInt p = curve.p; /// Calculate the normalized coordinates of both points. - BigInt xn1 = (x1 * z2) % p; - BigInt xn2 = (x2 * z1) % p; - BigInt yn1 = (y1 * z2) % p; - BigInt yn2 = (y2 * z1) % p; + final BigInt xn1 = (x1 * z2) % p; + final BigInt xn2 = (x2 * z1) % p; + final BigInt yn1 = (y1 * z2) % p; + final BigInt yn2 = (y2 * z1) % p; /// Check if the normalized coordinates are equal. return xn1 == xn2 && yn1 == yn2; @@ -354,14 +354,14 @@ class EDPoint extends AbstractPoint { BigInt a, ) { /// Compute intermediate values for addition. - BigInt A = (x1 * x2) % p; - BigInt b = (y1 * y2) % p; - BigInt c = (z1 * t2) % p; - BigInt d = (t1 * z2) % p; - BigInt e = d + c; - BigInt f = (((x1 - y1) * (x2 + y2)) + b - A) % p; - BigInt g = b + (a * A); - BigInt h = d - c; + final BigInt A = (x1 * x2) % p; + final BigInt b = (y1 * y2) % p; + final BigInt c = (z1 * t2) % p; + final BigInt d = (t1 * z2) % p; + final BigInt e = d + c; + final BigInt f = (((x1 - y1) * (x2 + y2)) + b - A) % p; + final BigInt g = b + (a * A); + final BigInt h = d - c; /// Check if the value of 'h' is zero; if so, perform a doubling operation instead. if (h == BigInt.zero) { @@ -369,10 +369,10 @@ class EDPoint extends AbstractPoint { } /// Calculate the coordinates of the resulting point after addition. - BigInt x3 = (e * f) % p; - BigInt y3 = (g * h) % p; - BigInt t3 = (e * h) % p; - BigInt z3 = (f * g) % p; + final BigInt x3 = (e * f) % p; + final BigInt y3 = (g * h) % p; + final BigInt t3 = (e * h) % p; + final BigInt z3 = (f * g) % p; /// Return the resulting coordinates as a list. return [x3, y3, z3, t3]; @@ -400,20 +400,20 @@ class EDPoint extends AbstractPoint { if (other.isInfinity) { return this; } - BigInt p = curve.p; - BigInt a = curve.a; + final BigInt p = curve.p; + final BigInt a = curve.a; - BigInt x1 = _coords[0]; - BigInt y1 = _coords[1]; - BigInt z1 = _coords[2]; - BigInt t1 = _coords[3]; + final BigInt x1 = _coords[0]; + final BigInt y1 = _coords[1]; + final BigInt z1 = _coords[2]; + final BigInt t1 = _coords[3]; - BigInt x2 = other._coords[0]; - BigInt y2 = other._coords[1]; - BigInt z2 = other._coords[2]; - BigInt t2 = other._coords[3]; + final BigInt x2 = other._coords[0]; + final BigInt y2 = other._coords[1]; + final BigInt z2 = other._coords[2]; + final BigInt t2 = other._coords[3]; - List result = _add(x1, y1, z1, t1, x2, y2, z2, t2, p, a); + final List result = _add(x1, y1, z1, t1, x2, y2, z2, t2, p, a); if (result[0] == BigInt.zero || result[3] == BigInt.zero) { return EDPoint.infinity(curve: curve); } @@ -434,10 +434,10 @@ class EDPoint extends AbstractPoint { /// Returns: /// - A new Edwards curve point representing the negation of this point. EDPoint operator -() { - BigInt x1 = _coords[0]; - BigInt y1 = _coords[1]; - BigInt t1 = _coords[3]; - BigInt p = curve.p; + final BigInt x1 = _coords[0]; + final BigInt y1 = _coords[1]; + final BigInt t1 = _coords[3]; + final BigInt p = curve.p; return EDPoint._(curve, [x1, (p - y1) % p, _coords[2], (p - t1) % p], order: order); @@ -445,18 +445,18 @@ class EDPoint extends AbstractPoint { List _double( BigInt x1, BigInt y1, BigInt z1, BigInt t1, BigInt p, BigInt a) { - BigInt A = (x1 * x1) % p; - BigInt B = (y1 * y1) % p; - BigInt C = (z1 * z1 * BigInt.two) % p; - BigInt D = (a * A) % p; - BigInt E = (((x1 + y1) * (x1 + y1)) - A - B) % p; - BigInt G = D + B; - BigInt F = G - C; - BigInt H = D - B; - BigInt x3 = (E * F) % p; - BigInt y3 = (G * H) % p; - BigInt t3 = (E * H) % p; - BigInt z3 = (F * G) % p; + final BigInt A = (x1 * x1) % p; + final BigInt B = (y1 * y1) % p; + final BigInt C = (z1 * z1 * BigInt.two) % p; + final BigInt D = (a * A) % p; + final BigInt E = (((x1 + y1) * (x1 + y1)) - A - B) % p; + final BigInt G = D + B; + final BigInt F = G - C; + final BigInt H = D - B; + final BigInt x3 = (E * F) % p; + final BigInt y3 = (G * H) % p; + final BigInt t3 = (E * H) % p; + final BigInt z3 = (F * G) % p; return [x3, y3, z3, t3]; } @@ -478,10 +478,10 @@ class EDPoint extends AbstractPoint { /// - A list of BigInt values representing the new coordinates [x3, y3, z3, t3] after doubling the point. @override EDPoint doublePoint() { - BigInt x1 = _coords[0]; - BigInt t1 = _coords[3]; - BigInt p = curve.p; - BigInt a = curve.a; + final BigInt x1 = _coords[0]; + final BigInt t1 = _coords[3]; + final BigInt p = curve.p; + final BigInt a = curve.a; if (x1 == BigInt.zero || t1 == BigInt.zero) { return EDPoint.infinity(curve: curve); @@ -555,10 +555,10 @@ class EDPoint extends AbstractPoint { /// - A new Edwards curve point resulting from the multiplication. @override EDPoint operator *(BigInt other) { - BigInt x2 = _coords[0]; - BigInt t2 = _coords[3]; - BigInt y2 = _coords[1]; - BigInt z2 = _coords[2]; + final BigInt x2 = _coords[0]; + final BigInt t2 = _coords[3]; + final BigInt y2 = _coords[1]; + final BigInt z2 = _coords[2]; if (other == BigInt.zero) { return EDPoint.infinity(curve: curve); } @@ -578,22 +578,23 @@ class EDPoint extends AbstractPoint { BigInt t3 = BigInt.one; final nf = BigintUtils.computeNAF(other).reversed.toList(); - for (BigInt i in nf) { - List resultCoords = _double(x3, y3, z3, t3, curve.p, curve.a); + for (final i in nf) { + final List resultCoords = + _double(x3, y3, z3, t3, curve.p, curve.a); x3 = resultCoords[0]; y3 = resultCoords[1]; z3 = resultCoords[2]; t3 = resultCoords[3]; if (i < BigInt.zero) { - List doubleCoords = + final List doubleCoords = _add(x3, y3, z3, t3, -x2, y2, z2, -t2, curve.p, curve.a); x3 = doubleCoords[0]; y3 = doubleCoords[1]; z3 = doubleCoords[2]; t3 = doubleCoords[3]; } else if (i > BigInt.zero) { - List doubleCoords = + final List doubleCoords = _add(x3, y3, z3, t3, x2, y2, z2, t2, curve.p, curve.a); x3 = doubleCoords[0]; y3 = doubleCoords[1]; diff --git a/lib/crypto/crypto/cdsa/point/point.dart b/lib/crypto/crypto/cdsa/point/point.dart index e72df88..989a75e 100644 --- a/lib/crypto/crypto/cdsa/point/point.dart +++ b/lib/crypto/crypto/cdsa/point/point.dart @@ -25,7 +25,7 @@ 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'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'base.dart'; @@ -109,11 +109,11 @@ class AffinePointt extends AbstractPoint { } } - BigInt p = curve.p; - BigInt l = (other.y - y) * BigintUtils.inverseMod(other.x - x, p) % p; + final BigInt p = curve.p; + final BigInt l = (other.y - y) * BigintUtils.inverseMod(other.x - x, p) % p; - BigInt x3 = (l * l - x - other.x) % p; - BigInt y3 = (l * (x - x3) - y) % p; + final BigInt x3 = (l * l - x - other.x) % p; + final BigInt y3 = (l * (x - x3) - y) % p; return AffinePointt(curve, x3, y3, order: null); } @@ -153,7 +153,7 @@ class AffinePointt extends AbstractPoint { } e *= BigInt.from(3); - AffinePointt negativeSelf = AffinePointt(curve, x, -y, order: order); + final AffinePointt negativeSelf = AffinePointt(curve, x, -y, order: order); BigInt i = leftmostBit(e) ~/ BigInt.from(2); AffinePointt result = this; @@ -187,15 +187,15 @@ class AffinePointt extends AbstractPoint { return AffinePointt(curve, BigInt.zero, BigInt.zero); } - BigInt p = curve.p; - BigInt a = curve.a; + final BigInt p = curve.p; + final BigInt a = curve.a; - BigInt l = (BigInt.from(3) * x * x + a) * + final BigInt l = (BigInt.from(3) * x * x + a) * BigintUtils.inverseMod(BigInt.from(2) * y, p) % p; - BigInt x3 = (l * l - BigInt.from(2) * x) % p; - BigInt y3 = (l * (x - x3) - y) % p; + final BigInt x3 = (l * l - BigInt.from(2) * x) % p; + final BigInt y3 = (l * (x - x3) - y) % p; return AffinePointt(curve, x3, y3, order: null); } diff --git a/lib/crypto/crypto/cdsa/point/ristretto_point.dart b/lib/crypto/crypto/cdsa/point/ristretto_point.dart index 14a4285..eb44343 100644 --- a/lib/crypto/crypto/cdsa/point/ristretto_point.dart +++ b/lib/crypto/crypto/cdsa/point/ristretto_point.dart @@ -1,6 +1,6 @@ import 'dart:typed_data'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.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'; @@ -28,21 +28,14 @@ class RistrettoPoint extends EDPoint { /// - super.generator: A flag indicating if the point is a generator (default is false). /// - super.order: The order of the point in the group (optional). RistrettoPoint._( - {required CurveED curve, - required BigInt x, - required BigInt y, - required BigInt z, - required BigInt t, + {required super.curve, + required super.x, + required super.y, + required super.z, + required super.t, bool generator = false, - BigInt? order}) - : super( - curve: curve, - t: t, - x: x, - y: y, - z: z, - generator: false, - order: order); + super.order}) + : super(generator: false); /// Create a RistrettoPoint from an EdwardsPoint. /// @@ -86,7 +79,7 @@ class RistrettoPoint extends EDPoint { /// - ArgumentException: If the input bytes result in an invalid RistrettoPoint. /// - Exception: If the RistrettoPoint creation fails any validity checks. factory RistrettoPoint.fromBytes(List bytes, {CurveED? curveEdTw}) { - List hex = bytes; + final List hex = bytes; final c = curveEdTw ?? Curves.curveEd25519; final a = c.a; final d = c.d; @@ -198,7 +191,7 @@ class RistrettoPoint extends EDPoint { /// as a RistrettoPoint. /// /// Parameters: - /// - hash: A List representing the uniform byte value to be converted. + /// - hash: A `List` representing the uniform byte value to be converted. /// /// Returns: /// - RistrettoPoint: A RistrettoPoint instance created from the uniform byte input. @@ -232,7 +225,7 @@ class RistrettoPoint extends EDPoint { /// - encodeType: The encoding type for the output byte array (default is compressed). /// /// Returns: - /// - List: A byte array representing the RistrettoPoint in Edwards encoding. + /// - `List`: A byte array representing the RistrettoPoint in Edwards encoding. List toEdwardBytes([EncodeType encodeType = EncodeType.comprossed]) { return super.toBytes(encodeType); } @@ -293,7 +286,7 @@ class RistrettoPoint extends EDPoint { /// for serialization and other data storage or transmission purposes. /// /// Returns: - /// - List: A byte array representing the RistrettoPoint. + /// - `List`: A byte array representing the RistrettoPoint. /// /// Details: /// - The method calculates intermediate values and applies encoding-specific @@ -306,8 +299,8 @@ class RistrettoPoint extends EDPoint { final pointCoords = getCoords(); BigInt x = pointCoords[0]; BigInt y = pointCoords[1]; - BigInt z = pointCoords[2]; - BigInt t = pointCoords[3]; + final BigInt z = pointCoords[2]; + final BigInt t = pointCoords[3]; final u1 = ristretto_tools.positiveMod( ristretto_tools.positiveMod(z + y, primeP) * diff --git a/lib/crypto/crypto/cdsa/rfc6979/rfc6979.dart b/lib/crypto/crypto/cdsa/rfc6979/rfc6979.dart index 80fd311..7d34c42 100644 --- a/lib/crypto/crypto/cdsa/rfc6979/rfc6979.dart +++ b/lib/crypto/crypto/cdsa/rfc6979/rfc6979.dart @@ -60,12 +60,12 @@ class RFC6979 { static BigInt generateK( BigInt order, BigInt secexp, HashFunc hashFunc, List data, {int retryGn = 0, List? extraEntropy}) { - int qlen = order.bitLength; + final int qlen = order.bitLength; final hx = hashFunc(); - int holen = hx.getDigestLength; - int rolen = (qlen + 7) ~/ 8; + final int holen = hx.getDigestLength; + final int rolen = (qlen + 7) ~/ 8; - List> bx = [ + final List> bx = [ BigintUtils.toBytes(secexp, length: BigintUtils.orderLen(order)), BigintUtils.bitsToOctetsWithOrderPadding(data, order), extraEntropy ?? List.empty(), @@ -80,7 +80,7 @@ class RFC6979 { hmac.update(List.from([...v, 0x00])); - for (var i in bx) { + for (final i in bx) { hmac.update(i); } k = hmac.digest(); @@ -94,7 +94,7 @@ class RFC6979 { hmac = HMAC(hashFunc, k); hmac.update(List.from([...v, 0x01])); - for (var i in bx) { + for (final i in bx) { hmac.update(i); } k = hmac.digest(); @@ -114,7 +114,7 @@ class RFC6979 { } // Step H3 - BigInt secret = BigintUtils.bitsToBigIntWithLengthLimit(t, qlen); + final BigInt secret = BigintUtils.bitsToBigIntWithLengthLimit(t, qlen); if (secret >= BigInt.one && secret < order) { if (retryGn <= 0) { diff --git a/lib/crypto/crypto/cdsa/utils/ed25519_utils.dart b/lib/crypto/crypto/cdsa/utils/ed25519_utils.dart index 22f5e6b..977afb9 100644 --- a/lib/crypto/crypto/cdsa/utils/ed25519_utils.dart +++ b/lib/crypto/crypto/cdsa/utils/ed25519_utils.dart @@ -17,7 +17,7 @@ class Ed25519Utils { /// - scalar: A byte array representing the scalar value. /// /// Returns: - /// - List: A reduced byte array representing the scalar modulo the Ed25519 curve order. + /// - `List`: A reduced byte array representing the scalar modulo the Ed25519 curve order. /// /// Details: /// - The method converts the byte array to a BigInt, performs the reduction @@ -40,9 +40,9 @@ class Ed25519Utils { "The provided scalar exceeds the allowed range."); } - /// Adds two scalar values represented as Lists and returns the result as a List. + /// Adds two scalar values represented as `List` and returns the result as a `List`. /// - /// This method adds two scalar values, `scalar1` and `scalar2`, and stores the result in the `out` List. + /// This method adds two scalar values, `scalar1` and `scalar2`, and stores the result in the `out` `List`. /// The addition is performed according to Ristretto255 scalar operations. /// /// Parameters: @@ -50,16 +50,16 @@ class Ed25519Utils { /// - scalar2: The second scalar value to add. /// /// Returns: - /// A List representing the result of the addition. + /// A `List` representing the result of the addition. static List add(List scalar1, List scalar2) { final out = List.filled(32, 0); CryptoOps.scMulAdd(out, CryptoOpsConst.infinity, scalar1, scalar2); return BytesUtils.toBytes(out); } - /// Subtracts one scalar value from another and returns the result as a List. + /// Subtracts one scalar value from another and returns the result as a `List`. /// - /// This method subtracts `scalar2` from `scalar1` and stores the result in the `out` List. + /// This method subtracts `scalar2` from `scalar1` and stores the result in the `out` `List`. /// The subtraction is performed according to Ristretto255 scalar operations. /// /// Parameters: @@ -67,23 +67,23 @@ class Ed25519Utils { /// - scalar2: The scalar value to subtract. /// /// Returns: - /// A List representing the result of the subtraction. + /// A `List` representing the result of the subtraction. static List sub(List scalar1, List scalar2) { final out = List.filled(32, 0); CryptoOps.scMulAdd(out, CryptoOpsConst.scMinusOne, scalar2, scalar1); return BytesUtils.toBytes(out); } - /// Negates a scalar value and returns the result as a List. + /// Negates a scalar value and returns the result as a `List`. /// - /// This method negates the given `scalar` and stores the result in the `out` List. + /// This method negates the given `scalar` and stores the result in the `out` `List`. /// The negation is performed according to Ristretto255 scalar operations. /// /// Parameters: /// - scalar: The scalar value to negate. /// /// Returns: - /// A List representing the negated scalar. + /// A `List` representing the negated scalar. static List neg(List scalar) { final out = List.filled(32, 0); CryptoOps.scMulAdd( @@ -91,9 +91,9 @@ class Ed25519Utils { return BytesUtils.toBytes(out); } - /// Multiplies two scalar values represented as Lists and returns the result as a List. + /// Multiplies two scalar values represented as `List` and returns the result as a `List`. /// - /// This method multiplies two scalar values, `scalar1` and `scalar2`, and stores the result in the `out` List. + /// This method multiplies two scalar values, `scalar1` and `scalar2`, and stores the result in the `out` `List`. /// The multiplication is performed according to Ristretto255 scalar operations. /// /// Parameters: @@ -101,7 +101,7 @@ class Ed25519Utils { /// - scalar2: The second scalar value to multiply. /// /// Returns: - /// A List representing the result of the multiplication. + /// A `List` representing the result of the multiplication. static List mul(List scalar1, List scalar2) { final out = List.filled(32, 0); CryptoOps.scMulAdd(out, scalar1, scalar2, CryptoOpsConst.zero); @@ -113,7 +113,7 @@ class Ed25519Utils { } static bool isValidPoint(List bytes) { - GroupElementP3 p = GroupElementP3(); + final GroupElementP3 p = GroupElementP3(); return CryptoOps.geFromBytesVartime_(p, bytes) == 0; } diff --git a/lib/crypto/crypto/cdsa/utils/exp.dart b/lib/crypto/crypto/cdsa/utils/exp.dart index f2352b5..77ce94c 100644 --- a/lib/crypto/crypto/cdsa/utils/exp.dart +++ b/lib/crypto/crypto/cdsa/utils/exp.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// An exception class for errors related to square root calculations. /// @@ -6,8 +6,7 @@ import 'package:blockchain_utils/exception/exception.dart'; /// of a BigInt value within the defined constraints. /// class SquareRootError extends BlockchainUtilsException { - const SquareRootError(String message, {Map? details}) - : super(message, details: details); + const SquareRootError(super.message, {super.details}); } /// An exception class for errors related to Jacobi symbol calculations. @@ -16,6 +15,5 @@ class SquareRootError extends BlockchainUtilsException { /// for a pair of BigInt values within the defined constraints. /// class JacobiError extends BlockchainUtilsException { - const JacobiError(String message, {Map? details}) - : super(message, details: details); + const JacobiError(super.message, {super.details}); } diff --git a/lib/crypto/crypto/cdsa/utils/utils.dart b/lib/crypto/crypto/cdsa/utils/utils.dart index 1930f91..b963b63 100644 --- a/lib/crypto/crypto/cdsa/utils/utils.dart +++ b/lib/crypto/crypto/cdsa/utils/utils.dart @@ -1,5 +1,5 @@ import 'package:blockchain_utils/crypto/crypto/cdsa/utils/exp.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; class ECDSAUtils { /// Computes the modular exponentiation of a polynomial represented by [base] @@ -97,7 +97,8 @@ class ECDSAUtils { /// Multiply two polynomials represented by lists 'm1' and 'm2', reducing modulo 'polymod' and prime 'p'. static List polynomialMultiplyMod( List m1, List m2, List polymod, BigInt p) { - List prod = List.filled(m1.length + m2.length - 1, BigInt.zero); + final List prod = + List.filled(m1.length + m2.length - 1, BigInt.zero); // Add together all the cross-terms: for (int i = 0; i < m1.length; i++) { diff --git a/lib/crypto/crypto/chacha/chacha.dart b/lib/crypto/crypto/chacha/chacha.dart index bdcdd69..14d3922 100644 --- a/lib/crypto/crypto/chacha/chacha.dart +++ b/lib/crypto/crypto/chacha/chacha.dart @@ -1,5 +1,5 @@ import 'package:blockchain_utils/utils/utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; class ChaCha20 { static void _quarterround(List output, int a, int b, int c, int d) { @@ -107,7 +107,7 @@ class ChaCha20 { /// be used with or without an inplace counter, depending on the value of `nonceInplaceCounterLength`. /// /// Parameters: - /// - `key`: The 256-bit (32-byte) encryption key as a List. + /// - `key`: The 256-bit (32-byte) encryption key as a `List`. /// - `nonce`: The nonce data, which must be either 8, 12, or 16 bytes in length depending on the /// value of `nonceInplaceCounterLength`. /// - `src`: The source data to be encrypted or decrypted. @@ -120,7 +120,7 @@ class ChaCha20 { /// the nonce length is invalid. /// /// Returns: - /// - The `dst` List containing the result of the XOR operation. + /// - The `dst` `List` containing the result of the XOR operation. /// /// Note: This function securely zeros temporary data to protect sensitive information. static List streamXOR( @@ -183,14 +183,14 @@ class ChaCha20 { /// in the encrypted output. It also provides the option to incorporate a nonce inplace counter. /// /// Parameters: - /// - `key`: The encryption key as a List. - /// - `nonce`: A unique nonce as a List. - /// - `dst`: The destination List where the generated stream will be XORed. + /// - `key`: The encryption key as a `List`. + /// - `nonce`: A unique nonce as a `List`. + /// - `dst`: The destination `List` where the generated stream will be XORed. /// - `nonceInplaceCounterLength`: An optional parameter to specify the length of the nonce inplace counter /// (default is 0, meaning no nonce inplace counter). /// /// Returns: - /// - The `dst` List containing the encrypted data. + /// - The `dst` `List` containing the encrypted data. /// /// Note: This function securely zeros the `dst` data before writing the generated stream and should /// be used for generating secure random data. diff --git a/lib/crypto/crypto/chacha20poly1305/chacha20poly1305.dart b/lib/crypto/crypto/chacha20poly1305/chacha20poly1305.dart index 15d4e7c..0ba36a2 100644 --- a/lib/crypto/crypto/chacha20poly1305/chacha20poly1305.dart +++ b/lib/crypto/crypto/chacha20poly1305/chacha20poly1305.dart @@ -2,7 +2,7 @@ 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/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; const int _nonceLength = 12; const int _tagLength = 16; @@ -36,7 +36,7 @@ class ChaCha20Poly1305 implements AEAD { /// to hold the result. /// /// Parameters: - /// - `nonce`: The nonce as a List, with a maximum length of 16 bytes. + /// - `nonce`: The nonce as a `List`, with a maximum length of 16 bytes. /// - `plaintext`: The plaintext data to be encrypted. /// - `associatedData`: Optional associated data that is not encrypted but included in the tag calculation. /// - `dst`: An optional destination `List` where the encrypted data and tag will be written. @@ -66,7 +66,7 @@ class ChaCha20Poly1305 implements AEAD { final resultLength = plaintext.length + tagLength; - List result = dst ?? List.filled(resultLength, 0); + final List result = dst ?? List.filled(resultLength, 0); if (result.length != resultLength) { throw const ArgumentException( "ChaCha20Poly1305: incorrect destination length"); @@ -92,7 +92,7 @@ class ChaCha20Poly1305 implements AEAD { /// incorrect tag or nonce), `null` is returned. /// /// Parameters: - /// - `nonce`: The nonce as a List, with a maximum length of 16 bytes. + /// - `nonce`: The nonce as a `List`, with a maximum length of 16 bytes. /// - `sealed`: The sealed data, including the ciphertext and authentication tag. /// - `associatedData`: Optional associated data that is not encrypted but used in the tag verification. /// - `dst`: An optional destination `List` where the decrypted plaintext will be written. @@ -134,7 +134,7 @@ class ChaCha20Poly1305 implements AEAD { final resultLength = sealed.length - tagLength; - List result = dst ?? List.filled(resultLength, 0); + final List result = dst ?? List.filled(resultLength, 0); if (result.length != resultLength) { throw const ArgumentException( "ChaCha20Poly1305: incorrect destination length"); diff --git a/lib/crypto/crypto/crc16/crc16.dart b/lib/crypto/crypto/crc16/crc16.dart index 4e909e1..646cfeb 100644 --- a/lib/crypto/crypto/crc16/crc16.dart +++ b/lib/crypto/crypto/crc16/crc16.dart @@ -5,10 +5,10 @@ class Crc16 { static List quickIntDigest(List data) { int reg = 0; - List message = List.filled(data.length + 2, 0); + final List message = List.filled(data.length + 2, 0); message.setAll(0, data); - for (int byte in message) { + for (final byte in message) { int mask = 0x80; while (mask > 0) { reg <<= 1; diff --git a/lib/crypto/crypto/crc32/crc32.dart b/lib/crypto/crypto/crc32/crc32.dart index 7ee806e..e105b4c 100644 --- a/lib/crypto/crypto/crc32/crc32.dart +++ b/lib/crypto/crypto/crc32/crc32.dart @@ -286,7 +286,7 @@ class Crc32 { /// The returned integer is a digest of the input data, providing a compact representation of its content. static int quickIntDigest(List data) { int crc = mask32; - for (int byte in data) { + for (final byte in data) { crc = (crc >> 8) ^ _crcTable[(crc ^ byte) & mask8]; } return crc ^ mask32; diff --git a/lib/crypto/crypto/crypto.dart b/lib/crypto/crypto/crypto.dart index 2ef0e85..6581347 100644 --- a/lib/crypto/crypto/crypto.dart +++ b/lib/crypto/crypto/crypto.dart @@ -1,6 +1,6 @@ /// The 'crypto' library provides a collection of cryptographic algorithms and utilities /// for various cryptographic operations and security functions. -library crypto; +library; /// Export statement for AEAD (Authenticated Encryption with Associated Data) components. export 'aead/aead.dart'; diff --git a/lib/crypto/crypto/ctr/ctr.dart b/lib/crypto/crypto/ctr/ctr.dart index bda1296..37a0519 100644 --- a/lib/crypto/crypto/ctr/ctr.dart +++ b/lib/crypto/crypto/ctr/ctr.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/blockcipher/blockcipher.dart'; import 'package:blockchain_utils/utils/utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Counter (CTR) mode for block ciphers. /// diff --git a/lib/crypto/crypto/ecb/ecb.dart b/lib/crypto/crypto/ecb/ecb.dart index 4e97f10..25fd7da 100644 --- a/lib/crypto/crypto/ecb/ecb.dart +++ b/lib/crypto/crypto/ecb/ecb.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/aes/aes.dart'; import 'package:blockchain_utils/crypto/crypto/aes/padding.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Electronic Codebook (ECB) mode for AES encryption and decryption. /// @@ -11,7 +11,7 @@ class ECB extends AES { /// /// Parameters: /// - `key`: The encryption key used for ECB mode. - ECB(List key) : super(key); + ECB(super.key); /// Encrypts a single data block using the Electronic Codebook (ECB) mode. /// @@ -57,7 +57,7 @@ class ECB extends AES { for (var i = 0; i < numBlocks; i++) { final start = i * blockSize; final end = (i + 1) * blockSize; - List block = List.from(input.sublist(start, end)); + final List block = List.from(input.sublist(start, end)); final enc = super.encryptBlock(block); out.setRange(start, end, enc); } diff --git a/lib/crypto/crypto/gcm/gcm.dart b/lib/crypto/crypto/gcm/gcm.dart index 6180397..48af13f 100644 --- a/lib/crypto/crypto/gcm/gcm.dart +++ b/lib/crypto/crypto/gcm/gcm.dart @@ -2,7 +2,7 @@ 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/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'dart:math' as math; @@ -65,7 +65,7 @@ class GCM implements AEAD { final blockSize = _cipher.blockSize; final resultLength = plaintext.length + tagLength; - List result = dst ?? List.filled(resultLength, 0); + final List result = dst ?? List.filled(resultLength, 0); if (result.length != resultLength) { throw const ArgumentException("GCM: incorrect destination length"); } @@ -143,7 +143,7 @@ class GCM implements AEAD { } final resultLength = sealed.length - tagLength; - List result = dst ?? List.filled(resultLength, 0); + final List result = dst ?? List.filled(resultLength, 0); if (result.length != resultLength) { throw const ArgumentException("GCM: incorrect destination length"); } diff --git a/lib/crypto/crypto/hash/black2b/black2b.dart b/lib/crypto/crypto/hash/black2b/black2b.dart index 8113f52..bc3280f 100644 --- a/lib/crypto/crypto/hash/black2b/black2b.dart +++ b/lib/crypto/crypto/hash/black2b/black2b.dart @@ -144,7 +144,7 @@ class BLAKE2b implements SerializableHash { /// - [config]: Optional configuration for BLAKE2b (e.g., key, salt, personalization). /// /// Returns: - /// A List containing the computed BLAKE2b hash digest. + /// A `List` containing the computed BLAKE2b hash digest. static List hash(List data, [int digestLength = 64, Blake2bConfig? config]) { final h = BLAKE2b(digestLength: digestLength, config: config); @@ -298,7 +298,7 @@ class BLAKE2b implements SerializableHash { "blake2b: can't update because hash was finished."); } - int left = _blockSize - _bufferLength; + final int left = _blockSize - _bufferLength; int dataPos = 0; int dataLength = length ?? data.length; @@ -338,17 +338,17 @@ class BLAKE2b implements SerializableHash { return this; } - /// Finalizes the BLAKE2b hash, producing the hash digest and writing it to the given output [List]. + /// Finalizes the BLAKE2b hash, producing the hash digest and writing it to the given output [`List`]. /// /// If the hash was already finished, this method simply returns the digest. Otherwise, it /// completes the hash computation, marking it as finished. /// /// Parameters: - /// - `out`: The [List] where the hash digest will be written. + /// - `out`: The [`List`] where the hash digest will be written. /// /// Returns: /// - The BLAKE2b instance with the finalized hash state. The hash digest is also written - /// to the provided [List] 'out'. + /// to the provided [`List`] 'out'. @override BLAKE2b finish(List out) { if (!_finished) { @@ -370,7 +370,7 @@ class BLAKE2b implements SerializableHash { _finished = true; } - List tmp = List.filled(64, 0); + final List tmp = List.filled(64, 0); for (int i = 0; i < 16; i++) { writeUint32LE(_state[i], tmp, i * 4); } @@ -378,16 +378,16 @@ class BLAKE2b implements SerializableHash { return this; } - /// Returns the final hash digest as a [List]. + /// Returns the final hash digest as a [`List`]. /// /// This method calls the 'finish' method to complete the hash computation if it has - /// not already been finished, and then returns the hash digest as a [List]. + /// not already been finished, and then returns the hash digest as a [`List`]. /// /// Returns: - /// - The final hash digest as a [List]. + /// - The final hash digest as a [`List`]. @override List digest() { - List out = List.filled(getDigestLength, 0); + final List out = List.filled(getDigestLength, 0); finish(out); return out; } @@ -581,7 +581,7 @@ class BLAKE2b implements SerializableHash { void _processBlock(int length) { _incrementCounter(length); - var v = _vtmp; + final v = _vtmp; v.setAll(0, _state); v.setAll(16, _iv); v[12 * 2 + 0] ^= _ctr[0]; @@ -592,7 +592,7 @@ class BLAKE2b implements SerializableHash { v[14 * 2 + 1] ^= _flag[1]; v[15 * 2 + 0] ^= _flag[2]; v[15 * 2 + 1] ^= _flag[3]; - var m = _mtmp; + final m = _mtmp; for (var i = 0; i < 32; i++) { m[i] = readUint32LE(_buffer, i * 4); } @@ -720,7 +720,7 @@ class BLAKE2b implements SerializableHash { void _incrementCounter(int length) { for (int i = 0; i < 3; i++) { - int a = _ctr[i] + length; + final int a = _ctr[i] + length; _ctr[i] = a & mask32; if (_ctr[i] == a) { return; diff --git a/lib/crypto/crypto/hash/hash.dart b/lib/crypto/crypto/hash/hash.dart index 6113d26..7e860aa 100644 --- a/lib/crypto/crypto/hash/hash.dart +++ b/lib/crypto/crypto/hash/hash.dart @@ -13,12 +13,12 @@ /// - Keccack: SHA-3, SHA-3/224, SHA-3/256, SHA-3/384, SHA-3/512, SHAKE128-256 /// - Ridemp: RIPEMD-320, RIPEMD-256, RIPEMD-160, RIPEMD-128 /// -.... -library hash; +library; import 'package:blockchain_utils/utils/utils.dart'; import 'dart:math' as math; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// Export statement for the 'sha224' part, providing the SHA-224 hash algorithm. part 'sha224/sha224.dart'; diff --git a/lib/crypto/crypto/hash/keccack/sha3.dart b/lib/crypto/crypto/hash/keccack/sha3.dart index da60103..7e14465 100644 --- a/lib/crypto/crypto/hash/keccack/sha3.dart +++ b/lib/crypto/crypto/hash/keccack/sha3.dart @@ -49,7 +49,7 @@ class _Keccack { /// If the hash has already been finished using the `finish` method, calling this method will result in an error. /// /// Parameters: - /// - [data]: The List containing the data to be hashed. + /// - [data]: The `List` containing the data to be hashed. /// /// Returns this [Hash] object for method chaining. _Keccack update(List data) { @@ -139,7 +139,7 @@ class Keccack extends _Keccack { /// If the hash has already been finished using the `finish` method, calling this method will result in an error. /// /// Parameters: - /// - [data]: The List containing the data to be hashed. + /// - [data]: The `List` containing the data to be hashed. /// /// Returns this [Hash] object for method chaining. @override @@ -148,14 +148,14 @@ class Keccack extends _Keccack { return this; } - /// Finalizes the hash computation and stores the hash state in the provided List [out]. + /// Finalizes the hash computation and stores the hash state in the provided `List` [out]. /// /// This function completes the hash computation, finalizes the state, and stores the resulting - /// hash in the provided [out] List. If the hash has already been finished, this method + /// hash in the provided [out] `List`. If the hash has already been finished, this method /// will return the existing state without re-computing. /// /// Parameters: - /// - [out]: The List in which the hash digest is stored. + /// - [out]: The `List` in which the hash digest is stored. /// /// Returns the current instance of the hash algorithm. Keccack finish(List dst) { @@ -170,13 +170,13 @@ class Keccack extends _Keccack { return this; } - /// Generates the final hash digest by assembling and returning the hash state in a List. + /// Generates the final hash digest by assembling and returning the hash state in a `List`. /// /// This function produces the hash digest by combining the current hash state into a single - /// List output. It finalizes the hash if it hasn't been finished, effectively completing + /// `List` output. It finalizes the hash if it hasn't been finished, effectively completing /// the hash computation and returning the result. /// - /// Returns the List containing the computed hash digest. + /// Returns the `List` containing the computed hash digest. List digest() { final out = List.filled(digestLength, 0); finish(out); @@ -256,7 +256,7 @@ class SHA3 extends _Keccack implements SerializableHash { /// If the hash has already been finished using the `finish` method, calling this method will result in an error. /// /// Parameters: - /// - [data]: The List containing the data to be hashed. + /// - [data]: The `List` containing the data to be hashed. /// /// Returns this [Hash] object for method chaining. SHA3 update(List data) { @@ -264,14 +264,14 @@ class SHA3 extends _Keccack implements SerializableHash { return this; } - /// Finalizes the hash computation and stores the hash state in the provided List [out]. + /// Finalizes the hash computation and stores the hash state in the provided `List` [out]. /// /// This function completes the hash computation, finalizes the state, and stores the resulting - /// hash in the provided [out] List. If the hash has already been finished, this method + /// hash in the provided [out] `List`. If the hash has already been finished, this method /// will return the existing state without re-computing. /// /// Parameters: - /// - [out]: The List in which the hash digest is stored. + /// - [out]: The `List` in which the hash digest is stored. /// /// Returns the current instance of the hash algorithm. @override @@ -287,13 +287,13 @@ class SHA3 extends _Keccack implements SerializableHash { return this; } - /// Generates the final hash digest by assembling and returning the hash state in a List. + /// Generates the final hash digest by assembling and returning the hash state in a `List`. /// /// This function produces the hash digest by combining the current hash state into a single - /// List output. It finalizes the hash if it hasn't been finished, effectively completing + /// `List` output. It finalizes the hash if it hasn't been finished, effectively completing /// the hash computation and returning the result. /// - /// Returns the List containing the computed hash digest. + /// Returns the `List` containing the computed hash digest. @override List digest() { final out = List.filled(getDigestLength, 0); @@ -475,7 +475,7 @@ class SHAKE extends _Keccack implements SerializableHash { /// If the hash has already been finished using the `finish` method, calling this method will result in an error. /// /// Parameters: - /// - [data]: The List containing the data to be hashed. + /// - [data]: The `List` containing the data to be hashed. /// /// Returns this [Hash] object for method chaining. SHAKE update(List data) { @@ -512,13 +512,13 @@ class SHAKE extends _Keccack implements SerializableHash { zero(savedState); } - /// Generates the final hash digest by assembling and returning the hash state in a List. + /// Generates the final hash digest by assembling and returning the hash state in a `List`. /// /// This function produces the hash digest by combining the current hash state into a single - /// List output. It finalizes the hash if it hasn't been finished, effectively completing + /// `List` output. It finalizes the hash if it hasn't been finished, effectively completing /// the hash computation and returning the result. /// - /// Returns the List containing the computed hash digest. + /// Returns the `List` containing the computed hash digest. @override List digest([int outlen = 32]) { final out = List.filled(outlen, 0); @@ -526,14 +526,14 @@ class SHAKE extends _Keccack implements SerializableHash { return out; } - /// Finalizes the hash computation and stores the hash state in the provided List [out]. + /// Finalizes the hash computation and stores the hash state in the provided `List` [out]. /// /// This function completes the hash computation, finalizes the state, and stores the resulting - /// hash in the provided [out] List. If the hash has already been finished, this method + /// hash in the provided [out] `List`. If the hash has already been finished, this method /// will return the existing state without re-computing. /// /// Parameters: - /// - [out]: The List in which the hash digest is stored. + /// - [out]: The `List` in which the hash digest is stored. /// /// Returns the current instance of the hash algorithm. @override @@ -569,7 +569,7 @@ class SHAKE extends _Keccack implements SerializableHash { /// Example of usage: /// ```dart /// final shake = SHAKE128(); -/// shake.update(List.from([0x01, 0x02, 0x03])); +/// shake.update(`List`.from([0x01, 0x02, 0x03])); /// final digest = shake.digest(); /// shake.clean(); /// ``` @@ -589,7 +589,7 @@ class SHAKE128 extends SHAKE { /// Example of usage: /// ```dart /// final shake = SHAKE256(); -/// shake.update(List.from([0x01, 0x02, 0x03])); +/// shake.update(`List`.from([0x01, 0x02, 0x03])); /// final digest = shake.digest(); /// shake.clean(); /// ``` diff --git a/lib/crypto/crypto/hash/md4/md4.dart b/lib/crypto/crypto/hash/md4/md4.dart index 572f66c..7630cbd 100644 --- a/lib/crypto/crypto/hash/md4/md4.dart +++ b/lib/crypto/crypto/hash/md4/md4.dart @@ -21,7 +21,7 @@ class MD4 implements SerializableHash { /// - [data]: The input data for which the MD4 hash is computed. /// /// Returns: - /// A List representing the 128-bit MD4 hash value. + /// A `List` representing the 128-bit MD4 hash value. static List hash(List data) { /// Create an MD4 hash object. final h = MD4(); @@ -133,14 +133,14 @@ class MD4 implements SerializableHash { @override - /// Computes the MD4 hash digest and returns it as a List. + /// Computes the MD4 hash digest and returns it as a `List`. /// /// This method calculates the MD4 hash of the data processed so far and returns - /// the resulting hash digest as a List. It finalizes the hash computation + /// the resulting hash digest as a `List`. It finalizes the hash computation /// if it hasn't been finished already and then returns the digest. /// /// Returns: - /// - A List containing the MD4 hash digest. + /// - A `List` containing the MD4 hash digest. List digest() { final out = List.filled(getDigestLength, 0); finish(out); @@ -154,7 +154,7 @@ class MD4 implements SerializableHash { /// has already been finished, it won't be reprocessed. /// /// Parameters: - /// - [out]: The List buffer where the hash digest will be stored. + /// - [out]: The `List` buffer where the hash digest will be stored. /// /// Returns: /// - The MD4 hash object after finalization. @@ -180,13 +180,13 @@ class MD4 implements SerializableHash { _buffer.add(0); } - var lengthInBits = _lengthInBytes * 8; + final lengthInBits = _lengthInBytes * 8; final offset = _buffer.length; _buffer.addAll(List.filled(8, 0)); - var highBits = lengthInBits ~/ 0x100000000; // >> 32 - var lowBits = lengthInBits & mask32; + final highBits = lengthInBits ~/ 0x100000000; // >> 32 + final lowBits = lengthInBits & mask32; writeUint32LE(lowBits, _buffer, offset); writeUint32LE(highBits, _buffer, offset + 4); } @@ -259,7 +259,7 @@ class MD4 implements SerializableHash { } void _iterate() { - var pendingDataChunks = _buffer.length ~/ getBlockSize; + final pendingDataChunks = _buffer.length ~/ getBlockSize; for (var i = 0; i < pendingDataChunks; i++) { // Copy words from the pending data buffer into the current chunk buffer. for (var j = 0; j < _currentChunk.length; j++) { diff --git a/lib/crypto/crypto/hash/md5/md5.dart b/lib/crypto/crypto/hash/md5/md5.dart index 9831855..ee70ac9 100644 --- a/lib/crypto/crypto/hash/md5/md5.dart +++ b/lib/crypto/crypto/hash/md5/md5.dart @@ -8,7 +8,7 @@ part of 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; /// Example usage: /// ```dart /// final md5 = MD5(); -/// md5.update(List.from('Hello, world!'.codeUnits)); +/// md5.update(`List`.from('Hello, world!'.codeUnits)); /// final digest = md5.digest(); /// md5.clean(); // Clean up resources after use. /// ``` @@ -19,14 +19,14 @@ class MD5 implements SerializableHash { } /// Computes the MD5 hash of the provided [data] and returns the 128-bit (16-byte) - /// MD5 message digest as a [List]. + /// MD5 message digest as a [`List`]. /// /// This static method is a convenient way to compute an MD5 hash for a given /// data without creating an instance of the [MD5] class. /// /// Example usage: /// ```dart - /// final data = List.from('Hello, MD5!'.codeUnits); + /// final data = `List`.from('Hello, MD5!'.codeUnits); /// final digest = MD5.hash(data); /// ``` /// @@ -116,13 +116,13 @@ class MD5 implements SerializableHash { [6, 10, 15, 21] ]; - /// Generates the final hash digest by assembling and returning the hash state in a List. + /// Generates the final hash digest by assembling and returning the hash state in a `List`. /// /// This function produces the hash digest by combining the current hash state into a single - /// List output. It finalizes the hash if it hasn't been finished, effectively completing + /// `List` output. It finalizes the hash if it hasn't been finished, effectively completing /// the hash computation and returning the result. /// - /// Returns the List containing the computed hash digest. + /// Returns the `List` containing the computed hash digest. @override List digest() { final out = List.filled(getDigestLength, 0); @@ -130,14 +130,14 @@ class MD5 implements SerializableHash { return out; } - /// Finalizes the hash computation and stores the hash state in the provided List [out]. + /// Finalizes the hash computation and stores the hash state in the provided `List` [out]. /// /// This function completes the hash computation, finalizes the state, and stores the resulting - /// hash in the provided [out] List. If the hash has already been finished, this method + /// hash in the provided [out] `List`. If the hash has already been finished, this method /// will return the existing state without re-computing. /// /// Parameters: - /// - [out]: The List in which the hash digest is stored. + /// - [out]: The `List` in which the hash digest is stored. /// /// Returns the current instance of the hash algorithm. @override @@ -162,7 +162,7 @@ class MD5 implements SerializableHash { _buffer.add(0); } - var lengthInBits = _lengthInBytes * 8; + final lengthInBits = _lengthInBytes * 8; // Add the full length of the input data as a 64-bit value at the end of the // hash. Note: we're only writing out 64 bits, so skip ahead 8 if the @@ -175,8 +175,8 @@ class MD5 implements SerializableHash { // We're essentially doing byteData.setUint64(offset, lengthInBits, _endian) // here, but that method isn't supported on dart2js so we implement it // manually instead. - var highBits = lengthInBits ~/ 0x100000000; // >> 32 - var lowBits = lengthInBits & mask32; + final highBits = lengthInBits ~/ 0x100000000; // >> 32 + final lowBits = lengthInBits & mask32; // byteData.setUint32(offset, lowBits, Endian.little); // byteData.setUint32(offset + 4, highBits, Endian.little); writeUint32LE(lowBits, _buffer, offset); @@ -247,7 +247,7 @@ class MD5 implements SerializableHash { /// If the hash has already been finished using the `finish` method, calling this method will result in an error. /// /// Parameters: - /// - [data]: The List containing the data to be hashed. + /// - [data]: The `List` containing the data to be hashed. /// /// Returns this [Hash] object for method chaining. @override @@ -263,7 +263,7 @@ class MD5 implements SerializableHash { } void _iterate() { - var pendingDataChunks = _buffer.length ~/ getBlockSize; + final pendingDataChunks = _buffer.length ~/ getBlockSize; for (var i = 0; i < pendingDataChunks; i++) { // Copy words from the pending data buffer into the current chunk buffer. for (var j = 0; j < _currentChunk.length; j++) { diff --git a/lib/crypto/crypto/hash/ridemp/ridemp.dart b/lib/crypto/crypto/hash/ridemp/ridemp.dart index ce4861f..e2dc81e 100644 --- a/lib/crypto/crypto/hash/ridemp/ridemp.dart +++ b/lib/crypto/crypto/hash/ridemp/ridemp.dart @@ -8,12 +8,12 @@ part of 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; /// - [RIPEMD320]: Initializes an instance of the RIPEMD-320 hash. /// /// Static Method: -/// - [hash]: Computes the RIPEMD-320 hash of the provided data and returns the digest as a List. +/// - [hash]: Computes the RIPEMD-320 hash of the provided data and returns the digest as a `List`. /// It creates a new instance, updates it with the data, retrieves the digest, and then cleans up the internal state. /// /// Example: /// ```dart -/// final data = List.from([0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64]); +/// final data = `List`.from([0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64]); /// final hashDigest = RIPEMD320.hash(data); /// ``` class RIPEMD320 extends _RIPEMD { @@ -38,12 +38,12 @@ class RIPEMD320 extends _RIPEMD { /// - [RIPEMD256]: Initializes an instance of the RIPEMD-256 hash. /// /// Static Method: -/// - [hash]: Computes the RIPEMD-256 hash of the provided data and returns the digest as a List. +/// - [hash]: Computes the RIPEMD-256 hash of the provided data and returns the digest as a `List`. /// It creates a new instance, updates it with the data, retrieves the digest, and then cleans up the internal state. /// /// Example: /// ```dart -/// final data = List.from([0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64]); +/// final data = `List`.from([0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64]); /// final hashDigest = RIPEMD256.hash(data); /// ``` class RIPEMD256 extends _RIPEMD { @@ -68,12 +68,12 @@ class RIPEMD256 extends _RIPEMD { /// - [RIPEMD160]: Initializes an instance of the RIPEMD-160 hash. /// /// Static Method: -/// - [hash]: Computes the RIPEMD-160 hash of the provided data and returns the digest as a List. +/// - [hash]: Computes the RIPEMD-160 hash of the provided data and returns the digest as a `List`. /// It creates a new instance, updates it with the data, retrieves the digest, and then cleans up the internal state. /// /// Example: /// ```dart -/// final data = List.from([0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64]); +/// final data = `List`.from([0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64]); /// final hashDigest = RIPEMD160.hash(data); /// ``` class RIPEMD160 extends _RIPEMD { @@ -98,12 +98,12 @@ class RIPEMD160 extends _RIPEMD { /// - [RIPEMD128]: Initializes an instance of the RIPEMD-128 hash. /// /// Static Method: -/// - [hash]: Computes the RIPEMD-128 hash of the provided data and returns the digest as a List. +/// - [hash]: Computes the RIPEMD-128 hash of the provided data and returns the digest as a `List`. /// It creates a new instance, updates it with the data, retrieves the digest, and then cleans up the internal state. /// /// Example: /// ```dart -/// final data = List.from([0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64]); +/// final data = `List`.from([0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x2C, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64]); /// final hashDigest = RIPEMD128.hash(data); /// ``` class RIPEMD128 extends _RIPEMD { @@ -167,13 +167,13 @@ class _RIPEMD implements SerializableHash { savedState.length = 0; } - /// Generates the final hash digest by assembling and returning the hash state in a List. + /// Generates the final hash digest by assembling and returning the hash state in a `List`. /// /// This function produces the hash digest by combining the current hash state into a single - /// List output. It finalizes the hash if it hasn't been finished, effectively completing + /// `List` output. It finalizes the hash if it hasn't been finished, effectively completing /// the hash computation and returning the result. /// - /// Returns the List containing the computed hash digest. + /// Returns the `List` containing the computed hash digest. @override List digest() { final out = List.filled(getDigestLength, 0); @@ -181,14 +181,14 @@ class _RIPEMD implements SerializableHash { return out; } - /// Finalizes the hash computation and stores the hash state in the provided List [out]. + /// Finalizes the hash computation and stores the hash state in the provided `List` [out]. /// /// This function completes the hash computation, finalizes the state, and stores the resulting - /// hash in the provided [out] List. If the hash has already been finished, this method + /// hash in the provided [out] `List`. If the hash has already been finished, this method /// will return the existing state without re-computing. /// /// Parameters: - /// - [out]: The List in which the hash digest is stored. + /// - [out]: The `List` in which the hash digest is stored. /// /// Returns the current instance of the hash algorithm. @override @@ -213,7 +213,7 @@ class _RIPEMD implements SerializableHash { _buffer.add(0); } - var lengthInBits = _lengthInBytes * 8; + final lengthInBits = _lengthInBytes * 8; // Add the full length of the input data as a 64-bit value at the end of the // hash. Note: we're only writing out 64 bits, so skip ahead 8 if the @@ -224,8 +224,8 @@ class _RIPEMD implements SerializableHash { // We're essentially doing byteData.setUint64(offset, lengthInBits, _endian) // here, but that method isn't supported on dart2js so we implement it // manually instead. - var highBits = lengthInBits ~/ 0x100000000; // >> 32 - var lowBits = lengthInBits & mask32; + final highBits = lengthInBits ~/ 0x100000000; // >> 32 + final lowBits = lengthInBits & mask32; writeUint32LE(lowBits, _buffer, offset); writeUint32LE(highBits, _buffer, offset + 4); } @@ -294,7 +294,7 @@ class _RIPEMD implements SerializableHash { /// If the hash has already been finished using the `finish` method, calling this method will result in an error. /// /// Parameters: - /// - [data]: The List containing the data to be hashed. + /// - [data]: The `List` containing the data to be hashed. /// /// Returns this [Hash] object for method chaining. @override @@ -311,7 +311,7 @@ class _RIPEMD implements SerializableHash { void _iterate() { // var pendingDataBytes = _buffer.buffer.asByteData(); - var pendingDataChunks = _buffer.length ~/ getBlockSize; + final pendingDataChunks = _buffer.length ~/ getBlockSize; for (var i = 0; i < pendingDataChunks; i++) { // Copy words from the pending data buffer into the current chunk buffer. for (var j = 0; j < _currentChunk.length; j++) { @@ -369,7 +369,7 @@ class _RIPEMD implements SerializableHash { br = t; } - int t = add32(add32(_state[1], cl), dr); + final int t = add32(add32(_state[1], cl), dr); _state[1] = add32(add32(_state[2], dl), ar); _state[2] = add32(add32(_state[3], al), br); @@ -414,27 +414,27 @@ class _RIPEMD implements SerializableHash { switch (i) { case 15: - int temp = bl; + final int temp = bl; bl = br; br = temp; break; case 31: - int temp = dl; + final int temp = dl; dl = dr; dr = temp; break; case 47: - int temp = al; + final int temp = al; al = ar; ar = temp; break; case 63: - int temp = cl; + final int temp = cl; cl = cr; cr = temp; break; case 79: - int temp = el; + final int temp = el; el = er; er = temp; break; @@ -484,22 +484,22 @@ class _RIPEMD implements SerializableHash { switch (i) { case 15: - int temp = al; + final int temp = al; al = ar; ar = temp; break; case 31: - int temp = bl; + final int temp = bl; bl = br; br = temp; break; case 47: - int temp = cl; + final int temp = cl; cl = cr; cr = temp; break; case 63: - int temp = dl; + final int temp = dl; dl = dr; dr = temp; break; @@ -552,7 +552,7 @@ class _RIPEMD implements SerializableHash { br = t; } - int t = add32(add32(_state[1], cl), dr); + final int t = add32(add32(_state[1], cl), dr); _state[1] = add32(add32(_state[2], dl), er); _state[2] = add32(add32(_state[3], el), ar); _state[3] = add32(add32(_state[4], al), br); diff --git a/lib/crypto/crypto/hash/sha1/sha1.dart b/lib/crypto/crypto/hash/sha1/sha1.dart index 993a3be..1904319 100644 --- a/lib/crypto/crypto/hash/sha1/sha1.dart +++ b/lib/crypto/crypto/hash/sha1/sha1.dart @@ -10,7 +10,7 @@ part of 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; /// Example: /// ```dart /// final sha1 = SHA1(); -/// sha1.update(List.from([0x48, 0x65, 0x6C, 0x6C, 0x6F])); +/// sha1.update(`List`.from([0x48, 0x65, 0x6C, 0x6C, 0x6F])); /// final hashDigest = sha1.digest(); /// ``` class SHA1 implements SerializableHash { @@ -63,13 +63,13 @@ class SHA1 implements SerializableHash { savedState.length = 0; } - /// Generates the final hash digest by assembling and returning the hash state in a List. + /// Generates the final hash digest by assembling and returning the hash state in a `List`. /// /// This function produces the hash digest by combining the current hash state into a single - /// List output. It finalizes the hash if it hasn't been finished, effectively completing + /// `List` output. It finalizes the hash if it hasn't been finished, effectively completing /// the hash computation and returning the result. /// - /// Returns the List containing the computed hash digest. + /// Returns the `List` containing the computed hash digest. @override List digest() { final out = List.filled(getDigestLength, 0); @@ -77,14 +77,14 @@ class SHA1 implements SerializableHash { return out; } - /// Finalizes the hash computation and stores the hash state in the provided List [out]. + /// Finalizes the hash computation and stores the hash state in the provided `List` [out]. /// /// This function completes the hash computation, finalizes the state, and stores the resulting - /// hash in the provided [out] List. If the hash has already been finished, this method + /// hash in the provided [out] `List`. If the hash has already been finished, this method /// will return the existing state without re-computing. /// /// Parameters: - /// - [out]: The List in which the hash digest is stored. + /// - [out]: The `List` in which the hash digest is stored. /// /// Returns the current instance of the hash algorithm. @override @@ -109,7 +109,7 @@ class SHA1 implements SerializableHash { _buffer.add(0); } - var lengthInBits = _lengthInBytes * 8; + final lengthInBits = _lengthInBytes * 8; // Add the full length of the input data as a 64-bit value at the end of the // hash. Note: we're only writing out 64 bits, so skip ahead 8 if the @@ -122,8 +122,8 @@ class SHA1 implements SerializableHash { // We're essentially doing byteData.setUint64(offset, lengthInBits, _endian) // here, but that method isn't supported on dart2js so we implement it // manually instead. - var highBits = lengthInBits ~/ 0x100000000; // >> 32 - var lowBits = lengthInBits & mask32; + final highBits = lengthInBits ~/ 0x100000000; // >> 32 + final lowBits = lengthInBits & mask32; writeUint32BE(highBits, _buffer, offset); writeUint32BE(lowBits, _buffer, offset + 4); } @@ -234,7 +234,7 @@ class SHA1 implements SerializableHash { /// If the hash has already been finished using the `finish` method, calling this method will result in an error. /// /// Parameters: - /// - [data]: The List containing the data to be hashed. + /// - [data]: The `List` containing the data to be hashed. /// /// Returns this [Hash] object for method chaining. @override @@ -250,7 +250,7 @@ class SHA1 implements SerializableHash { } void _iterate() { - var pendingDataChunks = _buffer.length ~/ getBlockSize; + final pendingDataChunks = _buffer.length ~/ getBlockSize; for (var i = 0; i < pendingDataChunks; i++) { // Copy words from the pending data buffer into the current chunk buffer. for (var j = 0; j < _currentChunk.length; j++) { diff --git a/lib/crypto/crypto/hash/sha256/sha256.dart b/lib/crypto/crypto/hash/sha256/sha256.dart index 03c8296..20e918e 100644 --- a/lib/crypto/crypto/hash/sha256/sha256.dart +++ b/lib/crypto/crypto/hash/sha256/sha256.dart @@ -21,7 +21,7 @@ class SHA256 implements SerializableHash { @override int get getBlockSize => blockSize; - // Note: List is used instead of Uint32List for performance reasons. + // Note: `List` is used instead of Uint32List for performance reasons. final List _state = List.filled(8, 0); // hash state final List _temp = List.filled(64, 0); // temporary state final List _buffer = List.filled(128, 0); // buffer for data to hash @@ -49,7 +49,7 @@ class SHA256 implements SerializableHash { /// If the hash has already been finished using the `finish` method, calling this method will result in an error. /// /// Parameters: - /// - [data]: The List containing the data to be hashed. + /// - [data]: The `List` containing the data to be hashed. /// /// Returns this [Hash] object for method chaining. @override @@ -88,14 +88,14 @@ class SHA256 implements SerializableHash { return this; } - /// Finalizes the hash computation and stores the hash state in the provided List [out]. + /// Finalizes the hash computation and stores the hash state in the provided `List` [out]. /// /// This function completes the hash computation, finalizes the state, and stores the resulting - /// hash in the provided [out] List. If the hash has already been finished, this method + /// hash in the provided [out] `List`. If the hash has already been finished, this method /// will return the existing state without re-computing. /// /// Parameters: - /// - [out]: The List in which the hash digest is stored. + /// - [out]: The `List` in which the hash digest is stored. /// /// Returns the current instance of the hash algorithm. @override @@ -125,13 +125,13 @@ class SHA256 implements SerializableHash { return this; } - /// Generates the final hash digest by assembling and returning the hash state in a List. + /// Generates the final hash digest by assembling and returning the hash state in a `List`. /// /// This function produces the hash digest by combining the current hash state into a single - /// List output. It finalizes the hash if it hasn't been finished, effectively completing + /// `List` output. It finalizes the hash if it hasn't been finished, effectively completing /// the hash computation and returning the result. /// - /// Returns the List containing the computed hash digest. + /// Returns the `List` containing the computed hash digest. @override List digest() { final out = List.filled(getDigestLength, 0); @@ -299,22 +299,22 @@ class SHA256 implements SerializableHash { int g = v[6]; int h = v[7]; for (int i = 0; i < 16; i++) { - int j = pos + i * 4; + final int j = pos + i * 4; w[i] = readUint32BE(p, j); } for (int i = 16; i < 64; i++) { int u = w[i - 2]; - int t1 = rotr32(u, 17) ^ rotr32(u, 19) ^ (u >> 10); + final int t1 = rotr32(u, 17) ^ rotr32(u, 19) ^ (u >> 10); u = w[i - 15]; - int t2 = rotr32(u, 7) ^ rotr32(u, 18) ^ (u >> 3); + final int t2 = rotr32(u, 7) ^ rotr32(u, 18) ^ (u >> 3); w[i] = add32(add32(add32(t1, w[i - 7]), t2), w[i - 16]); } for (int i = 0; i < 64; i++) { - int t1 = add32( + final int t1 = add32( add32(rotr32(e, 6) ^ rotr32(e, 11) ^ rotr32(e, 25), (e & f) ^ (~e & g)), add32(add32(h, _k[i]), w[i])); - int t2 = add32((rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22)), + final int t2 = add32((rotr32(a, 2) ^ rotr32(a, 13) ^ rotr32(a, 22)), (a & b) ^ (a & c) ^ (b & c)); h = g; g = f; diff --git a/lib/crypto/crypto/hash/sha512/sha512.dart b/lib/crypto/crypto/hash/sha512/sha512.dart index 561bf78..009b3aa 100644 --- a/lib/crypto/crypto/hash/sha512/sha512.dart +++ b/lib/crypto/crypto/hash/sha512/sha512.dart @@ -95,7 +95,7 @@ class SHA512 implements SerializableHash { /// If the hash has already been finished using the `finish` method, calling this method will result in an error. /// /// Parameters: - /// - [data]: The List containing the data to be hashed. + /// - [data]: The `List` containing the data to be hashed. /// /// Returns this [Hash] object for method chaining. @override @@ -135,14 +135,14 @@ class SHA512 implements SerializableHash { return this; } - /// Finalizes the hash computation and stores the hash state in the provided List [out]. + /// Finalizes the hash computation and stores the hash state in the provided `List` [out]. /// /// This function completes the hash computation, finalizes the state, and stores the resulting - /// hash in the provided [out] List. If the hash has already been finished, this method + /// hash in the provided [out] `List`. If the hash has already been finished, this method /// will return the existing state without re-computing. /// /// Parameters: - /// - [out]: The List in which the hash digest is stored. + /// - [out]: The `List` in which the hash digest is stored. /// /// Returns the current instance of the hash algorithm. @override @@ -175,13 +175,13 @@ class SHA512 implements SerializableHash { return this; } - /// Generates the final hash digest by assembling and returning the hash state in a List. + /// Generates the final hash digest by assembling and returning the hash state in a `List`. /// /// This function produces the hash digest by combining the current hash state into a single - /// List output. It finalizes the hash if it hasn't been finished, effectively completing + /// `List` output. It finalizes the hash if it hasn't been finished, effectively completing /// the hash computation and returning the result. /// - /// Returns the List containing the computed hash digest. + /// Returns the `List` containing the computed hash digest. @override List digest() { final out = List.filled(getDigestLength, 0); @@ -415,73 +415,73 @@ class SHA512 implements SerializableHash { int _sigma1A(int ah4, int al4) { ah4 &= mask32; al4 &= mask32; - int one1 = (ah4 >> 14); - int one2 = al4 << (32 - 14); - int one = (one1 | one2); - - int two1 = ((ah4) >> 18); - int two2 = (al4 << (32 - 18)); - int two = (two1 | two2); - int three1 = (al4 >> 9); - int three2 = (ah4 << 23); - int three = (three1 | three2); - int h = one ^ two ^ three; + final int one1 = (ah4 >> 14); + final int one2 = al4 << (32 - 14); + final int one = (one1 | one2); + + final int two1 = ((ah4) >> 18); + final int two2 = (al4 << (32 - 18)); + final int two = (two1 | two2); + final int three1 = (al4 >> 9); + final int three2 = (ah4 << 23); + final int three = (three1 | three2); + final int h = one ^ two ^ three; return h; } int _sigma1B(int ah0, int al0) { al0 &= mask32; ah0 &= mask32; - int one1 = (ah0 >> 28) & mask32; - int one2 = al0 << (32 - 28) & mask32; - int one = (one1 | one2); - int two1 = (al0 >> 2); - int two2 = (ah0 << (32 - (34 - 32))) & mask32; - int two = (two1 | two2); - int three1 = (al0 >> 7); - int three2 = (ah0 << (32 - (39 - 32))) & mask32; - int three = (three1 | three2); - int h = one ^ two ^ three; + final int one1 = (ah0 >> 28) & mask32; + final int one2 = al0 << (32 - 28) & mask32; + final int one = (one1 | one2); + final int two1 = (al0 >> 2); + final int two2 = (ah0 << (32 - (34 - 32))) & mask32; + final int two = (two1 | two2); + final int three1 = (al0 >> 7); + final int three2 = (ah0 << (32 - (39 - 32))) & mask32; + final int three = (three1 | three2); + final int h = one ^ two ^ three; return h; } int _sigma0A(int th, int tl) { th &= mask32; tl &= mask32; - int one = ((th >> 1) | (tl << (32 - 1))) & mask32; - int two = ((th >> 8) | (tl << (32 - 8))) & mask32; - int three = (th >> 7); - int h = one ^ two ^ three; + final int one = ((th >> 1) | (tl << (32 - 1))) & mask32; + final int two = ((th >> 8) | (tl << (32 - 8))) & mask32; + final int three = (th >> 7); + final int h = one ^ two ^ three; return h; } int _sigma0B(int th, int tl) { th &= mask32; tl &= mask32; - int one = ((tl >> 1) | (th << (32 - 1))) & mask32; - int two = ((tl >> 8) | (th << (32 - 8))) & mask32; - int three = ((tl >> 7) | (th << (32 - 7))) & mask32; - int h = one ^ two ^ three; + final int one = ((tl >> 1) | (th << (32 - 1))) & mask32; + final int two = ((tl >> 8) | (th << (32 - 8))) & mask32; + final int three = ((tl >> 7) | (th << (32 - 7))) & mask32; + final int h = one ^ two ^ three; return h; } int _sigma0C(int th, int tl) { th &= mask32; tl &= mask32; - int one = ((th >> 19) | (tl << (32 - 19))) & mask32; - int two = ((tl >> (61 - 32)) | (th << (32 - (61 - 32)))) & mask32; - int three = (th >> 6) & mask32; - int h = one ^ two ^ three; + final int one = ((th >> 19) | (tl << (32 - 19))) & mask32; + final int two = ((tl >> (61 - 32)) | (th << (32 - (61 - 32)))) & mask32; + final int three = (th >> 6) & mask32; + final int h = one ^ two ^ three; return h; } int _sigma0D(int th, int tl) { th &= mask32; tl &= mask32; - int one = ((tl >> 19) | (th << (32 - 19))) & mask32; - int two = ((th >> (61 - 32)) | (tl << (32 - (61 - 32)))) & mask32; - int three = ((tl >> 6) | (th << (32 - 6))) & mask32; - int h = one ^ two ^ three; + final int one = ((tl >> 19) | (th << (32 - 19))) & mask32; + final int two = ((th >> (61 - 32)) | (tl << (32 - (61 - 32)))) & mask32; + final int three = ((tl >> 6) | (th << (32 - 6))) & mask32; + final int h = one ^ two ^ three; return h; } @@ -511,28 +511,28 @@ class SHA512 implements SerializableHash { while (len >= 128) { for (int i = 0; i < 16; i++) { - int j = 8 * i + pos; + final int j = 8 * i + pos; wh[i] = readUint32BE(m, j); wl[i] = readUint32BE(m, j + 4); } for (int i = 0; i < 80; i++) { - int bh0 = ah0; - int bh1 = ah1; - int bh2 = ah2; + final int bh0 = ah0; + final int bh1 = ah1; + final int bh2 = ah2; int bh3 = ah3; - int bh4 = ah4; - int bh5 = ah5; - int bh6 = ah6; + final int bh4 = ah4; + final int bh5 = ah5; + final int bh6 = ah6; int bh7 = ah7; - int bl0 = al0; - int bl1 = al1; - int bl2 = al2; + final int bl0 = al0; + final int bl1 = al1; + final int bl2 = al2; int bl3 = al3; - int bl4 = al4; - int bl5 = al5; - int bl6 = al6; + final int bl4 = al4; + final int bl5 = al5; + final int bl6 = al6; int bl7 = al7; // add @@ -921,7 +921,7 @@ class SHA512 implements SerializableHash { /// final state = SHA512State( /// stateHi: Int32List(8), /// stateLo: Int32List(8), -/// buffer:List.filled(SHA512.blockSize), +/// buffer:`List`.filled(SHA512.blockSize), /// bufferLength: 0, /// bytesHashed: 0, /// ); diff --git a/lib/crypto/crypto/hmac/hmac.dart b/lib/crypto/crypto/hmac/hmac.dart index a8bfc5b..4668ebc 100644 --- a/lib/crypto/crypto/hmac/hmac.dart +++ b/lib/crypto/crypto/hmac/hmac.dart @@ -28,7 +28,7 @@ class HMAC implements SerializableHash { /// /// Example: /// ```dart - /// final key = List.from([0x00, 0x01, 0x02]); + /// final key = `List`.from([0x00, 0x01, 0x02]); /// final hmac = HMAC(()=>SHA256(), key); /// ``` /// @@ -115,7 +115,7 @@ class HMAC implements SerializableHash { /// If the hash has already been finished using the `finish` method, calling this method will result in an error. /// /// Parameters: - /// - [data]: The List containing the data to be hashed. + /// - [data]: The `List` containing the data to be hashed. /// /// Returns this [Hash] object for method chaining. @override @@ -124,14 +124,14 @@ class HMAC implements SerializableHash { return this; } - /// Finalizes the hash computation and stores the hash state in the provided List [out]. + /// Finalizes the hash computation and stores the hash state in the provided `List` [out]. /// /// This function completes the hash computation, finalizes the state, and stores the resulting - /// hash in the provided [out] List. If the hash has already been finished, this method + /// hash in the provided [out] `List`. If the hash has already been finished, this method /// will return the existing state without re-computing. /// /// Parameters: - /// - [out]: The List in which the hash digest is stored. + /// - [out]: The `List` in which the hash digest is stored. /// /// Returns the current instance of the hash algorithm. @override @@ -150,13 +150,13 @@ class HMAC implements SerializableHash { return this; } - /// Generates the final hash digest by assembling and returning the hash state in a List. + /// Generates the final hash digest by assembling and returning the hash state in a `List`. /// /// This function produces the hash digest by combining the current hash state into a single - /// List output. It finalizes the hash if it hasn't been finished, effectively completing + /// `List` output. It finalizes the hash if it hasn't been finished, effectively completing /// the hash computation and returning the result. /// - /// Returns the List containing the computed hash digest. + /// Returns the `List` containing the computed hash digest. @override List digest() { final out = List.filled(getDigestLength, 0); @@ -210,8 +210,8 @@ class HMAC implements SerializableHash { /// /// Example: /// ```dart - /// final key = List.from([0x00, 0x01, 0x02]); - /// final data = List.from([0x10, 0x11, 0x12, 0x13]); + /// final key = `List`.from([0x00, 0x01, 0x02]); + /// final data = `List`.from([0x10, 0x11, 0x12, 0x13]); /// final hmac = hmac(()=>SHA256(), key, data); /// ``` static List hmac(HashFunc hash, List key, List data) { diff --git a/lib/crypto/crypto/poly1305/poly1305.dart b/lib/crypto/crypto/poly1305/poly1305.dart index ee20d2c..9364c11 100644 --- a/lib/crypto/crypto/poly1305/poly1305.dart +++ b/lib/crypto/crypto/poly1305/poly1305.dart @@ -1,6 +1,6 @@ // import 'dart:typed_data'; import 'package:blockchain_utils/utils/utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; const _digestLength = 16; @@ -33,22 +33,22 @@ class Poly1305 { _init(key); } void _init(List key) { - int t0 = key[0] | (key[1] << 8); + final int t0 = key[0] | (key[1] << 8); _r[0] = (t0) & mask13; - int t1 = key[2] | (key[3] << 8); + final int t1 = key[2] | (key[3] << 8); _r[1] = ((t0 >> 13) | (t1 << 3)) & mask13; - int t2 = key[4] | (key[5] << 8); + final int t2 = key[4] | (key[5] << 8); _r[2] = ((t1 >> 10) | (t2 << 6)) & 0x1f03; - int t3 = key[6] | (key[7] << 8); + final int t3 = key[6] | (key[7] << 8); _r[3] = ((t2 >> 7) | (t3 << 9)) & mask13; - int t4 = key[8] | (key[9] << 8); + final int t4 = key[8] | (key[9] << 8); _r[4] = ((t3 >> 4) | (t4 << 12)) & 0x00ff; _r[5] = ((t4 >> 1)) & 0x1ffe; - int t5 = key[10] | (key[11] << 8); + final int t5 = key[10] | (key[11] << 8); _r[6] = ((t4 >> 14) | (t5 << 2)) & mask13; - int t6 = key[12] | (key[13] << 8); + final int t6 = key[12] | (key[13] << 8); _r[7] = ((t5 >> 11) | (t6 << 5)) & 0x1f81; - int t7 = key[14] | (key[15] << 8); + final int t7 = key[14] | (key[15] << 8); _r[8] = ((t6 >> 8) | (t7 << 8)) & mask13; _r[9] = ((t7 >> 5)) & 0x007f; _pad[0] = key[16] | (key[17] << 8); @@ -74,7 +74,7 @@ class Poly1305 { h8 = _h[8], h9 = _h[9]; - int r0 = _r[0], + final int r0 = _r[0], r1 = _r[1], r2 = _r[2], r3 = _r[3], @@ -454,7 +454,7 @@ class Poly1305 { if (_finished) { throw const MessageException("Poly1305 was finished"); } - List mac = List.filled(16, 0); + final List mac = List.filled(16, 0); finish(mac); return mac; } @@ -494,9 +494,9 @@ class Poly1305 { /// This method creates a `Poly1305` instance initialized with the provided key, updates it with the data, /// computes the MAC, and then cleans up the instance before returning the MAC. static List auth(List key, List data) { - Poly1305 h = Poly1305(key); + final Poly1305 h = Poly1305(key); h.update(data); - List digest = h.digest(); + final List digest = h.digest(); h.clean(); return digest; } diff --git a/lib/crypto/crypto/prng/fortuna.dart b/lib/crypto/crypto/prng/fortuna.dart index 0773ba2..db60a32 100644 --- a/lib/crypto/crypto/prng/fortuna.dart +++ b/lib/crypto/crypto/prng/fortuna.dart @@ -2,7 +2,7 @@ import 'dart:math'; import 'package:blockchain_utils/crypto/crypto/aes/aes.dart'; import 'package:blockchain_utils/crypto/crypto/ctr/ctr.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// The `GenerateRandom` typedef defines a function signature for generating random data with a specified length. typedef GenerateRandom = List Function(int length); @@ -144,7 +144,7 @@ class FortunaPRNG { _generateBlocks(_out, 1); _c = 0; } - int result = (_out[_c] << 24) | + final int result = (_out[_c] << 24) | (_out[_c + 1] << 16) | (_out[_c + 2] << 8) | (_out[_c + 3]); @@ -161,7 +161,7 @@ class FortunaPRNG { if (max <= 0) throw ArgumentError("max must be greater than 0"); // Generate a random double in the range [0.0, 1.0) - double fraction = + final double fraction = nextUint32 / 4294967296.0; // Divide by 2^32 to get a fraction return (fraction * max).floor(); } diff --git a/lib/crypto/crypto/schnorrkel/keys/keys.dart b/lib/crypto/crypto/schnorrkel/keys/keys.dart index ee728c5..be90a87 100644 --- a/lib/crypto/crypto/schnorrkel/keys/keys.dart +++ b/lib/crypto/crypto/schnorrkel/keys/keys.dart @@ -8,7 +8,7 @@ import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:blockchain_utils/crypto/crypto/prng/fortuna.dart'; import 'package:blockchain_utils/crypto/crypto/schnorrkel/merlin/transcript.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// The `SchnorrkelKeyCost` class defines various constants related to the sizes and lengths of Schnorrkel keys and components. /// @@ -61,10 +61,10 @@ class _KeyUtils { /// Returns: /// A new byte array with the scalar divided by the cofactor. static List divideScalarByCofactor(List s) { - int l = s.length - 1; + final int l = s.length - 1; int low = 0; for (int i = 0; i < s.length; i++) { - int r = s[l - i] & 0x07; // remainder + final int r = s[l - i] & 0x07; // remainder s[l - i] >>= 3; s[l - i] += low; low = r << 5; @@ -80,7 +80,7 @@ class _KeyUtils { static void multiplyScalarBytesByCofactor(List scalar) { int high = 0; for (int i = 0; i < scalar.length; i++) { - int r = scalar[i] & 0xE0; // carry bits (0xE0 is binary 11100000) + final int r = scalar[i] & 0xE0; // carry bits (0xE0 is binary 11100000) scalar[i] <<= 3; // multiply by 8 scalar[i] += high; high = r >> 5; @@ -102,8 +102,8 @@ class _KeyUtils { static List? toCanonical(List bytes) { final cloneBytes = List.from(bytes); cloneBytes[31] &= 127; - bool highBitUnset = (bytes[31] >> 7 & 0) == 0; - bool isCanonical = BytesUtils.bytesEqual( + final bool highBitUnset = (bytes[31] >> 7 & 0) == 0; + final bool isCanonical = BytesUtils.bytesEqual( cloneBytes, Ed25519Utils.scalarReduce(cloneBytes)); if (highBitUnset && isCanonical) { return cloneBytes; diff --git a/lib/crypto/crypto/schnorrkel/merlin/transcript.dart b/lib/crypto/crypto/schnorrkel/merlin/transcript.dart index d8611ff..f2a574a 100644 --- a/lib/crypto/crypto/schnorrkel/merlin/transcript.dart +++ b/lib/crypto/crypto/schnorrkel/merlin/transcript.dart @@ -58,7 +58,7 @@ class MerlinTranscript { void additionalData(List label, List message) { final size = List.filled(4, 0); writeUint32LE(message.length, size); - List labelSize = [...label, ...size]; + final List labelSize = [...label, ...size]; strobe.additionalData(true, labelSize); strobe.additionalData(false, message); } @@ -89,10 +89,10 @@ class MerlinTranscript { List toBytes(List label, int outLen) { final len = List.filled(4, 0); writeUint32LE(outLen, len); - List labelSize = [...label, ...len]; + final List labelSize = [...label, ...len]; strobe.additionalData(true, labelSize); - List outBytes = strobe.pseudoRandomData(outLen); + final List outBytes = strobe.pseudoRandomData(outLen); return BytesUtils.toBytes(outBytes); } diff --git a/lib/crypto/crypto/schnorrkel/shnorrkel.dart b/lib/crypto/crypto/schnorrkel/shnorrkel.dart index cb630d3..f1cd179 100644 --- a/lib/crypto/crypto/schnorrkel/shnorrkel.dart +++ b/lib/crypto/crypto/schnorrkel/shnorrkel.dart @@ -1,6 +1,6 @@ /// The 'schnorrkel' library provides tools for working with the Schnorrkel /// digital signature scheme, including key management and cryptographic functions. -library schnorrkel; +library; /// Export statement for Schnorrkel key management components. export 'keys/keys.dart'; diff --git a/lib/crypto/crypto/schnorrkel/strobe/strobe.dart b/lib/crypto/crypto/schnorrkel/strobe/strobe.dart index f92fcfc..0604c2d 100644 --- a/lib/crypto/crypto/schnorrkel/strobe/strobe.dart +++ b/lib/crypto/crypto/schnorrkel/strobe/strobe.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/utils/utils.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; class StrobeSecParam { /// 128-bit security level @@ -153,7 +153,7 @@ class Strobe { /// This factory constructor ensures that the Strobe instance is properly initialized and configured based on the provided parameters, allowing it to be used for secure protocol operations. factory Strobe(String customizationString, StrobeSecParam security) { final int rate = (1600 ~/ 8) - security.value ~/ 4; - Strobe s = Strobe._( + final Strobe s = Strobe._( io: 2, rate: rate, strober: rate - 2, @@ -162,7 +162,7 @@ class Strobe { storage: List.filled(rate, 0), buffer: List.empty(growable: true), ); - List domain = [1, rate, 1, 0, 1, 12 * 8]; + final List domain = [1, rate, 1, 0, 1, 12 * 8]; domain.addAll(version.codeUnits); s._duplex(domain, false, false, true); @@ -184,7 +184,7 @@ class Strobe { _buffer.add(_posBegin); _buffer.add(0x04); _st.setAll(0, _buffer); - int zerosStart = _buffer.length; + final int zerosStart = _buffer.length; _buffer = _st.sublist(0, rate); for (int i = zerosStart; i < rate; i++) { _buffer[i] = 0; @@ -193,7 +193,7 @@ class Strobe { _st.setAll(0, _buffer); _xor(_state, _buffer); } else if (_buffer.isNotEmpty) { - int zerosStart = _buffer.length; + final int zerosStart = _buffer.length; _buffer = _st.sublist(0, rate); for (int i = zerosStart; i < rate; i++) { _buffer[i] = 0; @@ -306,9 +306,10 @@ class Strobe { } // Operation - bool cAfter = ((flags & (StrobeFlags.C | StrobeFlags.I | StrobeFlags.T)) == - (StrobeFlags.C | StrobeFlags.T)); - bool cBefore = ((flags & StrobeFlags.C) != 0) && (!cAfter); + final bool cAfter = + ((flags & (StrobeFlags.C | StrobeFlags.I | StrobeFlags.T)) == + (StrobeFlags.C | StrobeFlags.T)); + final bool cBefore = ((flags & StrobeFlags.C) != 0) && (!cAfter); _duplex(data, cBefore, cAfter, false); if ((flags & (StrobeFlags.I | StrobeFlags.A)) == @@ -323,7 +324,7 @@ class Strobe { "Not supposed to check a MAC with the 'more' streaming option"); } int failures = 0; - for (int dataByte in data) { + for (final dataByte in data) { failures |= dataByte; } return List.from([failures]); // 0 if correct, 1 if not @@ -341,7 +342,7 @@ class Strobe { /// /// Usage: /// ```dart - /// List secretKey = ...; // Your secret key. + /// `List` secretKey = ...; // Your secret key. /// strobeInstance.key(secretKey); /// // Set the secret key for cryptographic operations. /// ``` @@ -366,7 +367,7 @@ class Strobe { /// Usage: /// ```dart /// int outputLength = 32; // Length of the desired pseudo-random data. - /// List randomData = strobeInstance.pseudoRandomData(outputLength); + /// `List` randomData = strobeInstance.pseudoRandomData(outputLength); /// // Generate pseudo-random data for a specific use case. /// ``` /// @@ -392,8 +393,8 @@ class Strobe { /// /// Usage: /// ```dart - /// List plaintext = ...; // Data to be encrypted and sent. - /// List ciphertext = strobeInstance.sendEncUnauthenticated(true, plaintext); + /// `List` plaintext = ...; // Data to be encrypted and sent. + /// `List` ciphertext = strobeInstance.sendEncUnauthenticated(true, plaintext); /// // Encrypt and send data without authentication. /// ``` /// @@ -419,8 +420,8 @@ class Strobe { /// /// Usage: /// ```dart - /// List ciphertext = ...; // Received unauthenticated ciphertext. - /// List plaintext = strobeInstance.recvUnauthenticatedEncryptMessage(true, ciphertext); + /// `List` ciphertext = ...; // Received unauthenticated ciphertext. + /// `List` plaintext = strobeInstance.recvUnauthenticatedEncryptMessage(true, ciphertext); /// // Receive and process unauthenticated encrypted message. /// ``` /// @@ -441,7 +442,7 @@ class Strobe { /// /// Usage: /// ```dart - /// List metadata = ...; // Additional data or metadata to include. + /// `List` metadata = ...; // Additional data or metadata to include. /// strobeInstance.additionalData(true, metadata); /// // Process and add additional data to the Strobe protocol state. /// ``` @@ -459,11 +460,11 @@ class Strobe { /// /// Parameters: /// - `meta`: A boolean flag indicating whether metadata is included in the operation. - /// - `cleartext`: A List containing the clear text data to be processed and sent. + /// - `cleartext`: A `List` containing the clear text data to be processed and sent. /// /// Usage: /// ```dart - /// List dataToSend = ...; // Clear text data to send. + /// `List` dataToSend = ...; // Clear text data to send. /// strobeInstance.sendClearText(true, dataToSend); /// // Process and send the clear text data within the Strobe protocol. /// ``` @@ -480,11 +481,11 @@ class Strobe { /// /// Parameters: /// - `meta`: A boolean flag indicating whether metadata is included in the operation. - /// - `cleartext`: A List containing the received clear text data to be processed. + /// - `cleartext`: A `List` containing the received clear text data to be processed. /// /// Usage: /// ```dart - /// List receivedData = ...; // Received clear text data. + /// `List` receivedData = ...; // Received clear text data. /// strobeInstance.receivedClearText(true, receivedData); /// // Process the received clear text data within the Strobe protocol. /// ``` @@ -505,12 +506,12 @@ class Strobe { /// - `outputLength`: The desired output length of the generated MAC. /// /// Returns: - /// - A List containing the generated MAC of the specified length. + /// - A `List` containing the generated MAC of the specified length. /// /// Usage: /// ```dart /// int desiredMacLength = 16; // Specify the desired MAC length in bytes. - /// List generatedMac = strobeInstance.sendMac(true, desiredMacLength); + /// `List` generatedMac = strobeInstance.sendMac(true, desiredMacLength); /// // Append the generated MAC to the data to be sent. /// ``` /// diff --git a/lib/crypto/crypto/scrypt/scrypt.dart b/lib/crypto/crypto/scrypt/scrypt.dart index 811c44c..8e8f066 100644 --- a/lib/crypto/crypto/scrypt/scrypt.dart +++ b/lib/crypto/crypto/scrypt/scrypt.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:blockchain_utils/utils/utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// A class for performing scrypt key derivation. /// @@ -144,7 +144,7 @@ class Scrypt { ((sum << n) & mask32) | (sum & mask32) >> (32 - n); static void _salsaXOR(List tmp, List B, int bin, int bout) { - int j0 = tmp[0] ^ B[bin++], + final int j0 = tmp[0] ^ B[bin++], j1 = tmp[1] ^ B[bin++], j2 = tmp[2] ^ B[bin++], j3 = tmp[3] ^ B[bin++], @@ -262,9 +262,9 @@ class Scrypt { } static void _smix(List B, int r, int N, List V, List xy) { - var xi = 0; - var yi = 32 * r; - var tmp = List.filled(16, 0); + const xi = 0; + final yi = 32 * r; + final tmp = List.filled(16, 0); for (var i = 0; i < 32 * r; i++) { V[i] = readUint32LE(B, i * 4); 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 7956a6a..c4de13a 100644 --- a/lib/crypto/crypto/x_modem_crc/x_modem_crc.dart +++ b/lib/crypto/crypto/x_modem_crc/x_modem_crc.dart @@ -8,7 +8,7 @@ import 'package:blockchain_utils/utils/utils.dart'; class XModemCrc { static List _calculateXmodemCrc(List bytes) { int crc = 0; - for (int byte in bytes) { + for (final byte in bytes) { crc = crc ^ byte << 8; for (int i = 0; i < 8; i++) { if ((crc & 0x8000) != 0) { @@ -19,7 +19,7 @@ class XModemCrc { } } - // Convert the 16-bit CRC integer to a List with two bytes + // Convert the 16-bit CRC integer to a `List` with two bytes final crcBytes = List.filled(2, 0); crcBytes[0] = (crc >> 8) & mask8; crcBytes[1] = crc & mask8; @@ -30,13 +30,13 @@ class XModemCrc { /// Calculates the XModem CRC (Cyclic Redundancy Check) for the given [data]. /// /// This method computes the CRC value for a block of data using the XModem CRC - /// algorithm and returns the result as a 16-bit [List]. + /// algorithm and returns the result as a 16-bit [`List`]. /// /// Parameters: /// - [data]: The data block for which to calculate the CRC. /// /// Returns: - /// A 16-bit CRC value as a List. + /// A 16-bit CRC value as a `List`. static List quickDigest(List data) { return _calculateXmodemCrc(data); } diff --git a/lib/crypto/quick_crypto.dart b/lib/crypto/quick_crypto.dart index 82a9509..6246ab0 100644 --- a/lib/crypto/quick_crypto.dart +++ b/lib/crypto/quick_crypto.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/crypto/crypto/aes/padding.dart'; import 'package:blockchain_utils/crypto/crypto/crypto.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/utils/utils.dart'; /// QuickCrypto provides a set of utility methods for cryptographic operations. @@ -16,7 +16,7 @@ class QuickCrypto { /// Calculate the SHA-256 hash of the SHA-256 hash of the input data static List sha256DoubleHash(List data) { - List tmp = sha256Hash(data); + final List tmp = sha256Hash(data); return sha256Hash(tmp); } @@ -41,7 +41,7 @@ class QuickCrypto { /// Calculate the RIPEMD-160 hash of the SHA-256 hash of the input data static List hash160(List data) { - List tmp = SHA256.hash(data); + final List tmp = SHA256.hash(data); return RIPEMD160.hash(tmp); } @@ -161,8 +161,6 @@ class QuickCrypto { return _xxHash(data, twoX256DigestSize); } - // Twox128: (data) => utilCrypto.xxhashAsU8a(data, 128), - // Twox256: (data) => utilCrypto.xxhashAsU8a(data, 256), /// Calculate the SHA-512/256 hash of the input data static List sha512256Hash(List data) { return SHA512256.hash(data); @@ -297,7 +295,7 @@ class QuickCrypto { } } - /// This function generates a random List of the specified size (default is 32 bytes). + /// This function generates a random `List` of the specified size (default is 32 bytes). static List generateRandom([int size = 32]) { /// Generate the random bytes of the specified size using the _randomGenerator. final r = _generateRandom(size); diff --git a/lib/exception/const/const.dart b/lib/exception/const/const.dart new file mode 100644 index 0000000..fd13891 --- /dev/null +++ b/lib/exception/const/const.dart @@ -0,0 +1,6 @@ +import 'package:blockchain_utils/exception/exception/exception.dart'; + +class ExceptionConst { + static GenericException itemNotFound({String? item}) => + GenericException("${item ?? 'item'} not found."); +} diff --git a/lib/exception/exception.dart b/lib/exception/exception/exception.dart similarity index 82% rename from lib/exception/exception.dart rename to lib/exception/exception/exception.dart index 41878c8..650947b 100644 --- a/lib/exception/exception.dart +++ b/lib/exception/exception/exception.dart @@ -23,14 +23,17 @@ abstract class BlockchainUtilsException implements Exception { /// This exception is used to represent errors related to invalid arguments in blockchain utility operations. class ArgumentException extends BlockchainUtilsException { /// Constructor to initialize the exception with a specific message. - const ArgumentException(String message, {Map? details}) - : super(message, details: details); + const ArgumentException(super.message, {super.details}); } /// Another specific exception class 'MessageException' that extends 'BlockchainUtilsException'. /// This exception is used to represent errors related to messages in blockchain utility operations. class MessageException extends BlockchainUtilsException { /// Constructor to initialize the exception with a specific message. - const MessageException(String message, {Map? details}) - : super(message, details: details); + const MessageException(super.message, {super.details}); +} + +class GenericException extends BlockchainUtilsException { + /// Constructor to initialize the exception with a specific message. + const GenericException(super.message, {super.details}); } diff --git a/lib/exception/rpc_error.dart b/lib/exception/exception/rpc_error.dart similarity index 95% rename from lib/exception/rpc_error.dart rename to lib/exception/exception/rpc_error.dart index 038dd7e..dcc94f0 100644 --- a/lib/exception/rpc_error.dart +++ b/lib/exception/exception/rpc_error.dart @@ -9,7 +9,7 @@ class RPCError extends BlockchainUtilsException { /// The optional [request] parameter holds the details of the RPC request that resulted in the error. const RPCError( {required String message, - required this.errorCode, + this.errorCode, this.request, Map? details}) : super(message, details: details); @@ -20,6 +20,8 @@ class RPCError extends BlockchainUtilsException { /// Details of the RPC request that resulted in the error. final Map? request; + int? get statusCode => request?["statusCode"]; + @override String toString() { final infos = Map.fromEntries( diff --git a/lib/exception/exceptions.dart b/lib/exception/exceptions.dart index 0577254..28781a2 100644 --- a/lib/exception/exceptions.dart +++ b/lib/exception/exceptions.dart @@ -1,2 +1,2 @@ -export 'exception.dart'; -export 'rpc_error.dart'; +export 'exception/exception.dart'; +export 'exception/rpc_error.dart'; diff --git a/lib/helper/extensions/extensions.dart b/lib/helper/extensions/extensions.dart index e4b9ac4..09b269a 100644 --- a/lib/helper/extensions/extensions.dart +++ b/lib/helper/extensions/extensions.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/utils/utils.dart'; typedef ItrableCondition = bool Function(T); @@ -59,12 +59,12 @@ extension IterableIntHelper on Iterable { extension ListIntHelper on List { List get asBytes { - BytesUtils.validateBytes(this); + BytesUtils.validateListOfBytes(this); return this; } List get asImmutableBytes { - BytesUtils.validateBytes(this); + BytesUtils.validateListOfBytes(this); return immutable; } diff --git a/lib/hex/hex.dart b/lib/hex/hex.dart index db948d6..eae37ca 100644 --- a/lib/hex/hex.dart +++ b/lib/hex/hex.dart @@ -1,5 +1,5 @@ import 'package:blockchain_utils/utils/utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; // ignore: library_private_types_in_public_api const _Hex hex = _Hex(); @@ -106,8 +106,8 @@ class _Hex { final result = List.filled(hex.length ~/ 2, 0); bool haveBad = false; for (int i = 0; i < hex.length; i += 2) { - int v0 = _decodeNibble(hex.codeUnitAt(i)); - int v1 = _decodeNibble(hex.codeUnitAt(i + 1)); + final int v0 = _decodeNibble(hex.codeUnitAt(i)); + final int v1 = _decodeNibble(hex.codeUnitAt(i + 1)); result[i ~/ 2] = ((v0 << 4) | v1) & mask8; haveBad |= (v0 == _invalidHexNibble) | (v1 == _invalidHexNibble); } diff --git a/lib/layout/core/types/array.dart b/lib/layout/core/types/array.dart index fc5f39a..d127b46 100644 --- a/lib/layout/core/types/array.dart +++ b/lib/layout/core/types/array.dart @@ -94,7 +94,7 @@ class SequenceLayout extends Layout> { @override LayoutDecodeResult> decode(LayoutByteReader bytes, {int offset = 0}) { - List decoded = []; + final List decoded = []; int i = 0; int startOffset = offset; int count; diff --git a/lib/layout/core/types/lazy_union.dart b/lib/layout/core/types/lazy_union.dart index 4cb2344..3e93da4 100644 --- a/lib/layout/core/types/lazy_union.dart +++ b/lib/layout/core/types/lazy_union.dart @@ -102,7 +102,8 @@ class LazyUnion extends Layout> { LazyVariantLayout? getVariant(LayoutByteReader variantBytes, {int offset = 0}) { - int variant = discriminator.decode(variantBytes, offset: offset).value; + final int variant = + discriminator.decode(variantBytes, offset: offset).value; return _registry[variant]; } @@ -140,7 +141,7 @@ class LazyVariantLayout extends Layout> { if (!this.span.isNegative) { return this.span; } - int contentOffset = union.discriminator.layout.span; + final int contentOffset = union.discriminator.layout.span; int span = 0; span = layout.layout(property: layout.property).getSpan(bytes, @@ -157,7 +158,7 @@ class LazyVariantLayout extends Layout> { details: {"property": property}); } - int contentOffset = union.discriminator.layout.span; + final int contentOffset = union.discriminator.layout.span; final Map dest = {}; int consumed = 0; @@ -173,7 +174,7 @@ class LazyVariantLayout extends Layout> { @override int encode(Map source, LayoutByteWriter writer, {int offset = 0}) { - int contentOffset = union.discriminator.layout.span; + final int contentOffset = union.discriminator.layout.span; if (!source.containsKey(property)) { throw LayoutException("variant lacks property", details: {"property": property}); diff --git a/lib/layout/core/types/numeric.dart b/lib/layout/core/types/numeric.dart index 7213926..282c4f0 100644 --- a/lib/layout/core/types/numeric.dart +++ b/lib/layout/core/types/numeric.dart @@ -10,8 +10,7 @@ import 'package:blockchain_utils/utils/numbers/numbers.dart'; /// Represents an external layout. abstract class ExternalLayout extends Layout { - const ExternalLayout(int span, {String? property}) - : super(span, property: property); + const ExternalLayout(super.span, {super.property}); bool isCount() => false; } @@ -54,8 +53,7 @@ class GreedyCount extends ExternalLayout { } abstract class BaseIntiger extends Layout { - const BaseIntiger(int span, {String? property}) - : super(span, property: property); + const BaseIntiger(super.span, {super.property}); void validate(T value); bool get sign; Endian get order; @@ -171,9 +169,8 @@ class BigIntLayout extends BaseIntiger { final bool sign; @override final Endian order; - BigIntLayout(int span, - {this.sign = false, this.order = Endian.little, String? property}) - : super(span, property: property); + BigIntLayout(super.span, + {this.sign = false, this.order = Endian.little, super.property}); @override void validate(BigInt value) { if (value.isNegative && !sign) { diff --git a/lib/layout/core/types/raw.dart b/lib/layout/core/types/raw.dart index 5996441..7be5561 100644 --- a/lib/layout/core/types/raw.dart +++ b/lib/layout/core/types/raw.dart @@ -42,7 +42,7 @@ class RawBytesLayout extends Layout> { @override LayoutDecodeResult> decode(LayoutByteReader bytes, {int offset = 0}) { - int span = getSpan(bytes, offset: offset); + final int span = getSpan(bytes, offset: offset); final result = bytes.sublist(offset, offset + span); return LayoutDecodeResult(consumed: span, value: result); } diff --git a/lib/layout/core/types/struct.dart b/lib/layout/core/types/struct.dart index 9e1e299..5f6fec4 100644 --- a/lib/layout/core/types/struct.dart +++ b/lib/layout/core/types/struct.dart @@ -23,7 +23,7 @@ class StructLayout extends Layout> { final bool decodePrefixes; factory StructLayout(List fields, {String? property, bool decodePrefixes = false}) { - for (var fd in fields) { + for (final fd in fields) { if (fd.property == null) { throw LayoutException("fields cannot contain unnamed layout", details: { "property": property, @@ -96,7 +96,7 @@ class StructLayout extends Layout> { {int offset = 0}) { final Map result = {}; int consumed = 0; - for (var fd in fields) { + for (final fd in fields) { if (fd.property != null) { final decode = fd.decode(bytes, offset: offset); consumed += decode.consumed; diff --git a/lib/layout/core/types/tuple_layout.dart b/lib/layout/core/types/tuple_layout.dart index d2c89ae..45713c7 100644 --- a/lib/layout/core/types/tuple_layout.dart +++ b/lib/layout/core/types/tuple_layout.dart @@ -16,7 +16,7 @@ class TupleLayout extends Layout { @override LayoutDecodeResult decode(LayoutByteReader bytes, {int offset = 0}) { - List encoded = []; + final List encoded = []; int pos = offset; for (final i in layouts) { final decode = i.decode(bytes, offset: pos); @@ -78,7 +78,7 @@ class TupleCompactLayout extends Layout { throw LayoutException("Source length must match layout length.", details: {"property": property}); } - List encoded = []; + final List encoded = []; int pos = decodeLength.item1 + offset; for (int i = 0; i < layouts.length; i++) { final layout = layouts[i]; diff --git a/lib/layout/core/types/union.dart b/lib/layout/core/types/union.dart index 2486496..9683187 100644 --- a/lib/layout/core/types/union.dart +++ b/lib/layout/core/types/union.dart @@ -194,7 +194,8 @@ class Union extends Layout> { } VariantLayout? getVariant(LayoutByteReader variantBytes, {int offset = 0}) { - int variant = discriminator.decode(variantBytes, offset: offset).value; + final int variant = + discriminator.decode(variantBytes, offset: offset).value; return _registry[variant]; } diff --git a/lib/layout/core/types/xdr_bytes.dart b/lib/layout/core/types/xdr_bytes.dart index 087af2f..404ca4d 100644 --- a/lib/layout/core/types/xdr_bytes.dart +++ b/lib/layout/core/types/xdr_bytes.dart @@ -26,7 +26,7 @@ class XDRBytesLayout extends Layout> { return XDRBytesLayout._(RawBytesLayout(length), property: property); } static int _reminder(int dividend) { - int remainder = dividend % 4; + final int remainder = dividend % 4; return remainder == 0 ? 0 : 4 - remainder; } diff --git a/lib/layout/exception/exception.dart b/lib/layout/exception/exception.dart index 248969d..2997fcb 100644 --- a/lib/layout/exception/exception.dart +++ b/lib/layout/exception/exception.dart @@ -1,6 +1,5 @@ import 'package:blockchain_utils/exception/exceptions.dart'; class LayoutException extends BlockchainUtilsException { - const LayoutException(String message, {Map? details}) - : super(message, details: details); + const LayoutException(super.message, {super.details}); } diff --git a/lib/layout/utils/utils.dart b/lib/layout/utils/utils.dart index 6f9be37..4de27d9 100644 --- a/lib/layout/utils/utils.dart +++ b/lib/layout/utils/utils.dart @@ -1,6 +1,6 @@ import 'dart:typed_data' show Endian; import 'package:blockchain_utils/bip/substrate/scale/substrate_scale_enc_cuint.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/utils/utils.dart'; class LayoutSerializationUtils { diff --git a/lib/secret_wallet/exception.dart b/lib/secret_wallet/exception.dart index 4aef257..5e1ce92 100644 --- a/lib/secret_wallet/exception.dart +++ b/lib/secret_wallet/exception.dart @@ -1,7 +1,5 @@ import 'package:blockchain_utils/blockchain_utils.dart'; class Web3SecretStorageDefinationV3Exception extends BlockchainUtilsException { - const Web3SecretStorageDefinationV3Exception(String message, - {Map? details}) - : super(message, details: details); + const Web3SecretStorageDefinationV3Exception(super.message, {super.details}); } diff --git a/lib/service/const/constant.dart b/lib/service/const/constant.dart new file mode 100644 index 0000000..dfe4326 --- /dev/null +++ b/lib/service/const/constant.dart @@ -0,0 +1,46 @@ +/// A utility class that defines constants commonly used in HTTP services. +/// +/// This class centralizes HTTP-related constants, including status codes, +/// default headers, error messages, and common HTTP error descriptions. +class ServiceConst { + /// HTTP status code for "Not Found". + static const int notFoundStatusCode = 404; + + /// HTTP status code for "Success". + static const int successStatucCode = 200; + + /// A default error message for unknown errors. + static const String defaultError = + 'Unknown Error: An unexpected error occurred.'; + + /// Default headers for HTTP POST requests, indicating JSON content. + static const Map defaultPostHeaders = { + 'Content-Type': 'application/json' + }; + + /// A map of common HTTP status codes to their corresponding error messages. + /// + /// Provides detailed descriptions for various client and server-side errors, + /// helping in debugging and user feedback. + static const Map httpErrorMessages = { + 400: + "Bad Request: The server could not understand the request due to invalid syntax.", + 401: "Unauthorized: Authentication is required or has failed.", + 403: "Forbidden: You do not have permission to access this resource.", + 404: "Not Found: The requested resource could not be found.", + 405: + "Method Not Allowed: The HTTP method used is not supported for this resource.", + 409: + "Conflict: The request could not be processed due to a conflict with the current state of the resource.", + 422: + "Unprocessable Entity: The request was well-formed but could not be processed.", + 500: + "Internal Server Error: The server encountered an unexpected condition.", + 502: + "Bad Gateway: The server received an invalid response from the upstream server.", + 503: + "Service Unavailable: The server is temporarily unable to handle the request.", + 504: + "Gateway Timeout: The server did not receive a timely response from the upstream server." + }; +} diff --git a/lib/service/models/params.dart b/lib/service/models/params.dart new file mode 100644 index 0000000..60fb3d5 --- /dev/null +++ b/lib/service/models/params.dart @@ -0,0 +1,128 @@ +import 'package:blockchain_utils/exception/exceptions.dart'; +import 'package:blockchain_utils/service/const/constant.dart'; +import 'package:blockchain_utils/service/utils/utils.dart'; + +/// Enum representing the types of HTTP requests supported by the service. +enum RequestServiceType { + /// Represents an HTTP POST request. + post, + + /// Represents an HTTP GET request. + get; + + /// Checks if the current request type is a POST request. + /// + /// Returns `true` if the request type is `post`, otherwise `false`. + bool get isPostRequest => this == post; +} + +/// Enum representing the types of responses that a service can return. +enum ServiceResponseType { + /// Indicates that the service response is an error. + error, + + /// Indicates that the service response is successful. + success +} + +abstract class BaseServiceResponse { + final int statusCode; + final ServiceResponseType type; + const BaseServiceResponse({required this.statusCode, required this.type}); + E cast() { + if (this is! E) { + throw ArgumentException("BaseServiceResponse casting faild.", + details: {"excepted": "$T", "type": type.name}); + } + return this as E; + } + + T getResult(BaseServiceRequestParams params) { + return switch (type) { + ServiceResponseType.error => throw RPCError( + message: ServiceConst.httpErrorMessages[statusCode] ?? + "Unknown Error${statusCode == 200 ? '' : ' $statusCode'}: An unexpected error occurred.", + errorCode: null, + request: params.toJson(), + details: ServiceProviderUtils.findErrorDetails( + statusCode: statusCode, + object: cast().error)), + ServiceResponseType.success => cast>().response + }; + } +} + +class ServiceSuccessRespose extends BaseServiceResponse { + final T response; + const ServiceSuccessRespose( + {required super.statusCode, required this.response}) + : super(type: ServiceResponseType.success); +} + +class ServiceErrorResponse extends BaseServiceResponse { + final String? error; + const ServiceErrorResponse({required super.statusCode, required this.error}) + : super(type: ServiceResponseType.error); +} + +abstract class BaseServiceRequestParams { + final Map headers; + final RequestServiceType type; + final int requestID; + const BaseServiceRequestParams( + {required this.headers, required this.type, required this.requestID}); + Uri toUri(String uri); + List? body(); + Map toJson(); + BaseServiceResponse toResponse(Object? body, [int? statusCode]) { + statusCode ??= 200; + if (!ServiceProviderUtils.isSuccessStatusCode(statusCode)) { + return ServiceErrorResponse( + statusCode: statusCode, + error: ServiceProviderUtils.findError( + object: body, statusCode: statusCode)); + } + try { + T response; + if (body is List) { + response = ServiceProviderUtils.toResult(body); + } else { + response = + ServiceProviderUtils.parseResponse(object: body, params: this); + } + return ServiceSuccessRespose( + statusCode: statusCode, response: response); + } catch (_) {} + + throw RPCError( + message: "Parsing response failed.", + request: toJson(), + details: {"excepted": "$T"}); + } +} + +abstract class BaseServiceRequest { + const BaseServiceRequest(); + abstract final RequestServiceType requestType; + RESULT onResonse(SERVICERESPONSE result) { + return result as RESULT; + } + + PARAMS buildRequest(int requestID); +} + +abstract class BaseProvider { + Future requestDynamic( + BaseServiceRequest request, + {Duration? timeout}); + + Future request( + BaseServiceRequest request, + {Duration? timeout}); +} + +mixin BaseServiceProvider { + Future> doRequest(PARAMS params, + {Duration? timeout}); +} diff --git a/lib/service/service.dart b/lib/service/service.dart new file mode 100644 index 0000000..e64d7e4 --- /dev/null +++ b/lib/service/service.dart @@ -0,0 +1,3 @@ +export 'models/params.dart'; +export 'const/constant.dart'; +export 'utils/utils.dart'; diff --git a/lib/service/utils/utils.dart b/lib/service/utils/utils.dart new file mode 100644 index 0000000..cbc979e --- /dev/null +++ b/lib/service/utils/utils.dart @@ -0,0 +1,150 @@ +import 'package:blockchain_utils/exception/exceptions.dart'; +import 'package:blockchain_utils/service/models/params.dart'; +import 'package:blockchain_utils/utils/utils.dart'; + +/// A utility class providing helper methods for handling HTTP responses, +/// building JSON-RPC requests, and parsing responses in a service-oriented architecture. +class ServiceProviderUtils { + /// Finds an error message from the response based on the status code and object type. + /// + /// If the status code is `401` or `403` and the object is a list of bytes or a string, + /// it attempts to decode the error message. + /// Returns: A decoded error message if applicable, otherwise `null`. + static String? findError({Object? object, required int statusCode}) { + if (statusCode == 401 || statusCode == 403) { + if (object is List) { + return StringUtils.tryDecode(object); + } else if (object is String) { + return object; + } + } + return null; + } + + /// Extracts detailed error information from the response. + /// + /// Similar to [findError], but includes additional details such as JSON parsing. + /// + /// Returns: A map containing the status code and an error message (if any). + static Map findErrorDetails( + {Object? object, required int statusCode}) { + String? error; + if (statusCode == 401 || statusCode == 403) { + if (object is List) { + error = StringUtils.tryDecode(object); + } else if (object is String) { + error = object; + } else if (object is Map) { + error = StringUtils.tryFromJson(object); + } + } + return {"statusCode": statusCode, if (error != null) "error": error}; + } + + /// Builds a JSON-RPC request object. + /// + /// - [requestId]: The ID of the request. + /// - [method]: The RPC method being called. + /// - [params]: Optional parameters for the RPC call. + /// + /// Returns: A map representing the JSON-RPC request. + static Map buildJsonRPCParams({ + required int requestId, + required String method, + Object? params, + }) { + return { + "jsonrpc": "2.0", + "method": method, + "params": params, + "id": requestId + }; + } + + /// Checks if the given HTTP status code indicates a successful response. + /// + /// - [statusCode]: The HTTP status code to check. + /// + /// Returns: `true` if the status code is in the range 200–299, otherwise `false`. + static bool isSuccessStatusCode(int statusCode) { + return statusCode >= 200 && statusCode < 300; + } + + /// Converts a list of bytes into a result of type `T`. + /// + /// Handles various types of conversions, including JSON decoding, + /// byte lists, and casting to other types. + /// + /// - [bytes]: The response body as a list of bytes. + /// + /// Returns: The parsed response as an object of type `T`. + static T toResult(List bytes) { + if (bytes.isEmpty && null is T) { + return null as T; + } + if (dynamic is T) { + return StringUtils.toJson(StringUtils.decode(bytes)); + } + if ({} is T) { + return StringUtils.toJson(StringUtils.decode(bytes)); + } + if (>[] is T) { + return StringUtils.toJson(StringUtils.decode(bytes)) + .map((e) => (e as Map).cast()) + .toList() as T; + } + if ([] is T) { + return bytes as T; + } + return StringUtils.decode(bytes) as T; + } + + /// Parses a response object into a result of type `T`. + /// + /// Handles various input types, including strings, maps, lists, and bytes, + /// performing necessary conversions or JSON decoding. + /// + /// Throws: [RPCError] if parsing fails. + /// + /// Returns: The parsed response as an object of type `T`. + static T parseResponse( + {required Object? object, required BaseServiceRequestParams params}) { + try { + if (object is T) return object; + if (object == null && null is T) { + return null as T; + } + if (dynamic is T) { + return object as T; + } + if ({} is T) { + if (object is Map) return object.cast() as T; + if (object is String) { + return StringUtils.toJson>(object) as T; + } + } + if (>[] is T) { + if (object is String) { + return StringUtils.toJson(object) + .map((e) => (e as Map).cast()) + .toList() as T; + } + return (object as List) + .map((e) => (e as Map).cast()) + .toList() as T; + } + if ([] is T) { + if (object is List) { + return StringUtils.encode(object as String) as T; + } + return (Object as List).cast() as T; + } + return object as T; + } catch (e) { + throw RPCError( + message: "Parsing response failed.", + request: params.toJson(), + details: {"error": e.toString()}); + } + } +} diff --git a/lib/signer/bitcoin_signer.dart b/lib/signer/bitcoin_signer.dart index a9ea4e0..d98ae2d 100644 --- a/lib/signer/bitcoin_signer.dart +++ b/lib/signer/bitcoin_signer.dart @@ -1,3 +1,4 @@ +import 'package:blockchain_utils/signer/eth/evm_signer.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'; @@ -8,7 +9,7 @@ import 'package:blockchain_utils/crypto/crypto/cdsa/point/base.dart'; import 'package:blockchain_utils/crypto/crypto/cdsa/point/ec_projective_point.dart'; 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/exception/exceptions.dart'; import 'package:blockchain_utils/signer/ecdsa_signing_key.dart'; /// The [BitcoinSignerUtils] class provides utility methods related to Bitcoin signing operations. @@ -89,7 +90,7 @@ class BitcoinSigner { List signMessage(List message, String messagePrefix) { final messgaeHash = QuickCrypto.sha256Hash( BitcoinSignerUtils.magicMessage(message, messagePrefix)); - ECDSASignature ecdsaSign = signingKey.signDigestDeterminstic( + final ECDSASignature ecdsaSign = signingKey.signDigestDeterminstic( digest: messgaeHash, hashFunc: () => SHA256()); final n = BitcoinSignerUtils._order >> 1; BigInt newS; @@ -108,6 +109,19 @@ class BitcoinSigner { return newSignature.toBytes(BitcoinSignerUtils.baselen); } + /// Signs a given transaction digest using the ECDSA deterministic signature scheme. + /// The signature is adjusted for low-S encoding and verified against the public key. + List signBcHTransaction(List digest) { + ECDSASignature ecdsaSign = signingKey.signDigestDeterminstic( + digest: digest, hashFunc: () => SHA256()); + if (ecdsaSign.s > ETHSignerConst.orderHalf) { + ecdsaSign = + ECDSASignature(ecdsaSign.r, ETHSignerConst.curveOrder - ecdsaSign.s); + } + final List signature = BigintUtils.toDer([ecdsaSign.r, ecdsaSign.s]); + return signature; + } + /// Signs a given transaction digest using the ECDSA deterministic signature scheme. /// The signature is adjusted for low-S encoding and verified against the public key. List signTransaction(List digest) { @@ -133,23 +147,23 @@ class BitcoinSigner { lengthR = signature[3]; } - int derPrefix = signature[0]; + final int derPrefix = signature[0]; int lengthTotal = signature[1]; - int derTypeInt = signature[2]; - List R = signature.sublist(4, 4 + lengthR); + final int derTypeInt = signature[2]; + final List R = signature.sublist(4, 4 + lengthR); int lengthS = signature[5 + lengthR]; - List S = signature.sublist(5 + lengthR + 1); + final List S = signature.sublist(5 + lengthR + 1); BigInt sAsBigint = BigintUtils.fromBytes(S); List newS; if (lengthS == 33) { - final newSAsBigint = BitcoinSignerUtils._order - sAsBigint; - newS = - BigintUtils.toBytes(newSAsBigint, length: BitcoinSignerUtils.baselen); + sAsBigint = BitcoinSignerUtils._order - sAsBigint; + newS = BigintUtils.toBytes(sAsBigint, length: BitcoinSignerUtils.baselen); lengthS -= 1; lengthTotal -= 1; } else { newS = S; } + assert(sAsBigint <= ETHSignerConst.orderHalf); signature = List.from([ derPrefix, @@ -172,7 +186,9 @@ class BitcoinSigner { /// Signs a given Schnorr-based transaction digest using the Schnorr signature scheme. List signSchnorrTransaction(List digest, - {required List tapScripts, required bool tweak}) { + {required List tapScripts, + required bool tweak, + List? auxRand}) { if (digest.length != 32) { throw const ArgumentException("The message must be a 32-byte array."); } @@ -186,7 +202,8 @@ class BitcoinSigner { } else { byteKey = signingKey.privateKey.toBytes(); } - final List aux = QuickCrypto.sha256Hash([...digest, ...byteKey]); + final List aux = + auxRand ?? QuickCrypto.sha256Hash([...digest, ...byteKey]); final d0 = BigintUtils.fromBytes(byteKey); if (!(BigInt.one <= d0 && d0 <= BitcoinSignerUtils._order - BigInt.one)) { @@ -275,11 +292,11 @@ class BitcoinVerifier { /// Verifies an ECDSA signature against a given transaction digest. bool verifyTransaction(List digest, List derSignature) { - int lengthR = derSignature[3]; - int lengthS = derSignature[5 + lengthR]; - List rBytes = derSignature.sublist(4, 4 + lengthR); + final int lengthR = derSignature[3]; + final int lengthS = derSignature[5 + lengthR]; + final List rBytes = derSignature.sublist(4, 4 + lengthR); final int sIndex = 4 + lengthR + 2; - List sBytes = derSignature.sublist(sIndex, sIndex + lengthS); + final List sBytes = derSignature.sublist(sIndex, sIndex + lengthS); final signature = ECDSASignature( BigintUtils.fromBytes(rBytes), BigintUtils.fromBytes(sBytes)); return verifyKey.verify(signature, digest); @@ -326,7 +343,7 @@ class BitcoinVerifier { if (P.y.isEven) { e = BitcoinSignerUtils._order - e; } - ProjectiveECCPoint eP = P * e; + final ProjectiveECCPoint eP = P * e; final R = sp + eP; @@ -346,10 +363,10 @@ class BitcoinVerifier { } final List messgaeHash = QuickCrypto.sha256Hash( BitcoinSignerUtils.magicMessage(message, messagePrefix)); - List correctSignature = + final List correctSignature = signature.length == 65 ? signature.sublist(1) : List.from(signature); - List rBytes = correctSignature.sublist(0, 32); - List sBytes = correctSignature.sublist(32); + final List rBytes = correctSignature.sublist(0, 32); + final List sBytes = correctSignature.sublist(32); final ecdsaSignature = ECDSASignature( BigintUtils.fromBytes(rBytes), BigintUtils.fromBytes(sBytes)); diff --git a/lib/signer/cardano/cardano_signer.dart b/lib/signer/cardano/cardano_signer.dart index 4e4e43c..e87b96a 100644 --- a/lib/signer/cardano/cardano_signer.dart +++ b/lib/signer/cardano/cardano_signer.dart @@ -1,7 +1,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/exception/exceptions.dart'; import 'package:blockchain_utils/utils/numbers/numbers.dart'; /// Constants used by the Solana signer for cryptographic operations. diff --git a/lib/signer/cosmos/cosmos.dart b/lib/signer/cosmos/cosmos.dart new file mode 100644 index 0000000..42248ff --- /dev/null +++ b/lib/signer/cosmos/cosmos.dart @@ -0,0 +1,4 @@ +export 'signers/cosmos_ed25519_signer.dart'; +export 'signers/cosmos_eth_sec256k1_signer.dart'; +export 'signers/cosmos_nist256r1_signer.dart'; +export 'signers/cosmos_secp256k1_signer.dart'; diff --git a/lib/signer/cosmos/signers/cosmos_ed25519_signer.dart b/lib/signer/cosmos/signers/cosmos_ed25519_signer.dart new file mode 100644 index 0000000..eb49032 --- /dev/null +++ b/lib/signer/cosmos/signers/cosmos_ed25519_signer.dart @@ -0,0 +1,4 @@ +import 'package:blockchain_utils/signer/solana/solana_signer.dart'; + +typedef CosmosED25519Signer = SolanaSigner; +typedef CosmosED25519Verifier = SolanaVerifier; diff --git a/lib/signer/cosmos/signers/cosmos_eth_sec256k1_signer.dart b/lib/signer/cosmos/signers/cosmos_eth_sec256k1_signer.dart new file mode 100644 index 0000000..b0616f6 --- /dev/null +++ b/lib/signer/cosmos/signers/cosmos_eth_sec256k1_signer.dart @@ -0,0 +1,71 @@ +import 'package:blockchain_utils/signer/eth/evm_signer.dart'; + +/// Ethereum Signer class for cryptographic operations, including signing and verification. +/// +/// The `CosmosETHSecp256k1Signer` class facilitates the creation of Ethereum signatures and +/// provides methods for signing messages, personal messages, and converting to +/// verification keys. It uses the ECDSA (Elliptic Curve Digital Signature Algorithm) +/// for cryptographic operations on the secp256k1 elliptic curve. +class CosmosETHSecp256k1Signer { + const CosmosETHSecp256k1Signer._(this._signer); + + final ETHSigner _signer; + + /// Factory method to create an CosmosETHSecp256k1Signer from a byte representation of a private key. + factory CosmosETHSecp256k1Signer.fromKeyBytes(List keyBytes) { + return CosmosETHSecp256k1Signer._(ETHSigner.fromKeyBytes(keyBytes)); + } + + /// Signs a personal message digest with an optional payload length. + /// + /// The Ethereum personal sign prefix is applied to the message, and the resulting + /// signature is returned as a byte list. Optionally, a payload length can be provided. + /// + /// Parameters: + /// - [digest]: The personal message digest to be signed. + /// - [payloadLength]: An optional payload length to include in the message prefix. + /// + /// Returns: + /// - A byte list representing the signature of the personal message. + List sign(List digest, {bool hashMessage = true}) { + return _signer.sign(digest, hashMessage: hashMessage).toBytes(false); + } + + /// Converts the CosmosETHSecp256k1Signer to an CosmosETHSecp256k1Verifier for verification purposes. + /// + /// Returns: + /// - An CosmosETHSecp256k1Verifier representing the verification key. + CosmosETHSecp256k1Verifier toVerifyKey() { + return CosmosETHSecp256k1Verifier._(_signer.toVerifyKey()); + } +} + +/// Ethereum Verifier class for cryptographic operations, including signature verification. +/// +/// The `CosmosETHSecp256k1Verifier` class allows the verification of Ethereum signatures and +/// public keys. It uses the ECDSA (Elliptic Curve Digital Signature Algorithm) +/// for cryptographic operations on the secp256k1 elliptic curve. +class CosmosETHSecp256k1Verifier { + final ETHVerifier _verifier; + + CosmosETHSecp256k1Verifier._(this._verifier); + + /// Factory method to create an CosmosETHSecp256k1Verifier from a byte representation of a public key. + factory CosmosETHSecp256k1Verifier.fromKeyBytes(List keyBytes) { + return CosmosETHSecp256k1Verifier._(ETHVerifier.fromKeyBytes(keyBytes)); + } + + /// Verifies an Ethereum signature against a message digest. + /// + /// Parameters: + /// - [digest]: The message digest. + /// - [signature]: The signature bytes. + /// - [hashMessage]: Whether to hash the message before verification (default is true). + /// + /// Returns: + /// - True if the signature is valid, false otherwise. + bool verify(List digest, List signature, + {bool hashMessage = true}) { + return _verifier.verify(digest, signature, hashMessage: hashMessage); + } +} diff --git a/lib/signer/cosmos/cosmos_nist256r1_signer.dart b/lib/signer/cosmos/signers/cosmos_nist256r1_signer.dart similarity index 98% rename from lib/signer/cosmos/cosmos_nist256r1_signer.dart rename to lib/signer/cosmos/signers/cosmos_nist256r1_signer.dart index 74cfc2c..980b876 100644 --- a/lib/signer/cosmos/cosmos_nist256r1_signer.dart +++ b/lib/signer/cosmos/signers/cosmos_nist256r1_signer.dart @@ -1,7 +1,7 @@ import 'package:blockchain_utils/crypto/crypto/cdsa/cdsa.dart'; 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/exception/exceptions.dart'; import 'package:blockchain_utils/signer/ecdsa_signing_key.dart'; class _NistSignerConst { diff --git a/lib/signer/cosmos/cosmos_signer.dart b/lib/signer/cosmos/signers/cosmos_secp256k1_signer.dart similarity index 87% rename from lib/signer/cosmos/cosmos_signer.dart rename to lib/signer/cosmos/signers/cosmos_secp256k1_signer.dart index 2e70c02..b79e9f7 100644 --- a/lib/signer/cosmos/cosmos_signer.dart +++ b/lib/signer/cosmos/signers/cosmos_secp256k1_signer.dart @@ -1,26 +1,26 @@ import 'package:blockchain_utils/crypto/crypto/cdsa/cdsa.dart'; 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/exception/exceptions.dart'; import 'package:blockchain_utils/signer/ecdsa_signing_key.dart'; import 'package:blockchain_utils/signer/eth/evm_signer.dart'; /// Cosmos Signer class for cryptographic operations, including signing and verification. /// -/// The [CosmosSigner] class facilitates the creation of Cosmos signatures and +/// The [CosmosSecp256k1Signer] class facilitates the creation of Cosmos signatures and /// provides methods for signing messages, personal messages, and converting to /// verification keys. It uses the ECDSA (Elliptic Curve Digital Signature Algorithm) /// for cryptographic operations on the secp256k1 elliptic curve. -class CosmosSigner { - const CosmosSigner._(this._ecdsaSigningKey); +class CosmosSecp256k1Signer { + const CosmosSecp256k1Signer._(this._ecdsaSigningKey); final EcdsaSigningKey _ecdsaSigningKey; - /// Factory method to create a [CosmosSigner] from a byte representation of a private key. - factory CosmosSigner.fromKeyBytes(List keyBytes) { + /// Factory method to create a [CosmosSecp256k1Signer] from a byte representation of a private key. + factory CosmosSecp256k1Signer.fromKeyBytes(List keyBytes) { final signingKey = ECDSAPrivateKey.fromBytes(keyBytes, ETHSignerConst.secp256); - return CosmosSigner._(EcdsaSigningKey(signingKey)); + return CosmosSecp256k1Signer._(EcdsaSigningKey(signingKey)); } List _signEcdsa(List digest, {bool hashMessage = true}) { @@ -62,7 +62,7 @@ class CosmosSigner { return _signEcdsa(digest, hashMessage: hashMessage); } - /// Converts the [CosmosSigner] to a [CosmosVerifier] for verification purposes. + /// Converts the [CosmosSecp256k1Signer] to a [CosmosVerifier] for verification purposes. /// /// Returns: /// - A [CosmosVerifier] representing the verification key. diff --git a/lib/signer/ecdsa_signing_key.dart b/lib/signer/ecdsa_signing_key.dart index 476aff4..15be3a2 100644 --- a/lib/signer/ecdsa_signing_key.dart +++ b/lib/signer/ecdsa_signing_key.dart @@ -6,7 +6,7 @@ import 'package:blockchain_utils/crypto/crypto/cdsa/rfc6979/rfc6979.dart'; import 'package:blockchain_utils/crypto/crypto/hash/hash.dart'; import 'package:blockchain_utils/utils/utils.dart'; import 'dart:math' as math; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// The [EcdsaSigningKey] class represents a key pair for ECDSA (Elliptic Curve Digital Signature Algorithm) signing. /// It encapsulates the private key and provides methods for signing digests and generating deterministic signatures. @@ -38,8 +38,8 @@ class EcdsaSigningKey { BigInt toBig = BigintUtils.fromBytes(digest); if (truncate) { - int maxLength = toBig.bitLength; - int digestLen = digestBytes.length * 8; + final int maxLength = toBig.bitLength; + final int digestLen = digestBytes.length * 8; toBig >>= math.max(0, digestLen - maxLength); } diff --git a/lib/signer/eth/eth_signature.dart b/lib/signer/eth/eth_signature.dart index 99ed89c..8f24439 100644 --- a/lib/signer/eth/eth_signature.dart +++ b/lib/signer/eth/eth_signature.dart @@ -1,5 +1,5 @@ import 'package:blockchain_utils/utils/utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/signer/eth/evm_signer.dart'; /// Utility class for Ethereum signature operations. @@ -107,6 +107,10 @@ class ETHSignature { return [...rBytes, ...sBytes, !eip155 ? v - 27 : v]; } + List ecdsaBytes() { + return [...rBytes, ...sBytes]; + } + /// Gets the hexadecimal representation of the 'r', 's', and 'v' components. /// /// Optionally adjusts 'v' according to EIP-155. diff --git a/lib/signer/eth/evm_signer.dart b/lib/signer/eth/evm_signer.dart index d831039..6a53ef2 100644 --- a/lib/signer/eth/evm_signer.dart +++ b/lib/signer/eth/evm_signer.dart @@ -175,7 +175,7 @@ class ETHVerifier { /// - True if the signature is valid, false otherwise. bool verifyPersonalMessage(List message, List signature, {bool hashMessage = true, int? payloadLength}) { - List messagaeHash = _hashMessage(message, + final List messagaeHash = _hashMessage(message, hashMessage: hashMessage, payloadLength: payloadLength); return _verifyEcdsa( messagaeHash, signature.sublist(0, ETHSignerConst.ethSignatureLength)); @@ -205,7 +205,7 @@ class ETHVerifier { /// - The recovered ECDSAPublicKey. static ECDSAPublicKey? getPublicKey(List message, List signature, {bool hashMessage = true, int? payloadLength}) { - List messagaeHash = _hashMessage(message, + final List messagaeHash = _hashMessage(message, hashMessage: hashMessage, payloadLength: payloadLength); final ethSignature = ETHSignature.fromBytes(signature); final toBytes = ethSignature.toBytes(false); diff --git a/lib/signer/signer.dart b/lib/signer/signer.dart index fa251b2..c46ed1b 100644 --- a/lib/signer/signer.dart +++ b/lib/signer/signer.dart @@ -6,3 +6,4 @@ export 'tron/tron_signer.dart'; export 'solana/solana_signer.dart'; export 'cardano/cardano_signer.dart'; export 'substrate/substrate.dart'; +export 'cosmos/cosmos.dart'; diff --git a/lib/signer/substrate/core/signer.dart b/lib/signer/substrate/core/signer.dart index 9d2eba2..50579cf 100644 --- a/lib/signer/substrate/core/signer.dart +++ b/lib/signer/substrate/core/signer.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; import 'package:blockchain_utils/bip/substrate/substrate.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.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 5bd17f0..854312e 100644 --- a/lib/signer/substrate/core/verifier.dart +++ b/lib/signer/substrate/core/verifier.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bip/ecc/curve/elliptic_curve_types.dart'; import 'package:blockchain_utils/bip/substrate/substrate.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.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 4ad33da..0340b15 100644 --- a/lib/signer/substrate/signers/substrate_ecdsa.dart +++ b/lib/signer/substrate/signers/substrate_ecdsa.dart @@ -176,7 +176,7 @@ class SubstrateEcdsaVerifier implements BaseSubstrateVerifier { /// - True if the signature is valid, false otherwise. bool verifyPersonalMessage(List message, List signature, {bool hashMessage = true, int? payloadLength}) { - List messagaeHash = _hashMessage(message, + final List messagaeHash = _hashMessage(message, hashMessage: hashMessage, payloadLength: payloadLength); return _verifyEcdsa( messagaeHash, signature.sublist(0, ETHSignerConst.ethSignatureLength)); @@ -206,7 +206,7 @@ class SubstrateEcdsaVerifier implements BaseSubstrateVerifier { /// - The recovered ECDSAPublicKey. static ECDSAPublicKey? getPublicKey(List message, List signature, {bool hashMessage = true, int? payloadLength}) { - List messagaeHash = _hashMessage(message, + final List messagaeHash = _hashMessage(message, hashMessage: hashMessage, payloadLength: payloadLength); final ethSignature = ETHSignature.fromBytes(signature); final toBytes = ethSignature.toBytes(false); diff --git a/lib/signer/substrate/signers/substrate_eddsa.dart b/lib/signer/substrate/signers/substrate_eddsa.dart index b29c7e8..5fa77d4 100644 --- a/lib/signer/substrate/signers/substrate_eddsa.dart +++ b/lib/signer/substrate/signers/substrate_eddsa.dart @@ -1,5 +1,5 @@ import 'package:blockchain_utils/crypto/quick_crypto.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.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'; diff --git a/lib/signer/substrate/signers/substrate_sr25519.dart b/lib/signer/substrate/signers/substrate_sr25519.dart index d0b8546..80d357e 100644 --- a/lib/signer/substrate/signers/substrate_sr25519.dart +++ b/lib/signer/substrate/signers/substrate_sr25519.dart @@ -1,5 +1,5 @@ import 'package:blockchain_utils/crypto/crypto/crypto.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/signer/substrate/core/signer.dart'; import 'package:blockchain_utils/signer/substrate/core/verifier.dart'; diff --git a/lib/signer/tron/tron_signer.dart b/lib/signer/tron/tron_signer.dart index c6ae4ee..0c5bd4f 100644 --- a/lib/signer/tron/tron_signer.dart +++ b/lib/signer/tron/tron_signer.dart @@ -1,6 +1,6 @@ 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/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/signer/eth/evm_signer.dart'; diff --git a/lib/signer/xrp_signer.dart b/lib/signer/xrp_signer.dart index 6f0e7e9..eb28caf 100644 --- a/lib/signer/xrp_signer.dart +++ b/lib/signer/xrp_signer.dart @@ -1,7 +1,7 @@ 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/exception/exceptions.dart'; import 'package:blockchain_utils/signer/ecdsa_signing_key.dart'; import 'package:blockchain_utils/utils/utils.dart'; @@ -103,13 +103,13 @@ class XrpSigner { throw ArgumentException( "invalid digest. digest length must be ${_XrpSignerConst.digestLength} got ${digest.length}"); } - ECDSASignature ecdsaSign = _ecdsaSigningKey! + final ECDSASignature ecdsaSign = _ecdsaSigningKey! .signDigestDeterminstic(digest: hash, hashFunc: () => SHA256()); BigInt s = ecdsaSign.s; if (ecdsaSign.s > _XrpSignerConst.orderHalf) { s = _XrpSignerConst.curveOrder - s; } - List derSignature = BigintUtils.toDer([ecdsaSign.r, s]); + final List derSignature = BigintUtils.toDer([ecdsaSign.r, s]); final vr = toVerifyKey(); final verify = vr._verifyEcdsa(hash, derSignature); if (!verify) { @@ -197,12 +197,12 @@ class XrpVerifier { /// [derSignature] The DER-encoded ECDSA signature as a list of bytes. /// returns True if the signature is verified, false otherwise. bool _verifyEcdsa(List digest, List derSignature) { - int lengthR = derSignature[3]; - int lengthS = derSignature[5 + lengthR]; + final int lengthR = derSignature[3]; + final int lengthS = derSignature[5 + lengthR]; - List rBytes = derSignature.sublist(4, 4 + lengthR); + final List rBytes = derSignature.sublist(4, 4 + lengthR); final int sIndex = 4 + lengthR + 2; - List sBytes = derSignature.sublist(sIndex, sIndex + lengthS); + final List sBytes = derSignature.sublist(sIndex, sIndex + lengthS); final r = BigintUtils.fromBytes(rBytes); final s = BigintUtils.fromBytes(sBytes); final signature = ECDSASignature(r, s); diff --git a/lib/ss58/ss58.dart b/lib/ss58/ss58.dart index 6398207..22a75a7 100644 --- a/lib/ss58/ss58.dart +++ b/lib/ss58/ss58.dart @@ -1,5 +1,5 @@ /// Library for SS58 address encoding and decoding. -library ss58; +library; /// Export statement for SS58 address encoding-decoding functionality. export 'ss58_base.dart'; diff --git a/lib/ss58/ss58_base.dart b/lib/ss58/ss58_base.dart index 035e3c4..afa87e4 100644 --- a/lib/ss58/ss58_base.dart +++ b/lib/ss58/ss58_base.dart @@ -2,7 +2,7 @@ import 'dart:typed_data'; import 'package:blockchain_utils/base58/base58_base.dart'; import 'package:blockchain_utils/crypto/quick_crypto.dart'; import 'package:blockchain_utils/utils/utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'ss58_ex.dart'; diff --git a/lib/ss58/ss58_ex.dart b/lib/ss58/ss58_ex.dart index 0210619..64e485b 100644 --- a/lib/ss58/ss58_ex.dart +++ b/lib/ss58/ss58_ex.dart @@ -1,9 +1,8 @@ -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; /// An exception class for errors related to SS58 address checksum validation. /// /// The [message] field can contain additional information about the error. class SS58ChecksumError extends BlockchainUtilsException { - const SS58ChecksumError(String message, {Map? details}) - : super(message, details: details); + const SS58ChecksumError(super.message, {super.details}); } diff --git a/lib/utils/binary/binary_operation.dart b/lib/utils/binary/binary_operation.dart index f254389..b956e3d 100644 --- a/lib/utils/binary/binary_operation.dart +++ b/lib/utils/binary/binary_operation.dart @@ -89,13 +89,13 @@ int add32(int x, int y) => (x + y) & mask32; /// Rotates a 32-bit integer left by a specified number of bits. int rotl32(int val, int shift) { - var modShift = shift & 31; + final modShift = shift & 31; return ((val << modShift) & mask32) | ((val & mask32) >> (32 - modShift)); } /// Rotates a 32-bit integer right by a specified number of bits. int rotr32(int val, int shift) { - var modShift = shift & 31; + final modShift = shift & 31; return ((val >> modShift) & mask32) | ((val & mask32) << (32 - modShift)); } diff --git a/lib/utils/binary/bytes_tracker.dart b/lib/utils/binary/bytes_tracker.dart index 5c4430d..43c3ff5 100644 --- a/lib/utils/binary/bytes_tracker.dart +++ b/lib/utils/binary/bytes_tracker.dart @@ -1,4 +1,4 @@ -import 'utils.dart'; +import 'package:blockchain_utils/helper/helper.dart'; /// A utility class for tracking bytes dynamically. class DynamicByteTracker { @@ -13,6 +13,6 @@ class DynamicByteTracker { } void add(List chunk) { - _buffer.addAll(BytesUtils.toBytes(chunk)); + _buffer.addAll(chunk.asBytes); } } diff --git a/lib/utils/binary/utils.dart b/lib/utils/binary/utils.dart index 4c1f532..77ceefd 100644 --- a/lib/utils/binary/utils.dart +++ b/lib/utils/binary/utils.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.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'; @@ -30,8 +30,9 @@ class BytesUtils { /// Parses a binary string and converts it back to a list of bytes. An optional /// parameter allows padding the result with zeros to achieve a specific byte length. static List fromBinary(String data, {int zeroPadByteLen = 0}) { - BigInt intValue = BigInt.parse(data, radix: 2); - String hexValue = intValue.toRadixString(16).padLeft(zeroPadByteLen, '0'); + final BigInt intValue = BigInt.parse(data, radix: 2); + final String hexValue = + intValue.toRadixString(16).padLeft(zeroPadByteLen, '0'); return fromHexString(hexValue); } @@ -167,6 +168,24 @@ class BytesUtils { } } + static void validateListOfBytes(List bytes, {String? onError}) { + for (int i = 0; i < bytes.length; i++) { + final int byte = bytes[i]; + if (byte < 0 || byte > mask8) { + throw ArgumentError("${onError ?? "Invalid bytes"} at index $i: $byte"); + } + } + } + + static bool isValidBytes(Iterable bytes) { + try { + validateBytes(bytes); + return true; + } catch (e) { + return false; + } + } + /// Compare two Uint8Lists lexicographically. static int compareBytes(List a, List b) { final length = a.length < b.length ? a.length : b.length; diff --git a/lib/utils/compare/hash_code.dart b/lib/utils/compare/hash_code.dart index 1e76aec..1ca5dec 100644 --- a/lib/utils/compare/hash_code.dart +++ b/lib/utils/compare/hash_code.dart @@ -1,23 +1,37 @@ import '../binary/binary_operation.dart'; +/// A utility class for generating consistent and efficient hash codes +/// for collections and objects. class HashCodeGenerator { + /// Generates a hash code for a list of bytes, optionally including + /// additional objects in the calculation. + /// + /// Returns: A 32-bit integer hash code. static int generateBytesHashCode(List bytes, [List optional = const []]) { int hash = 12; - for (var element in bytes) { - hash ^= element; // XOR each element into the hash + for (final element in bytes) { + hash ^= element; hash = (hash * 31) & mask32; } - for (var element in optional) { - hash = (hash ^ element.hashCode) & mask32; + if (optional.isNotEmpty) { + hash = (hash ^ generateHashCode(optional)) & mask32; } return hash; } - static int generateHashCode(List objects) { + /// Generates a hash code for a collection of objects, recursively handling + /// nested iterables. + /// + /// Returns: A 32-bit integer hash code. + static int generateHashCode(Iterable objects) { int hash = 12; - for (var element in objects) { - hash = (hash ^ element.hashCode) & mask32; + for (final element in objects) { + if (element is Iterable) { + hash = (hash ^ generateHashCode(element)) & mask32; + } else { + hash = (hash ^ element.hashCode) & mask32; + } } return hash; } diff --git a/lib/utils/numbers/rational/big_rational.dart b/lib/utils/numbers/rational/big_rational.dart index 6709203..a7b0d1a 100644 --- a/lib/utils/numbers/rational/big_rational.dart +++ b/lib/utils/numbers/rational/big_rational.dart @@ -1,4 +1,4 @@ -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:blockchain_utils/utils/numbers/utils/bigint_utils.dart'; class _BigRationalConst { @@ -111,7 +111,7 @@ class BigRational { throw const ArgumentException("Invalid input: too many '.' tokens"); } if (parts.length > 1) { - bool isNegative = parts[0][0] == '-'; + final bool isNegative = parts[0][0] == '-'; if (isNegative) parts[0] = parts[0].substring(1); BigRational intPart = BigRational._(BigInt.parse(parts[0]), _one); final int length = parts[1].length; @@ -239,8 +239,8 @@ class BigRational { /// [other] The divisor BigRational. /// Returns a new BigRational representing the integer division of this BigRational by the given BigRational. BigRational operator ~/(BigRational other) { - BigInt divmod = _truncate; - BigInt rminder = _remainder; + final BigInt divmod = _truncate; + final BigInt rminder = _remainder; BigInt floor; if (rminder == _zero || !divmod.isNegative) { @@ -293,8 +293,8 @@ class BigRational { /// /// Returns a new BigRational representing the ceiling of this BigRational. BigRational ceil(toBigInt) { - BigInt divmod = _truncate; - BigInt remind = _remainder; + final BigInt divmod = _truncate; + final BigInt remind = _remainder; BigInt ceil; if (remind == _zero || divmod.isNegative) { @@ -350,8 +350,8 @@ class BigRational { static BigRational _reduce(BigInt n, BigInt d) { final BigInt divisor = _gcd(n, d); - BigInt num = n ~/ divisor; - BigInt denom = d ~/ divisor; + final BigInt num = n ~/ divisor; + final BigInt denom = d ~/ divisor; if (denom.isNegative) { return BigRational._(-num, -denom); } diff --git a/lib/utils/numbers/utils/bigint_utils.dart b/lib/utils/numbers/utils/bigint_utils.dart index 1f14b53..7c86389 100644 --- a/lib/utils/numbers/utils/bigint_utils.dart +++ b/lib/utils/numbers/utils/bigint_utils.dart @@ -3,7 +3,7 @@ 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/exception/exceptions.dart'; import 'int_utils.dart'; @@ -12,19 +12,19 @@ class BigintUtils { return a.compareTo(b) > 0 ? a : b; } - /// Converts a BigInt 'num' into a List of bytes with a specified 'order'. + /// Converts a BigInt 'num' into a `List` of bytes with a specified 'order'. /// /// This method converts 'num' into a hexadecimal string, ensuring it's at least - /// 'l' bytes long, and then creates a List of bytes from this hexadecimal + /// 'l' bytes long, and then creates a `List` of bytes from this hexadecimal /// string. /// - /// Returns a List containing the bytes of 'num' with a length determined + /// Returns a `List` containing the bytes of 'num' with a length determined /// by 'order'. /// static List bigintToBytesWithPadding(BigInt x, BigInt order) { String hexStr = x.toRadixString(16); - int hexLen = hexStr.length; - int byteLen = (order.bitLength + 7) ~/ 8; + final int hexLen = hexStr.length; + final int byteLen = (order.bitLength + 7) ~/ 8; if (hexLen < byteLen * 2) { hexStr = '0' * (byteLen * 2 - hexLen) + hexStr; @@ -45,7 +45,7 @@ class BigintUtils { /// to ensure it doesn't exceed 'qlen' bits in length. /// /// Parameters: - /// - data: A List containing the bits to be converted. + /// - data: A `List` containing the bits to be converted. /// - qlen: The maximum bit length for the resulting integer. /// /// Returns: @@ -60,8 +60,8 @@ class BigintUtils { /// Note: The method assumes that 'data' is big-endian (most significant bits first). /// Any padding bits will be removed as needed to match 'qlen'. static BigInt bitsToBigIntWithLengthLimit(List data, int qlen) { - BigInt x = BigInt.parse(BytesUtils.toHexString(data), radix: 16); - int l = data.length * 8; + final BigInt x = BigInt.parse(BytesUtils.toHexString(data), radix: 16); + final int l = data.length * 8; if (l > qlen) { return (x >> (l - qlen)); @@ -78,11 +78,11 @@ class BigintUtils { /// to match the length of 'order' in octets. /// /// Parameters: - /// - data: A List containing the bits to be converted. + /// - data: A `List` containing the bits to be converted. /// - order: A BigInt representing the order of a cryptographic curve. /// /// Returns: - /// - List: A byte array representing the converted bits as octets. + /// - `List`: A byte array representing the converted bits as octets. /// /// Details: /// - The method first converts the binary data to a BigInt 'z1'. @@ -91,7 +91,7 @@ class BigintUtils { /// - Finally, 'z2' is converted to a byte array with padding to match the length /// of 'order' in octets. The output is a byte array suitable for cryptographic use. static List bitsToOctetsWithOrderPadding(List data, BigInt order) { - BigInt z1 = bitsToBigIntWithLengthLimit(data, order.bitLength); + final BigInt z1 = bitsToBigIntWithLengthLimit(data, order.bitLength); BigInt z2 = z1 - order; if (z2 < BigInt.zero) { z2 = z1; @@ -108,8 +108,8 @@ class BigintUtils { /// Returns the number of bytes required to represent 'order'. /// static int orderLen(BigInt value) { - String hexOrder = value.toRadixString(16); - int byteLength = (hexOrder.length + 1) ~/ 2; // Calculate bytes needed + final String hexOrder = value.toRadixString(16); + final int byteLength = (hexOrder.length + 1) ~/ 2; // Calculate bytes needed return byteLength; } @@ -133,9 +133,9 @@ class BigintUtils { while (low > BigInt.one) { // Continue the Euclidean algorithm until 'low' becomes 1. - BigInt r = high ~/ low; - BigInt nm = hm - lm * r; - BigInt newLow = high - low * r; + final BigInt r = high ~/ low; + final BigInt nm = hm - lm * r; + final BigInt newLow = high - low * r; hm = lm; high = low; lm = nm; @@ -153,7 +153,7 @@ class BigintUtils { /// Returns: /// - A list of BigInt values representing the NAF of the input integer. static List computeNAF(BigInt mult) { - List nafList = []; + final List nafList = []; while (mult != BigInt.zero) { if (mult.isOdd) { @@ -191,7 +191,7 @@ class BigintUtils { /// /// This method is useful for converting BigInt values to binary strings for various applications. static String toBinary(BigInt value, int zeroPadBitLen) { - String binaryStr = value.toRadixString(2); + final String binaryStr = value.toRadixString(2); if (zeroPadBitLen > 0) { return binaryStr.padLeft(zeroPadBitLen, '0'); } else { @@ -232,7 +232,7 @@ class BigintUtils { /// Example Usage: /// ```dart /// BigInt value = BigInt.from(16909060); - /// List byteList = BigIntUtils.toBytes(value, length: 4); // Result: [0x01, 0x02, 0x03, 0x04] + /// `List` byteList = BigIntUtils.toBytes(value, length: 4); // Result: [0x01, 0x02, 0x03, 0x04] /// ``` /// /// Parameters: @@ -245,7 +245,7 @@ class BigintUtils { if (val == BigInt.zero) { return List.filled(length, 0); } - BigInt bigMaskEight = BigInt.from(0xff); + final BigInt bigMaskEight = BigInt.from(0xff); List byteList = List.filled(length, 0); for (var i = 0; i < length; i++) { byteList[length - i - 1] = (val & bigMaskEight).toInt(); @@ -269,7 +269,7 @@ class BigintUtils { /// /// Example Usage: /// ```dart - /// List bytes = [0x01, 0x02, 0x03, 0x04]; + /// `List` bytes = [0x01, 0x02, 0x03, 0x04]; /// BigInt result = BigIntUtils.fromBytes(bytes); // Result: 16909060 /// ``` /// @@ -304,24 +304,23 @@ class BigintUtils { /// Example Usage: /// ```dart /// List values = [BigInt.from(123), BigInt.from(456)]; - /// List derBytes = DEREncoding.toDer(values); + /// `List` derBytes = DEREncoding.toDer(values); /// ``` /// /// Parameters: /// - [bigIntList]: The list of BigInt values to be DER-encoded. /// Returns: A list of bytes representing the DER-encoded sequence of integers. static List toDer(List bigIntList) { - List> encodedIntegers = bigIntList.map((bi) { - List bytes = _encodeInteger(bi); + final List> encodedIntegers = bigIntList.map((bi) { + final List bytes = _encodeInteger(bi); return bytes; }).toList(); - List lengthBytes = + final List lengthBytes = _encodeLength(encodedIntegers.fold(0, (sum, e) => sum + e.length)); - List contentBytes = + final List contentBytes = encodedIntegers.fold>([], (prev, e) => [...prev, ...e]); - _encodeLength(200); - var derBytes = [ + final derBytes = [ 0x30, ...lengthBytes, ...contentBytes, @@ -361,8 +360,8 @@ class BigintUtils { assert(r >= BigInt.zero); final len = BigintUtils.orderLen(r); - List s = BigintUtils.toBytes(r, length: len); - int num = s[0]; + final List s = BigintUtils.toBytes(r, length: len); + final int num = s[0]; if (num <= 0x7F) { return [0x02, ..._encodeLength(s.length), ...s]; } else { @@ -376,7 +375,7 @@ class BigintUtils { /// Parses a dynamic value [v] into a BigInt. /// /// Tries to convert the dynamic value [v] into a BigInt. It supports parsing - /// from BigInt, int, List, and String types. If [v] is a String and + /// from BigInt, int, `List`, and String types. If [v] is a String and /// represents a hexadecimal number (prefixed with '0x' or not), it is parsed /// accordingly. /// @@ -442,7 +441,7 @@ class BigintUtils { static Tuple variableNatDecode(List bytes) { BigInt output = BigInt.zero; int bytesRead = 0; - for (int byte in bytes) { + for (final byte in bytes) { output = (output << 7) | BigInt.from(byte & 0x7F); if (output > maxU64) { throw const MessageException( diff --git a/lib/utils/numbers/utils/int_utils.dart b/lib/utils/numbers/utils/int_utils.dart index c5f1b21..a3880d3 100644 --- a/lib/utils/numbers/utils/int_utils.dart +++ b/lib/utils/numbers/utils/int_utils.dart @@ -3,7 +3,7 @@ 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/exception/exceptions.dart'; import 'dart:math' as math; /// Utility class for integer-related operations and conversions. @@ -20,7 +20,7 @@ class IntUtils { /// /// Throws a MessageException if the decoded value cannot fit into an integer in the current environment. static Tuple decodeVarint(List byteint) { - int ni = byteint[0]; + final int ni = byteint[0]; int size = 0; if (ni < 253) { @@ -35,7 +35,7 @@ class IntUtils { size = 8; } - BigInt value = BigintUtils.fromBytes(byteint.sublist(1, 1 + size), + final BigInt value = BigintUtils.fromBytes(byteint.sublist(1, 1 + size), byteOrder: Endian.little); if (!value.isValidInt) { throw const MessageException( @@ -103,8 +103,8 @@ class IntUtils { {required int length, Endian byteOrder = Endian.big}) { assert(length <= 8); if (length > 4) { - int lowerPart = val & mask32; - int upperPart = (val >> 32) & mask32; + final int lowerPart = val & mask32; + final int upperPart = (val >> 32) & mask32; final bytes = [ ...toBytes(upperPart, length: length - 4), @@ -115,7 +115,7 @@ class IntUtils { } return bytes; } - List byteList = List.filled(length, 0); + final List byteList = List.filled(length, 0); for (var i = 0; i < length; i++) { byteList[length - i - 1] = val & mask8; @@ -142,8 +142,9 @@ class IntUtils { } int result = 0; if (bytes.length > 4) { - int lowerPart = fromBytes(bytes.sublist(bytes.length - 4, bytes.length)); - int upperPart = fromBytes(bytes.sublist(0, bytes.length - 4)); + final int lowerPart = + fromBytes(bytes.sublist(bytes.length - 4, bytes.length)); + final int upperPart = fromBytes(bytes.sublist(0, bytes.length - 4)); result = (upperPart << 32) | lowerPart; } else { for (var i = 0; i < bytes.length; i++) { @@ -161,7 +162,7 @@ class IntUtils { /// Parses a dynamic value [v] into an integer. /// /// Tries to convert the dynamic value [v] into an integer. It supports parsing - /// from int, BigInt, List, and String types. If [v] is a String and + /// from int, BigInt, `List`, and String types. If [v] is a String and /// represents a hexadecimal number (prefixed with '0x' or not), it is parsed /// accordingly. /// diff --git a/lib/utils/string/string.dart b/lib/utils/string/string.dart index 87c5fdd..4a6166e 100644 --- a/lib/utils/string/string.dart +++ b/lib/utils/string/string.dart @@ -132,14 +132,16 @@ class StringUtils { /// /// The input [data] is a Map representing the Dart object. static String fromJson(Object data, - {String? indent, bool toStringEncodable = false}) { + {String? indent, + bool toStringEncodable = false, + Object? Function(dynamic)? toEncodable}) { + if (toStringEncodable) { + toEncodable ??= (c) => c.toString(); + } if (indent != null) { - return JsonEncoder.withIndent( - indent, toStringEncodable ? (c) => c.toString() : null) - .convert(data); + return JsonEncoder.withIndent(indent, toEncodable).convert(data); } - return jsonEncode(data, - toEncodable: toStringEncodable ? (c) => c.toString() : null); + return jsonEncode(data, toEncodable: toEncodable); } /// Converts a JSON-encoded string to a Dart object represented as a Map. @@ -168,10 +170,14 @@ class StringUtils { /// /// The input [data] is a Map representing the Dart object. static String? tryFromJson(Object? data, - {String? indent, bool toStringEncodable = false}) { + {String? indent, + bool toStringEncodable = false, + Object? Function(dynamic)? toEncodable}) { try { return fromJson(data!, - indent: indent, toStringEncodable: toStringEncodable); + indent: indent, + toStringEncodable: toStringEncodable, + toEncodable: toEncodable); } catch (e) { return null; } diff --git a/lib/uuid/uuid.dart b/lib/uuid/uuid.dart index 8b87815..a5790aa 100644 --- a/lib/uuid/uuid.dart +++ b/lib/uuid/uuid.dart @@ -6,12 +6,12 @@ /// /// The `UUID` class within this library allows for the generation UUID V4 -library uuid; +library; import 'dart:math' as math; import 'package:blockchain_utils/utils/utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; class UUID { /// Generates a version 4 (random) UUID (Universally Unique Identifier). @@ -63,7 +63,7 @@ class UUID { /// - [uuidString]: The UUID string to convert to a binary buffer. /// /// Returns: - /// A binary buffer (List) representing the UUID. + /// A binary buffer (`List`) representing the UUID. static List toBuffer(String uuidString, {bool validate = true}) { if (validate && !isValidUUIDv4(uuidString)) { throw ArgumentException("invalid uuid string.", @@ -90,7 +90,7 @@ class UUID { /// UUIDv4 string is commonly used to represent unique identifiers. /// /// Parameters: - /// - [buffer]: The binary buffer (List) representing the UUID. + /// - [buffer]: The binary buffer (`List`) representing the UUID. /// /// Returns: /// A UUIDv4 string. diff --git a/pubspec.yaml b/pubspec.yaml index b138ec1..57f682c 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.5.0 +version: 4.0.0 homepage: "https://github.com/mrtnetwork/blockchain_utils" repository: "https://github.com/mrtnetwork/blockchain_utils" Author: mrhaydari.t@gmail.com @@ -12,7 +12,7 @@ topics: - bip environment: - sdk: '>=2.15.0 <4.0.0' + sdk: '>=3.3.0 <4.0.0' dependencies: @@ -20,9 +20,9 @@ dependencies: dev_dependencies: - lints: ^4.0.0 - test: ^1.25.2 - flutter_lints: ^4.0.0 + lints: ^5.0.0 + test: ^1.25.9 + flutter_lints: ^5.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/p2pkh/p2pkh_test.dart b/test/address/p2pkh/p2pkh_test.dart index ada6440..aad13ed 100644 --- a/test/address/p2pkh/p2pkh_test.dart +++ b/test/address/p2pkh/p2pkh_test.dart @@ -1,6 +1,5 @@ -import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; +import 'package:blockchain_utils/blockchain_utils.dart'; import '../../quick_hex.dart'; -import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import 'comperesed_test_vector.dart' show compresedTestVector; diff --git a/test/base58/base58_xmr_test.dart b/test/base58/base58_xmr_test.dart index 3a77268..72a508c 100644 --- a/test/base58/base58_xmr_test.dart +++ b/test/base58/base58_xmr_test.dart @@ -2,7 +2,7 @@ import 'package:blockchain_utils/base58/base58_xmr.dart'; import 'package:blockchain_utils/utils/utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:test/test.dart'; var _testVect = [ diff --git a/test/bech32/bech32_test.dart b/test/bech32/bech32_test.dart index 203171d..fe26e1b 100644 --- a/test/bech32/bech32_test.dart +++ b/test/bech32/bech32_test.dart @@ -1,6 +1,6 @@ import 'package:blockchain_utils/bech32/bech32_base.dart'; import 'package:blockchain_utils/utils/utils.dart'; -import 'package:blockchain_utils/exception/exception.dart'; +import 'package:blockchain_utils/exception/exceptions.dart'; import 'package:test/test.dart'; final List> _testVect = [ diff --git a/test/bip/bip38/bip38_addr_test.dart b/test/bip/bip38/bip38_addr_test.dart index 337149e..d5e8bae 100644 --- a/test/bip/bip38/bip38_addr_test.dart +++ b/test/bip/bip38/bip38_addr_test.dart @@ -1,8 +1,6 @@ // ignore_for_file: depend_on_referenced_packages -import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; -import 'package:blockchain_utils/bip/bip/bip38/bip38_addr.dart'; -import 'package:blockchain_utils/utils/utils.dart'; +import 'package:blockchain_utils/blockchain_utils.dart'; import 'package:test/test.dart'; List> _testVector = [ diff --git a/test/bip/bip38/bip38_ec_test.dart b/test/bip/bip38/bip38_ec_test.dart index f056aa1..f34b613 100644 --- a/test/bip/bip38/bip38_ec_test.dart +++ b/test/bip/bip38/bip38_ec_test.dart @@ -1,7 +1,6 @@ // ignore_for_file: depend_on_referenced_packages -import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; -import 'package:blockchain_utils/bip/bip/bip38/bip38_base.dart'; +import 'package:blockchain_utils/blockchain_utils.dart'; import 'package:test/test.dart'; import '../../quick_hex.dart'; diff --git a/test/bip/bip38/bip38_no_ec_test.dart b/test/bip/bip38/bip38_no_ec_test.dart index dfd8105..e9a24e8 100644 --- a/test/bip/bip38/bip38_no_ec_test.dart +++ b/test/bip/bip38/bip38_no_ec_test.dart @@ -1,7 +1,5 @@ -import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; -import 'package:blockchain_utils/bip/bip/bip38/bip38_base.dart'; -import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; +import 'package:blockchain_utils/blockchain_utils.dart'; List> _testVector = [ { diff --git a/test/cardano/bip32/icarus_test.dart b/test/cardano/bip32/icarus_test.dart index 3b490e3..8963906 100644 --- a/test/cardano/bip32/icarus_test.dart +++ b/test/cardano/bip32/icarus_test.dart @@ -10,39 +10,39 @@ void main() { for (final i in icarusTestVector) { final seed = BytesUtils.fromHexString(i["seed"]); final w = CardanoIcarusBip32.fromSeed(seed); - String public = w.publicKey.toExtended; + final String public = w.publicKey.toExtended; expect(public, i["public"]); - String private = w.privateKey.toExtended; + final String private = w.privateKey.toExtended; expect(private, i["private"]); - String chainCode = w.chainCode.toHex(); + final String chainCode = w.chainCode.toHex(); expect(chainCode, i["chaincode"]); - String finger = w.parentFingerPrint.toHex(); + final String finger = w.parentFingerPrint.toHex(); expect(finger, i["finger_print"]); for (final c in (i["child"] as List)) { final pathIndex = Bip32KeyIndex(c["index"]); CardanoIcarusBip32 child = w.childKey(pathIndex); - String public = child.publicKey.toExtended; + final String public = child.publicKey.toExtended; expect(public, c["public"]); - String private = child.privateKey.toExtended; + final String private = child.privateKey.toExtended; expect(private, c["private"]); - int index = child.index.toInt(); + final int index = child.index.toInt(); expect(index, c["index"]); - String chainCode = child.chainCode.toHex(); + final String chainCode = child.chainCode.toHex(); expect(chainCode, c["chaincode"]); - String finger = child.parentFingerPrint.toHex(); + final String finger = child.parentFingerPrint.toHex(); expect(finger, c["finger_print"]); for (final c2 in (c["child"] as List)) { final pathIndex = Bip32KeyIndex(c2["index"]); child = child.childKey(pathIndex); - String public = child.publicKey.toExtended; + final String public = child.publicKey.toExtended; expect(public, c2["public"]); - String private = child.privateKey.toExtended; + final String private = child.privateKey.toExtended; expect(private, c2["private"]); - int index = child.index.toInt(); + final int index = child.index.toInt(); expect(index, c2["index"]); - String chainCode = child.chainCode.toHex(); + final String chainCode = child.chainCode.toHex(); expect(chainCode, c2["chaincode"]); - String finger = child.parentFingerPrint.toHex(); + final String finger = child.parentFingerPrint.toHex(); expect(finger, c2["finger_print"]); } } diff --git a/test/cardano/bip32/legacy_test.dart b/test/cardano/bip32/legacy_test.dart index 0f608d1..16f14a1 100644 --- a/test/cardano/bip32/legacy_test.dart +++ b/test/cardano/bip32/legacy_test.dart @@ -10,39 +10,39 @@ void main() { for (final i in testVector) { final seed = BytesUtils.fromHexString(i["seed"]); final w = CardanoByronLegacyBip32.fromSeed(seed); - String public = w.publicKey.toExtended; + final String public = w.publicKey.toExtended; expect(public, i["public"]); - String private = w.privateKey.toExtended; + final String private = w.privateKey.toExtended; expect(private, i["private"]); - String chainCode = w.chainCode.toHex(); + final String chainCode = w.chainCode.toHex(); expect(chainCode, i["chaincode"]); - String finger = w.parentFingerPrint.toHex(); + final String finger = w.parentFingerPrint.toHex(); expect(finger, i["finger_print"]); for (final c in (i["child"] as List)) { final pathIndex = Bip32KeyIndex(c["index"]); CardanoByronLegacyBip32 child = w.childKey(pathIndex); - String public = child.publicKey.toExtended; + final String public = child.publicKey.toExtended; expect(public, c["public"]); - String private = child.privateKey.toExtended; + final String private = child.privateKey.toExtended; expect(private, c["private"]); - int index = child.index.toInt(); + final int index = child.index.toInt(); expect(index, c["index"]); - String chainCode = child.chainCode.toHex(); + final String chainCode = child.chainCode.toHex(); expect(chainCode, c["chaincode"]); - String finger = child.parentFingerPrint.toHex(); + final String finger = child.parentFingerPrint.toHex(); expect(finger, c["finger_print"]); for (final c2 in (c["child"] as List)) { final pathIndex = Bip32KeyIndex(c2["index"]); child = child.childKey(pathIndex); - String public = child.publicKey.toExtended; + final String public = child.publicKey.toExtended; expect(public, c2["public"]); - String private = child.privateKey.toExtended; + final String private = child.privateKey.toExtended; expect(private, c2["private"]); - int index = child.index.toInt(); + final int index = child.index.toInt(); expect(index, c2["index"]); - String chainCode = child.chainCode.toHex(); + final String chainCode = child.chainCode.toHex(); expect(chainCode, c2["chaincode"]); - String finger = child.parentFingerPrint.toHex(); + final String finger = child.parentFingerPrint.toHex(); expect(finger, c2["finger_print"]); } } diff --git a/test/cbor_test.dart b/test/cbor_test.dart index ecc8113..042cf6a 100644 --- a/test/cbor_test.dart +++ b/test/cbor_test.dart @@ -17,18 +17,21 @@ void _decodeInt() { const cb = CborIntValue(0); final dec2 = CborObject.fromCbor(cb.encode()); expect(dec2.value, cb.value); + expect(dec2.encode(), cb.encode()); } void _decodeFloat() { final cb = CborFloatValue(2.0); final dec2 = CborObject.fromCbor(cb.encode()); expect(dec2.value, cb.value); + expect(dec2.encode(), cb.encode()); } void _decodeString() { final cb = CborStringValue("mrtnetwork"); final dec = CborObject.fromCbor(cb.encode()); expect(dec.value, cb.value); + expect(dec.encode(), cb.encode()); } void _decodeStringIndefinite() { @@ -37,13 +40,15 @@ void _decodeStringIndefinite() { expect(dec.runtimeType, CborIndefiniteStringValue); dec as CborIndefiniteStringValue; expect(CompareUtils.iterableIsEqual(dec.value, cb.value), true); + expect(dec.encode(), cb.encode()); } void _decodeMap() { final cb = CborMapValue.fixedLength( - {0: "mrtnetwork", BigInt.one: BigInt.two, "metnetwork": "mrtnetwork"}); + {0: "mrtnetwork", BigInt.one: BigInt.two, "mrtnetwork": "mrtnetwork"}); final dec = CborObject.fromCbor(cb.encode()); expect(dec is CborMapValue, true); + expect(dec.encode(), cb.encode()); dec as CborMapValue; final keys = cb.value.keys.map((e) => e).toList(); @@ -61,6 +66,7 @@ void _decodeMapDynamic() { "metnetwork": "mrtnetwork", }); final dec = CborObject.fromCbor(cb.encode()); + expect(dec.encode(), cb.encode()); expect(dec is CborMapValue, true); dec as CborMapValue; @@ -83,6 +89,7 @@ void _decodeList() { ]); final dec = CborObject.fromCbor(cb.encode()); expect(dec is CborListValue, true); + expect(dec.encode(), cb.encode()); dec as CborListValue; final valuesDec = dec.value.map((e) => e.value).toList(); @@ -94,19 +101,129 @@ void _decodeDateTime() { final decode = CborObject.fromCbor(cb.encode()); expect(decode is CborStringDateValue, true); expect(cb.value.difference(decode.value).inMilliseconds, 0); + expect(decode.encode(), cb.encode()); final cb2 = CborEpochFloatValue(DateTime.now()); final decode2 = CborObject.fromCbor(cb2.encode()); expect(decode2 is CborEpochFloatValue, true); expect(cb2.value.difference(decode2.value).inMilliseconds, 0); + expect(decode2.encode(), cb2.encode()); final cb3 = CborEpochIntValue(DateTime.now()); final decode3 = CborObject.fromCbor(cb3.encode()); expect(decode3 is CborEpochIntValue, true); expect(cb3.value.difference(decode3.value).inSeconds, 0); + expect(decode3.encode(), cb3.encode()); +} + +void _nestedList() { + final list = CborListValue.fixedLength([ + 0, + CborListValue.fixedLength([ + 1, + 2, + BigInt.parse("111111111111111111111111110"), + ]), + CborListValue.fixedLength([ + 1, + 2, + BigInt.parse("111111111111111111111111110"), + CborListValue.fixedLength([ + -1, + 2, + BigInt.parse("111111111111111111111111110"), + ]), + false, + false, + false, + true + ]), + CborBytesValue(List.filled(100, 12)), + CborMapValue.fixedLength({ + 1: 1, + "one": "one", + BigInt.two: CborBytesValue(List.filled(19, 31)), + CborListValue.fixedLength([ + -1, + 2, + BigInt.parse("111111111111111111111111110"), + ]): CborListValue.fixedLength([ + -1, + 2, + BigInt.parse("111111111111111111111111110"), + ]) + }), + null, + BigInt.one, + BigInt.two, + "metnetwork", + "mrtnetwork", + CborFloatValue.from16BytesFloat(2.0), + CborFloatValue(-2.0), + CborFloatValue.from64BytesFloat(233333333333.100000) + ]); + final cb = CborTagValue(list, [1, 2, 3]); + final dec = CborObject.fromCbor(cb.encode()); + expect(dec is CborTagValue, true); + expect(dec.encode(), cb.encode()); +} + +void _tag() { + CborObject cborTag = CborTagValue(const CborNullValue(), [1, 2, 3]); + expect(cborTag.encode(), CborObject.fromCbor(cborTag.encode()).encode()); + cborTag = CborTagValue( + CborListValue.fixedLength([ + 1, + 2, + 3, + BigInt.from(-1), + BigInt.from(-2), + BigInt.from(-3), + const CborUriValue("https://github.com/mrtnetwork"), + const CborRegxpValue(r'[A-Za-z0-9+/_-]+'), + const CborMimeValue("image/svg+xml"), + const CborBaseUrlValue("cXdlbHF3amVsa3Fqd2VranFrd2pla2xxd2pla2xxdw==", + CborBase64Types.base64), + const CborBaseUrlValue("cXdlbHF3amVsa3Fqd2VranFrd2pla2xxd2pla2xxdw", + CborBase64Types.base64Url), + "mystrig", + + /// + CborListValue.dynamicLength([ + CborEpochFloatValue(DateTime.now()), + CborDecimalFracValue( + BigInt.from(123123), BigInt.parse("123123123123123")), + CborEpochIntValue(DateTime.now()), + CborTagValue( + CborListValue.fixedLength([ + 1, + CborBytesValue(List.filled(32, 32)), + ]), + [ + 1, + 2, + 3, + ]) + ]), + CborMapValue.fixedLength({ + "key1": 1, + "key2": "2", + "key3": CborBytesValue([3]), + 4: CborStringValue("value 4"), + BigInt.parse("11111111111111111111111111"): 5, + "key6": CborListValue.dynamicLength([1, 2, 3, 4, 5]), + "key7": CborTagValue( + CborMapValue.dynamicLength({"1": "1", "2": "2", 1: 1}), + [100, 1001, 100002]) + }), + ]), + [1, 2, 3]); + expect(cborTag.encode(), CborObject.fromCbor(cborTag.encode()).encode()); } void main() { test("cbor decode", () { + _tag(); + _nestedList(); _decodeInt(); _decodeFloat(); _decodeString(); diff --git a/test/elctrum/v1/v1_test.dart b/test/elctrum/v1/v1_test.dart index 8fef8e8..2732bc5 100644 --- a/test/elctrum/v1/v1_test.dart +++ b/test/elctrum/v1/v1_test.dart @@ -1,12 +1,8 @@ -import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; -import 'package:blockchain_utils/bip/coin_conf/constant/coins_conf.dart'; -import 'package:blockchain_utils/bip/electrum/electrum_v1.dart'; -import 'package:blockchain_utils/bip/wif/wif.dart'; -import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import '../../quick_hex.dart'; import 'test_vectors.dart'; +import 'package:blockchain_utils/blockchain_utils.dart'; void main() { test("electrum v1", () { diff --git a/test/elctrum/v2/v2_test.dart b/test/elctrum/v2/v2_test.dart index 65bc363..c27ed88 100644 --- a/test/elctrum/v2/v2_test.dart +++ b/test/elctrum/v2/v2_test.dart @@ -1,4 +1,7 @@ -import 'package:blockchain_utils/blockchain_utils.dart'; +import 'package:blockchain_utils/bip/coin_conf/constant/coins_conf.dart'; +import 'package:blockchain_utils/bip/electrum/electrum_v2.dart'; +import 'package:blockchain_utils/bip/wif/wif.dart'; +import 'package:blockchain_utils/utils/utils.dart'; import 'package:test/test.dart'; import '../../quick_hex.dart'; diff --git a/test/signer/bitcoin_test.dart b/test/signer/bitcoin_test.dart index ab73b3a..3698c72 100644 --- a/test/signer/bitcoin_test.dart +++ b/test/signer/bitcoin_test.dart @@ -1 +1,70 @@ -void main() {} +import 'package:blockchain_utils/signer/bitcoin_signer.dart'; +import 'package:blockchain_utils/utils/binary/utils.dart'; +import 'package:test/test.dart'; + +void main() { + _schnorr(); +} + +void _schnorr() { + test("schnorr sig", () { + final btcSigner = BitcoinSigner.fromKeyBytes(BytesUtils.fromHexString( + "0000000000000000000000000000000000000000000000000000000000000003")); + final sig = btcSigner.signSchnorrTransaction( + BytesUtils.fromHexString( + "0000000000000000000000000000000000000000000000000000000000000000"), + tapScripts: [], + tweak: false, + auxRand: BytesUtils.fromHexString( + "0000000000000000000000000000000000000000000000000000000000000000")); + expect( + sig, + BytesUtils.fromHexString( + "E907831F80848D1069A5371B402410364BDF1C5F8307B0084C55F1CE2DCA821525F66A4A85EA8B71E482A74F382D2CE5EBEEE8FDB2172F477DF4900D310536C0")); + }); + test("schnorr sig 2", () { + final btcSigner = BitcoinSigner.fromKeyBytes(BytesUtils.fromHexString( + "B7E151628AED2A6ABF7158809CF4F3C762E7160F38B4DA56A784D9045190CFEF")); + final sig = btcSigner.signSchnorrTransaction( + BytesUtils.fromHexString( + "243F6A8885A308D313198A2E03707344A4093822299F31D0082EFA98EC4E6C89"), + tapScripts: [], + tweak: false, + auxRand: BytesUtils.fromHexString( + "0000000000000000000000000000000000000000000000000000000000000001")); + expect( + sig, + BytesUtils.fromHexString( + "6896BD60EEAE296DB48A229FF71DFE071BDE413E6D43F917DC8DCF8C78DE33418906D11AC976ABCCB20B091292BFF4EA897EFCB639EA871CFA95F6DE339E4B0A")); + }); + test("schnorr sig 3", () { + final btcSigner = BitcoinSigner.fromKeyBytes(BytesUtils.fromHexString( + "C90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B14E5C9")); + final sig = btcSigner.signSchnorrTransaction( + BytesUtils.fromHexString( + "7E2D58D8B3BCDF1ABADEC7829054F90DDA9805AAB56C77333024B9D0A508B75C"), + tapScripts: [], + tweak: false, + auxRand: BytesUtils.fromHexString( + "C87AA53824B4D7AE2EB035A2B5BBBCCC080E76CDC6D1692C4B0B62D798E6D906")); + expect( + sig, + BytesUtils.fromHexString( + "5831AAEED7B44BB74E5EAB94BA9D4294C49BCF2A60728D8B4C200F50DD313C1BAB745879A5AD954A72C45A91C3A51D3C7ADEA98D82F8481E0E1E03674A6F3FB7")); + }); + test("schnorr sig 4", () { + final btcSigner = BitcoinSigner.fromKeyBytes(BytesUtils.fromHexString( + "0B432B2677937381AEF05BB02A66ECD012773062CF3FA2549E44F58ED2401710")); + final sig = btcSigner.signSchnorrTransaction( + BytesUtils.fromHexString( + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"), + tapScripts: [], + tweak: false, + auxRand: BytesUtils.fromHexString( + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF")); + expect( + sig, + BytesUtils.fromHexString( + "7EB0509757E246F19449885651611CB965ECC1A187DD51B64FDA1EDC9637D5EC97582B9CB13DB3933705B32BA982AF5AF25FD78881EBB32771FC5922EFC66EA3")); + }); +} diff --git a/test/uuid_test.dart b/test/uuid_test.dart index 5c3c8cc..fb4eb2e 100644 --- a/test/uuid_test.dart +++ b/test/uuid_test.dart @@ -2,10 +2,10 @@ import 'package:blockchain_utils/blockchain_utils.dart'; import 'package:test/test.dart'; void main() { - List buffer1 = List.from( + final List buffer1 = List.from( [174, 91, 168, 91, 107, 15, 78, 26, 181, 132, 151, 91, 160, 7, 157, 152]); - List buffer2 = List.from([ + final List buffer2 = List.from([ 42, 118, 243, @@ -23,9 +23,9 @@ void main() { 219, 178 ]); - List buffer3 = List.from( + final List buffer3 = List.from( [115, 181, 16, 102, 139, 73, 65, 95, 181, 34, 94, 80, 60, 118, 197, 55]); - List buffer4 = List.from([ + final List buffer4 = List.from([ 215, 154, 165, @@ -43,7 +43,7 @@ void main() { 165, 177 ]); - List buffer5 = List.from( + final List buffer5 = List.from( [97, 148, 163, 150, 135, 56, 166, 2, 171, 26, 194, 71, 2, 140, 199, 132]); // Test cases for UUID operations diff --git a/test/wif/wif_test.dart b/test/wif/wif_test.dart index e45f8e1..0f40939 100644 --- a/test/wif/wif_test.dart +++ b/test/wif/wif_test.dart @@ -1,6 +1,5 @@ // ignore_for_file: depend_on_referenced_packages -import 'package:blockchain_utils/bip/address/p2pkh_addr.dart'; import 'package:blockchain_utils/blockchain_utils.dart'; import 'package:test/test.dart'; @@ -10,7 +9,7 @@ final List> _testVector = [ "5e9441950b3918772cc3da1fc6735b7c33f1bbe08a8f1e704be46cb664f7e457", "encode": "5JXwUhNu98kXkyhR8EpvpaTGRjj8JZEP7hWboB5xscgjbgK2zNk", "pub_key_mode": PubKeyModes.uncompressed, - "net_ver": CoinsConf.bitcoinMainNet.params.wifNetVer, + "net_ver": CoinsConf.bitcoinMainNet.params.wifNetVer }, { "key_bytes":