bch clean up linter warnings and unused variables

This commit is contained in:
julian 2022-11-04 13:55:13 -06:00
parent 4dd8ae23c5
commit 039a9a68f6

View file

@ -6,7 +6,7 @@ import 'dart:typed_data';
import 'package:bech32/bech32.dart';
import 'package:bip32/bip32.dart' as bip32;
import 'package:bip39/bip39.dart' as bip39;
import 'package:bitbox/bitbox.dart' as Bitbox;
import 'package:bitbox/bitbox.dart' as bitbox;
import 'package:bitcoindart/bitcoindart.dart';
import 'package:bs58check/bs58check.dart' as bs58check;
import 'package:crypto/crypto.dart';
@ -258,7 +258,7 @@ class BitcoinCashWallet extends CoinServiceAPI {
}
Future<void> updateStoredChainHeight({required int newHeight}) async {
DB.instance.put<dynamic>(
await DB.instance.put<dynamic>(
boxName: walletId, key: "storedChainHeight", value: newHeight);
}
@ -266,8 +266,8 @@ class BitcoinCashWallet extends CoinServiceAPI {
Uint8List? decodeBase58;
Segwit? decodeBech32;
try {
if (Bitbox.Address.detectFormat(address) == 0) {
address = Bitbox.Address.toLegacyAddress(address);
if (bitbox.Address.detectFormat(address) == 0) {
address = bitbox.Address.toLegacyAddress(address);
}
} catch (e, s) {}
try {
@ -609,7 +609,9 @@ class BitcoinCashWallet extends CoinServiceAPI {
// get address tx counts
final counts = await _getBatchTxCount(addresses: txCountCallArgs);
print("Counts $counts");
if (kDebugMode) {
print("Counts $counts");
}
// check and add appropriate addresses
for (int k = 0; k < txCountBatchSize; k++) {
int count = counts["${_id}_$k"]!;
@ -745,31 +747,35 @@ class BitcoinCashWallet extends CoinServiceAPI {
// notify on new incoming transaction
for (final tx in unconfirmedTxnsToNotifyPending) {
if (tx.txType == "Received") {
NotificationApi.showNotification(
title: "Incoming transaction",
body: walletName,
walletId: walletId,
iconAssetName: Assets.svg.iconFor(coin: coin),
date: DateTime.now(),
shouldWatchForUpdates: tx.confirmations < MINIMUM_CONFIRMATIONS,
coinName: coin.name,
txid: tx.txid,
confirmations: tx.confirmations,
requiredConfirmations: MINIMUM_CONFIRMATIONS,
unawaited(
NotificationApi.showNotification(
title: "Incoming transaction",
body: walletName,
walletId: walletId,
iconAssetName: Assets.svg.iconFor(coin: coin),
date: DateTime.now(),
shouldWatchForUpdates: tx.confirmations < MINIMUM_CONFIRMATIONS,
coinName: coin.name,
txid: tx.txid,
confirmations: tx.confirmations,
requiredConfirmations: MINIMUM_CONFIRMATIONS,
),
);
await txTracker.addNotifiedPending(tx.txid);
} else if (tx.txType == "Sent") {
NotificationApi.showNotification(
title: "Sending transaction",
body: walletName,
walletId: walletId,
iconAssetName: Assets.svg.iconFor(coin: coin),
date: DateTime.fromMillisecondsSinceEpoch(tx.timestamp * 1000),
shouldWatchForUpdates: tx.confirmations < MINIMUM_CONFIRMATIONS,
coinName: coin.name,
txid: tx.txid,
confirmations: tx.confirmations,
requiredConfirmations: MINIMUM_CONFIRMATIONS,
unawaited(
NotificationApi.showNotification(
title: "Sending transaction",
body: walletName,
walletId: walletId,
iconAssetName: Assets.svg.iconFor(coin: coin),
date: DateTime.fromMillisecondsSinceEpoch(tx.timestamp * 1000),
shouldWatchForUpdates: tx.confirmations < MINIMUM_CONFIRMATIONS,
coinName: coin.name,
txid: tx.txid,
confirmations: tx.confirmations,
requiredConfirmations: MINIMUM_CONFIRMATIONS,
),
);
await txTracker.addNotifiedPending(tx.txid);
}
@ -778,26 +784,30 @@ class BitcoinCashWallet extends CoinServiceAPI {
// notify on confirmed
for (final tx in unconfirmedTxnsToNotifyConfirmed) {
if (tx.txType == "Received") {
NotificationApi.showNotification(
title: "Incoming transaction confirmed",
body: walletName,
walletId: walletId,
iconAssetName: Assets.svg.iconFor(coin: coin),
date: DateTime.now(),
shouldWatchForUpdates: false,
coinName: coin.name,
unawaited(
NotificationApi.showNotification(
title: "Incoming transaction confirmed",
body: walletName,
walletId: walletId,
iconAssetName: Assets.svg.iconFor(coin: coin),
date: DateTime.now(),
shouldWatchForUpdates: false,
coinName: coin.name,
),
);
await txTracker.addNotifiedConfirmed(tx.txid);
} else if (tx.txType == "Sent") {
NotificationApi.showNotification(
title: "Outgoing transaction confirmed",
body: walletName,
walletId: walletId,
iconAssetName: Assets.svg.iconFor(coin: coin),
date: DateTime.now(),
shouldWatchForUpdates: false,
coinName: coin.name,
unawaited(
NotificationApi.showNotification(
title: "Outgoing transaction confirmed",
body: walletName,
walletId: walletId,
iconAssetName: Assets.svg.iconFor(coin: coin),
date: DateTime.now(),
shouldWatchForUpdates: false,
coinName: coin.name,
),
);
await txTracker.addNotifiedConfirmed(tx.txid);
}
@ -862,7 +872,7 @@ class BitcoinCashWallet extends CoinServiceAPI {
if (currentHeight != storedHeight) {
if (currentHeight != -1) {
// -1 failed to fetch current height
updateStoredChainHeight(newHeight: currentHeight);
await updateStoredChainHeight(newHeight: currentHeight);
}
GlobalEventBus.instance.fire(RefreshPercentChangedEvent(0.2, walletId));
@ -1147,10 +1157,12 @@ class BitcoinCashWallet extends CoinServiceAPI {
bool validateAddress(String address) {
try {
// 0 for bitcoincash: address scheme, 1 for legacy address
final format = Bitbox.Address.detectFormat(address);
print("format $format");
final format = bitbox.Address.detectFormat(address);
if (kDebugMode) {
print("format $format");
}
return true;
} catch (e, s) {
} catch (e) {
return false;
}
}
@ -1226,7 +1238,7 @@ class BitcoinCashWallet extends CoinServiceAPI {
);
if (shouldRefresh) {
refresh();
unawaited(refresh());
}
}
@ -1522,12 +1534,14 @@ class BitcoinCashWallet extends CoinServiceAPI {
break;
}
print("Array key is ${jsonEncode(arrayKey)}");
if (kDebugMode) {
print("Array key is ${jsonEncode(arrayKey)}");
}
final internalChainArray =
DB.instance.get<dynamic>(boxName: walletId, key: arrayKey);
if (derivePathType == DerivePathType.bip44) {
if (Bitbox.Address.detectFormat(internalChainArray.last as String) == 1) {
return Bitbox.Address.toCashAddress(internalChainArray.last as String);
if (bitbox.Address.detectFormat(internalChainArray.last as String) == 1) {
return bitbox.Address.toCashAddress(internalChainArray.last as String);
}
}
return internalChainArray.last as String;
@ -1642,7 +1656,9 @@ class BitcoinCashWallet extends CoinServiceAPI {
batches[batchNumber] = {};
}
final scripthash = _convertToScriptHash(allAddresses[i], _network);
print("SCRIPT_HASH_FOR_ADDRESS ${allAddresses[i]} IS $scripthash");
if (kDebugMode) {
print("SCRIPT_HASH_FOR_ADDRESS ${allAddresses[i]} IS $scripthash");
}
batches[batchNumber]!.addAll({
scripthash: [scripthash]
});
@ -1818,20 +1834,28 @@ class BitcoinCashWallet extends CoinServiceAPI {
}) async {
try {
final Map<String, List<dynamic>> args = {};
print("Address $addresses");
if (kDebugMode) {
print("Address $addresses");
}
for (final entry in addresses.entries) {
args[entry.key] = [_convertToScriptHash(entry.value, _network)];
}
print("Args ${jsonEncode(args)}");
if (kDebugMode) {
print("Args ${jsonEncode(args)}");
}
final response = await electrumXClient.getBatchHistory(args: args);
print("Response ${jsonEncode(response)}");
if (kDebugMode) {
print("Response ${jsonEncode(response)}");
}
final Map<String, int> result = {};
for (final entry in response.entries) {
result[entry.key] = entry.value.length;
}
print("result ${jsonEncode(result)}");
if (kDebugMode) {
print("result ${jsonEncode(result)}");
}
return result;
} catch (e, s) {
Logging.instance.log(
@ -1995,8 +2019,8 @@ class BitcoinCashWallet extends CoinServiceAPI {
/// Returns the scripthash or throws an exception on invalid bch address
String _convertToScriptHash(String bchAddress, NetworkType network) {
try {
if (Bitbox.Address.detectFormat(bchAddress) == 0) {
bchAddress = Bitbox.Address.toLegacyAddress(bchAddress);
if (bitbox.Address.detectFormat(bchAddress) == 0) {
bchAddress = bitbox.Address.toLegacyAddress(bchAddress);
}
final output = Address.addressToOutputScript(bchAddress, network);
final hash = sha256.convert(output.toList(growable: false)).toString();
@ -2073,8 +2097,8 @@ class BitcoinCashWallet extends CoinServiceAPI {
List<String> allAddressesOld = await _fetchAllOwnAddresses();
List<String> allAddresses = [];
for (String address in allAddressesOld) {
if (Bitbox.Address.detectFormat(address) == 1) {
allAddresses.add(Bitbox.Address.toCashAddress(address));
if (bitbox.Address.detectFormat(address) == 1) {
allAddresses.add(bitbox.Address.toCashAddress(address));
} else {
allAddresses.add(address);
}
@ -2085,8 +2109,8 @@ class BitcoinCashWallet extends CoinServiceAPI {
as List<dynamic>;
List<dynamic> changeAddressesP2PKH = [];
for (var address in changeAddressesP2PKHOld) {
if (Bitbox.Address.detectFormat(address as String) == 1) {
changeAddressesP2PKH.add(Bitbox.Address.toCashAddress(address));
if (bitbox.Address.detectFormat(address as String) == 1) {
changeAddressesP2PKH.add(bitbox.Address.toCashAddress(address));
} else {
changeAddressesP2PKH.add(address);
}
@ -2108,21 +2132,26 @@ class BitcoinCashWallet extends CoinServiceAPI {
unconfirmedCachedTransactions
.removeWhere((key, value) => value.confirmedStatus);
print("CACHED_TRANSACTIONS_IS $cachedTransactions");
if (kDebugMode) {
print("CACHED_TRANSACTIONS_IS $cachedTransactions");
}
if (cachedTransactions != null) {
for (final tx in allTxHashes.toList(growable: false)) {
final txHeight = tx["height"] as int;
if (txHeight > 0 &&
txHeight < latestTxnBlockHeight - MINIMUM_CONFIRMATIONS) {
if (unconfirmedCachedTransactions[tx["tx_hash"] as String] == null) {
print(cachedTransactions.findTransaction(tx["tx_hash"] as String));
print(unconfirmedCachedTransactions[tx["tx_hash"] as String]);
if (kDebugMode) {
print(
cachedTransactions.findTransaction(tx["tx_hash"] as String));
print(unconfirmedCachedTransactions[tx["tx_hash"] as String]);
}
final cachedTx =
cachedTransactions.findTransaction(tx["tx_hash"] as String);
if (!(cachedTx != null &&
addressType(address: cachedTx.address) ==
DerivePathType.bip44 &&
Bitbox.Address.detectFormat(cachedTx.address) == 1)) {
bitbox.Address.detectFormat(cachedTx.address) == 1)) {
allTxHashes.remove(tx);
}
}
@ -2782,8 +2811,8 @@ class BitcoinCashWallet extends CoinServiceAPI {
final n = output["n"];
if (n != null && n == utxosToUse[i].vout) {
String address = output["scriptPubKey"]["addresses"][0] as String;
if (Bitbox.Address.detectFormat(address) == 0) {
address = Bitbox.Address.toLegacyAddress(address);
if (bitbox.Address.detectFormat(address) == 0) {
address = bitbox.Address.toLegacyAddress(address);
}
if (!addressTxid.containsKey(address)) {
addressTxid[address] = <String>[];
@ -2814,8 +2843,8 @@ class BitcoinCashWallet extends CoinServiceAPI {
);
for (int i = 0; i < p2pkhLength; i++) {
String address = addressesP2PKH[i];
if (Bitbox.Address.detectFormat(address) == 0) {
address = Bitbox.Address.toLegacyAddress(address);
if (bitbox.Address.detectFormat(address) == 0) {
address = bitbox.Address.toLegacyAddress(address);
}
// receives
@ -2950,36 +2979,36 @@ class BitcoinCashWallet extends CoinServiceAPI {
required List<String> recipients,
required List<int> satoshiAmounts,
}) async {
final builder = Bitbox.Bitbox.transactionBuilder();
final builder = bitbox.Bitbox.transactionBuilder();
// retrieve address' utxos from the rest api
List<Bitbox.Utxo> _utxos =
List<bitbox.Utxo> _utxos =
[]; // await Bitbox.Address.utxo(address) as List<Bitbox.Utxo>;
utxosToUse.forEach((element) {
_utxos.add(Bitbox.Utxo(
for (var element in utxosToUse) {
_utxos.add(bitbox.Utxo(
element.txid,
element.vout,
Bitbox.BitcoinCash.fromSatoshi(element.value),
bitbox.BitcoinCash.fromSatoshi(element.value),
element.value,
0,
MINIMUM_CONFIRMATIONS + 1));
});
Logger.print("bch utxos: ${_utxos}");
}
Logger.print("bch utxos: $_utxos");
// placeholder for input signatures
final signatures = <Map>[];
final List<Map<dynamic, dynamic>> signatures = [];
// placeholder for total input balance
int totalBalance = 0;
// int totalBalance = 0;
// iterate through the list of address _utxos and use them as inputs for the
// withdrawal transaction
_utxos.forEach((Bitbox.Utxo utxo) {
for (var utxo in _utxos) {
// add the utxo as an input for the transaction
builder.addInput(utxo.txid, utxo.vout);
final ec = utxoSigningData[utxo.txid]["keyPair"] as ECPair;
final bitboxEC = Bitbox.ECPair.fromWIF(ec.toWIF());
final bitboxEC = bitbox.ECPair.fromWIF(ec.toWIF());
// add a signature to the list to be used later
signatures.add({
@ -2988,15 +3017,15 @@ class BitcoinCashWallet extends CoinServiceAPI {
"original_amount": utxo.satoshis
});
totalBalance += utxo.satoshis;
});
// totalBalance += utxo.satoshis;
}
// calculate the fee based on number of inputs and one expected output
final fee =
Bitbox.BitcoinCash.getByteCount(signatures.length, recipients.length);
// final fee =
// bitbox.BitcoinCash.getByteCount(signatures.length, recipients.length);
// calculate how much balance will be left over to spend after the fee
final sendAmount = totalBalance - fee;
// final sendAmount = totalBalance - fee;
// add the output based on the address provided in the testing data
for (int i = 0; i < recipients.length; i++) {
@ -3006,12 +3035,12 @@ class BitcoinCashWallet extends CoinServiceAPI {
}
// sign all inputs
signatures.forEach((signature) {
for (var signature in signatures) {
builder.sign(
signature["vin"] as int,
signature["key_pair"] as Bitbox.ECPair,
signature["key_pair"] as bitbox.ECPair,
signature["original_amount"] as int);
});
}
// build the transaction
final tx = builder.build();
@ -3038,7 +3067,7 @@ class BitcoinCashWallet extends CoinServiceAPI {
);
// clear cache
_cachedElectrumXClient.clearSharedTransactionCache(coin: coin);
await _cachedElectrumXClient.clearSharedTransactionCache(coin: coin);
// back up data
await _rescanBackup();