WIP btc and other electrumx based coins tx building/send as well as various small tweaks and fixes

This commit is contained in:
julian 2023-11-08 13:57:38 -06:00
parent 3bd3bb9ee6
commit 36a1795984
22 changed files with 6087 additions and 6365 deletions

View file

@ -12,6 +12,7 @@ import 'dart:async';
import 'dart:io';
import 'dart:math';
import 'package:coinlib_flutter/coinlib_flutter.dart';
import 'package:cw_core/node.dart';
import 'package:cw_core/unspent_coins_info.dart';
import 'package:cw_core/wallet_info.dart';
@ -82,6 +83,9 @@ final openedFromSWBFileStringStateProvider =
// miscellaneous box for later use
void main() async {
WidgetsFlutterBinding.ensureInitialized();
final loadCoinlibFuture = loadCoinlib();
GoogleFonts.config.allowRuntimeFetching = false;
if (Platform.isIOS) {
Util.libraryPath = await getLibraryDirectory();
@ -214,6 +218,8 @@ void main() async {
// overlays: [SystemUiOverlay.bottom]);
await NotificationApi.init();
await loadCoinlibFuture;
await MainDB.instance.initMainDB();
ThemeService.instance.init(MainDB.instance);

View file

@ -21,6 +21,7 @@ import 'package:stackwallet/pages/add_wallet_views/new_wallet_recovery_phrase_wa
import 'package:stackwallet/pages/add_wallet_views/verify_recovery_phrase_view/verify_recovery_phrase_view.dart';
import 'package:stackwallet/pages_desktop_specific/desktop_home_view.dart';
import 'package:stackwallet/pages_desktop_specific/my_stack_view/exit_to_my_stack_button.dart';
import 'package:stackwallet/providers/global/secure_store_provider.dart';
import 'package:stackwallet/providers/providers.dart';
import 'package:stackwallet/themes/stack_colors.dart';
import 'package:stackwallet/utilities/assets.dart';
@ -80,7 +81,9 @@ class _NewWalletRecoveryPhraseViewState
Future<void> delete() async {
await _wallet.exit();
await ref.read(pWallets).deleteWallet(_wallet.walletId);
await ref
.read(pWallets)
.deleteWallet(_wallet.walletId, ref.read(secureStoreProvider));
}
Future<void> _copy() async {

View file

@ -10,6 +10,7 @@
import 'dart:async';
import 'package:bip39/bip39.dart' as bip39;
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';
@ -480,9 +481,40 @@ class _NewWalletRecoveryPhraseWarningViewState
walletId: info.walletId,
);
final failovers = ref
.read(nodeServiceChangeNotifierProvider)
.failoverNodesFor(coin: widget.coin);
int? wordCount;
String? mnemonicPassphrase;
String? mnemonic;
String? privateKey;
// TODO: [prio=high] finish fleshing this out
if (coin.hasMnemonicPassphraseSupport) {
if (ref
.read(pNewWalletOptions.state)
.state !=
null) {
mnemonicPassphrase = ref
.read(pNewWalletOptions.state)
.state!
.mnemonicPassphrase;
wordCount = ref
.read(pNewWalletOptions.state)
.state!
.mnemonicWordsCount;
} else {
wordCount = 12;
mnemonicPassphrase = "";
}
final int strength;
if (wordCount == 12) {
strength = 128;
} else if (wordCount == 24) {
strength = 256;
} else {
throw Exception("Invalid word count");
}
mnemonic = bip39.generateMnemonic(
strength: strength);
}
final wallet = await Wallet.create(
walletInfo: info,
@ -493,30 +525,13 @@ class _NewWalletRecoveryPhraseWarningViewState
nodeServiceChangeNotifierProvider),
prefs:
ref.read(prefsChangeNotifierProvider),
mnemonicPassphrase: mnemonicPassphrase,
mnemonic: mnemonic,
privateKey: privateKey,
);
await wallet.init();
// TODO: [prio=high] finish fleshing this out
// if (coin.hasMnemonicPassphraseSupport &&
// ref
// .read(pNewWalletOptions.state)
// .state !=
// null) {
// await manager.initializeNew((
// mnemonicPassphrase: ref
// .read(pNewWalletOptions.state)
// .state!
// .mnemonicPassphrase,
// wordCount: ref
// .read(pNewWalletOptions.state)
// .state!
// .mnemonicWordsCount,
// ));
// } else {
// await manager.initializeNew(null);
// }
// pop progress dialog
if (mounted) {
Navigator.pop(context);
@ -530,7 +545,7 @@ class _NewWalletRecoveryPhraseWarningViewState
unawaited(Navigator.of(context).pushNamed(
NewWalletRecoveryPhraseView.routeName,
arguments: Tuple2(
wallet.walletId,
wallet,
await (wallet as MnemonicBasedWallet)
.getMnemonicAsWords(),
),

View file

@ -246,7 +246,6 @@ class _RestoreWalletViewState extends ConsumerState<RestoreWalletView> {
name: widget.walletName,
);
bool isRestoring = true;
// show restoring in progress
unawaited(showDialog<dynamic>(
@ -260,6 +259,7 @@ class _RestoreWalletViewState extends ConsumerState<RestoreWalletView> {
await ref.read(pWallets).deleteWallet(
info.walletId,
ref.read(secureStoreProvider),
);
},
);

View file

@ -10,6 +10,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:stackwallet/providers/global/secure_store_provider.dart';
import 'package:stackwallet/providers/providers.dart';
import 'package:stackwallet/themes/stack_colors.dart';
import 'package:stackwallet/utilities/text_styles.dart';
@ -63,7 +64,10 @@ class _RestoreFailedDialogState extends ConsumerState<RestoreFailedDialog> {
style: STextStyles.itemSubtitle12(context),
),
onPressed: () async {
await ref.read(pWallets).deleteWallet(walletId);
await ref.read(pWallets).deleteWallet(
walletId,
ref.read(secureStoreProvider),
);
if (mounted) {
Navigator.of(context).pop();

View file

@ -25,6 +25,7 @@ import 'package:stackwallet/pages/home_view/home_view.dart';
import 'package:stackwallet/pages_desktop_specific/desktop_home_view.dart';
import 'package:stackwallet/pages_desktop_specific/my_stack_view/exit_to_my_stack_button.dart';
import 'package:stackwallet/providers/db/main_db_provider.dart';
import 'package:stackwallet/providers/global/secure_store_provider.dart';
import 'package:stackwallet/providers/providers.dart';
import 'package:stackwallet/themes/stack_colors.dart';
import 'package:stackwallet/utilities/assets.dart';
@ -261,7 +262,10 @@ class _VerifyRecoveryPhraseViewState
Future<void> delete() async {
await _wallet.exit();
await ref.read(pWallets).deleteWallet(_wallet.walletId);
await ref.read(pWallets).deleteWallet(
_wallet.walletId,
ref.read(secureStoreProvider),
);
}
@override

View file

@ -22,9 +22,6 @@ import 'package:stackwallet/pages/settings_views/wallet_settings_view/wallet_net
import 'package:stackwallet/pages/settings_views/wallet_settings_view/wallet_network_settings_view/sub_widgets/rescanning_dialog.dart';
import 'package:stackwallet/providers/providers.dart';
import 'package:stackwallet/route_generator.dart';
import 'package:stackwallet/services/coins/epiccash/epiccash_wallet.dart';
import 'package:stackwallet/services/coins/monero/monero_wallet.dart';
import 'package:stackwallet/services/coins/wownero/wownero_wallet.dart';
import 'package:stackwallet/services/event_bus/events/global/blocks_remaining_event.dart';
import 'package:stackwallet/services/event_bus/events/global/node_connection_status_changed_event.dart';
import 'package:stackwallet/services/event_bus/events/global/refresh_percent_changed_event.dart';
@ -139,8 +136,8 @@ class _WalletNetworkSettingsViewState
try {
final wallet = ref.read(pWallets).getWallet(widget.walletId);
await wallet.recover(isRescan: true
,
await wallet.recover(
isRescan: true,
);
if (mounted) {
@ -310,7 +307,6 @@ class _WalletNetworkSettingsViewState
final coin = ref.watch(pWalletCoin(widget.walletId));
// TODO: [prio=high] sync percent for certain wallets
// if (coin == Coin.monero) {
// double highestPercent =
@ -357,8 +353,7 @@ class _WalletNetworkSettingsViewState
style: STextStyles.navBarTitle(context),
),
actions: [
if (ref.watch(pWalletCoin(widget.walletId)) !=
Coin.epicCash)
if (ref.watch(pWalletCoin(widget.walletId)) != Coin.epicCash)
Padding(
padding: const EdgeInsets.only(
top: 10,
@ -915,14 +910,12 @@ class _WalletNetworkSettingsViewState
popBackToRoute: WalletNetworkSettingsView.routeName,
),
if (isDesktop &&
ref.watch(pWalletCoin(widget.walletId)) !=
Coin.epicCash)
ref.watch(pWalletCoin(widget.walletId)) != Coin.epicCash)
const SizedBox(
height: 32,
),
if (isDesktop &&
ref.watch(pWalletCoin(widget.walletId)) !=
Coin.epicCash)
ref.watch(pWalletCoin(widget.walletId)) != Coin.epicCash)
Padding(
padding: const EdgeInsets.only(
bottom: 12,
@ -939,8 +932,7 @@ class _WalletNetworkSettingsViewState
),
),
if (isDesktop &&
ref.watch(pWalletCoin(widget.walletId)) !=
Coin.epicCash)
ref.watch(pWalletCoin(widget.walletId)) != Coin.epicCash)
RoundedWhiteContainer(
borderColor: isDesktop
? Theme.of(context).extension<StackColors>()!.background

File diff suppressed because it is too large Load diff

View file

@ -15,9 +15,7 @@ import 'package:stackwallet/models/isar/models/isar_models.dart' as isar_models;
import 'package:stackwallet/models/node_model.dart';
import 'package:stackwallet/models/paymint/fee_object_model.dart';
import 'package:stackwallet/services/coins/banano/banano_wallet.dart';
import 'package:stackwallet/services/coins/bitcoin/bitcoin_wallet.dart';
import 'package:stackwallet/services/coins/bitcoincash/bitcoincash_wallet.dart';
import 'package:stackwallet/services/coins/dogecoin/dogecoin_wallet.dart';
import 'package:stackwallet/services/coins/ecash/ecash_wallet.dart';
import 'package:stackwallet/services/coins/epiccash/epiccash_wallet.dart';
import 'package:stackwallet/services/coins/ethereum/ethereum_wallet.dart';
@ -106,15 +104,7 @@ abstract class CoinServiceAPI {
);
case Coin.bitcoin:
return BitcoinWallet(
walletId: walletId,
walletName: walletName,
coin: coin,
secureStore: secureStorageInterface,
client: client,
cachedClient: cachedClient,
tracker: tracker,
);
throw UnimplementedError("moved");
case Coin.litecoin:
return LitecoinWallet(
@ -139,15 +129,7 @@ abstract class CoinServiceAPI {
);
case Coin.bitcoinTestNet:
return BitcoinWallet(
walletId: walletId,
walletName: walletName,
coin: coin,
secureStore: secureStorageInterface,
client: client,
cachedClient: cachedClient,
tracker: tracker,
);
throw UnimplementedError("moved");
case Coin.bitcoincash:
return BitcoinCashWallet(
@ -172,15 +154,7 @@ abstract class CoinServiceAPI {
);
case Coin.dogecoin:
return DogecoinWallet(
walletId: walletId,
walletName: walletName,
coin: coin,
secureStore: secureStorageInterface,
client: client,
cachedClient: cachedClient,
tracker: tracker,
);
throw UnimplementedError("moved");
case Coin.epicCash:
return EpicCashWallet(
@ -277,15 +251,7 @@ abstract class CoinServiceAPI {
secureStore: secureStorageInterface);
case Coin.dogecoinTestNet:
return DogecoinWallet(
walletId: walletId,
walletName: walletName,
coin: coin,
secureStore: secureStorageInterface,
client: client,
cachedClient: cachedClient,
tracker: tracker,
);
throw UnimplementedError("moved");
case Coin.eCash:
return ECashWallet(

File diff suppressed because it is too large Load diff

View file

@ -8,13 +8,19 @@
*
*/
import 'package:flutter_libmonero/monero/monero.dart';
import 'package:flutter_libmonero/wownero/wownero.dart';
import 'package:isar/isar.dart';
import 'package:stackwallet/db/hive/db.dart';
import 'package:stackwallet/db/isar/main_db.dart';
import 'package:stackwallet/services/coins/epiccash/epiccash_wallet.dart';
import 'package:stackwallet/services/node_service.dart';
import 'package:stackwallet/services/notifications_service.dart';
import 'package:stackwallet/services/trade_sent_from_stack_service.dart';
import 'package:stackwallet/services/transaction_notification_tracker.dart';
import 'package:stackwallet/utilities/enums/coin_enum.dart';
import 'package:stackwallet/utilities/enums/sync_type_enum.dart';
import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart';
import 'package:stackwallet/utilities/logger.dart';
import 'package:stackwallet/utilities/prefs.dart';
import 'package:stackwallet/wallets/isar/models/wallet_info.dart';
@ -69,8 +75,75 @@ class Wallets {
_wallets[wallet.walletId] = wallet;
}
Future<void> deleteWallet(String walletId) async {
throw UnimplementedError("Delete wallet unimplemented");
Future<void> deleteWallet(
String walletId,
SecureStorageInterface secureStorage,
) async {
Logging.instance.log(
"deleteWallet called with walletId=$walletId",
level: LogLevel.Warning,
);
final wallet = getWallet(walletId)!;
await secureStorage.delete(key: Wallet.mnemonicKey(walletId: walletId));
await secureStorage.delete(
key: Wallet.mnemonicPassphraseKey(walletId: walletId));
await secureStorage.delete(key: Wallet.privateKeyKey(walletId: walletId));
if (wallet.info.coin == Coin.wownero) {
final wowService =
wownero.createWowneroWalletService(DB.instance.moneroWalletInfoBox);
await wowService.remove(walletId);
Logging.instance
.log("monero wallet: $walletId deleted", level: LogLevel.Info);
} else if (wallet.info.coin == Coin.monero) {
final xmrService =
monero.createMoneroWalletService(DB.instance.moneroWalletInfoBox);
await xmrService.remove(walletId);
Logging.instance
.log("monero wallet: $walletId deleted", level: LogLevel.Info);
} else if (wallet.info.coin == Coin.epicCash) {
final deleteResult = await deleteEpicWallet(
walletId: walletId, secureStore: secureStorage);
Logging.instance.log(
"epic wallet: $walletId deleted with result: $deleteResult",
level: LogLevel.Info);
}
// delete wallet data in main db
await MainDB.instance.deleteWalletBlockchainData(walletId);
await MainDB.instance.deleteAddressLabels(walletId);
await MainDB.instance.deleteTransactionNotes(walletId);
// box data may currently still be read/written to if wallet was refreshing
// when delete was requested so instead of deleting now we mark the wallet
// as needs delete by adding it's id to a list which gets checked on app start
await DB.instance.add<String>(
boxName: DB.boxNameWalletsToDeleteOnStart, value: walletId);
final lookupService = TradeSentFromStackService();
for (final lookup in lookupService.all) {
if (lookup.walletIds.contains(walletId)) {
// update lookup data to reflect deleted wallet
await lookupService.save(
tradeWalletLookup: lookup.copyWith(
walletIds: lookup.walletIds.where((id) => id != walletId).toList(),
),
);
}
}
// delete notifications tied to deleted wallet
for (final notification in NotificationsService.instance.notifications) {
if (notification.walletId == walletId) {
await NotificationsService.instance.delete(notification, false);
}
}
await mainDB.isar.writeTxn(() async {
await mainDB.isar.walletInfo.deleteAllByWalletId([walletId]);
});
}
Future<void> load(Prefs prefs, MainDB mainDB) async {

View file

@ -10,17 +10,8 @@
import 'dart:convert';
import 'package:bitbox/bitbox.dart' as bitbox;
import 'package:bitcoindart/bitcoindart.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter_libepiccash/epic_cash.dart';
import 'package:nanodart/nanodart.dart';
import 'package:stackwallet/services/coins/dogecoin/dogecoin_wallet.dart';
import 'package:stackwallet/services/coins/ecash/ecash_wallet.dart';
import 'package:stackwallet/services/coins/firo/firo_wallet.dart';
import 'package:stackwallet/services/coins/litecoin/litecoin_wallet.dart';
import 'package:stackwallet/services/coins/namecoin/namecoin_wallet.dart';
import 'package:stackwallet/services/coins/particl/particl_wallet.dart';
import 'package:stackwallet/utilities/enums/coin_enum.dart';
import 'package:stackwallet/utilities/logger.dart';
@ -58,94 +49,95 @@ class AddressUtils {
}
static bool validateAddress(String address, Coin coin) {
switch (coin) {
case Coin.bitcoin:
return Address.validateAddress(address, bitcoin);
case Coin.litecoin:
return Address.validateAddress(address, litecoin);
case Coin.bitcoincash:
try {
// 0 for bitcoincash: address scheme, 1 for legacy address
final format = bitbox.Address.detectFormat(address);
if (coin == Coin.bitcoincashTestnet) {
return true;
}
if (format == bitbox.Address.formatCashAddr) {
String addr = address;
if (addr.contains(":")) {
addr = addr.split(":").last;
}
return addr.startsWith("q");
} else {
return address.startsWith("1");
}
} catch (e) {
return false;
}
case Coin.dogecoin:
return Address.validateAddress(address, dogecoin);
case Coin.epicCash:
return validateSendAddress(address) == "1";
case Coin.ethereum:
return true; //TODO - validate ETH address
case Coin.firo:
return Address.validateAddress(address, firoNetwork);
case Coin.eCash:
return Address.validateAddress(address, eCashNetwork);
case Coin.monero:
return RegExp("[a-zA-Z0-9]{95}").hasMatch(address) ||
RegExp("[a-zA-Z0-9]{106}").hasMatch(address);
case Coin.wownero:
return RegExp("[a-zA-Z0-9]{95}").hasMatch(address) ||
RegExp("[a-zA-Z0-9]{106}").hasMatch(address);
case Coin.namecoin:
return Address.validateAddress(address, namecoin, namecoin.bech32!);
case Coin.particl:
return Address.validateAddress(address, particl);
case Coin.stellar:
return RegExp(r"^[G][A-Z0-9]{55}$").hasMatch(address);
case Coin.nano:
return NanoAccounts.isValid(NanoAccountType.NANO, address);
case Coin.banano:
return NanoAccounts.isValid(NanoAccountType.BANANO, address);
case Coin.tezos:
return RegExp(r"^tz[1-9A-HJ-NP-Za-km-z]{34}$").hasMatch(address);
case Coin.bitcoinTestNet:
return Address.validateAddress(address, testnet);
case Coin.litecoinTestNet:
return Address.validateAddress(address, litecointestnet);
case Coin.bitcoincashTestnet:
try {
// 0 for bitcoincash: address scheme, 1 for legacy address
final format = bitbox.Address.detectFormat(address);
if (coin == Coin.bitcoincashTestnet) {
return true;
}
if (format == bitbox.Address.formatCashAddr) {
String addr = address;
if (addr.contains(":")) {
addr = addr.split(":").last;
}
return addr.startsWith("q");
} else {
return address.startsWith("1");
}
} catch (e) {
return false;
}
case Coin.firoTestNet:
return Address.validateAddress(address, firoTestNetwork);
case Coin.dogecoinTestNet:
return Address.validateAddress(address, dogecointestnet);
case Coin.stellarTestnet:
return RegExp(r"^[G][A-Z0-9]{55}$").hasMatch(address);
}
throw Exception("moved");
// switch (coin) {
// case Coin.bitcoin:
// return Address.validateAddress(address, bitcoin);
// case Coin.litecoin:
// return Address.validateAddress(address, litecoin);
// case Coin.bitcoincash:
// try {
// // 0 for bitcoincash: address scheme, 1 for legacy address
// final format = bitbox.Address.detectFormat(address);
//
// if (coin == Coin.bitcoincashTestnet) {
// return true;
// }
//
// if (format == bitbox.Address.formatCashAddr) {
// String addr = address;
// if (addr.contains(":")) {
// addr = addr.split(":").last;
// }
//
// return addr.startsWith("q");
// } else {
// return address.startsWith("1");
// }
// } catch (e) {
// return false;
// }
// case Coin.dogecoin:
// return Address.validateAddress(address, dogecoin);
// case Coin.epicCash:
// return validateSendAddress(address) == "1";
// case Coin.ethereum:
// return true; //TODO - validate ETH address
// case Coin.firo:
// return Address.validateAddress(address, firoNetwork);
// case Coin.eCash:
// return Address.validateAddress(address, eCashNetwork);
// case Coin.monero:
// return RegExp("[a-zA-Z0-9]{95}").hasMatch(address) ||
// RegExp("[a-zA-Z0-9]{106}").hasMatch(address);
// case Coin.wownero:
// return RegExp("[a-zA-Z0-9]{95}").hasMatch(address) ||
// RegExp("[a-zA-Z0-9]{106}").hasMatch(address);
// case Coin.namecoin:
// return Address.validateAddress(address, namecoin, namecoin.bech32!);
// case Coin.particl:
// return Address.validateAddress(address, particl);
// case Coin.stellar:
// return RegExp(r"^[G][A-Z0-9]{55}$").hasMatch(address);
// case Coin.nano:
// return NanoAccounts.isValid(NanoAccountType.NANO, address);
// case Coin.banano:
// return NanoAccounts.isValid(NanoAccountType.BANANO, address);
// case Coin.tezos:
// return RegExp(r"^tz[1-9A-HJ-NP-Za-km-z]{34}$").hasMatch(address);
// case Coin.bitcoinTestNet:
// return Address.validateAddress(address, testnet);
// case Coin.litecoinTestNet:
// return Address.validateAddress(address, litecointestnet);
// case Coin.bitcoincashTestnet:
// try {
// // 0 for bitcoincash: address scheme, 1 for legacy address
// final format = bitbox.Address.detectFormat(address);
//
// if (coin == Coin.bitcoincashTestnet) {
// return true;
// }
//
// if (format == bitbox.Address.formatCashAddr) {
// String addr = address;
// if (addr.contains(":")) {
// addr = addr.split(":").last;
// }
//
// return addr.startsWith("q");
// } else {
// return address.startsWith("1");
// }
// } catch (e) {
// return false;
// }
// case Coin.firoTestNet:
// return Address.validateAddress(address, firoTestNetwork);
// case Coin.dogecoinTestNet:
// return Address.validateAddress(address, dogecointestnet);
// case Coin.stellarTestnet:
// return RegExp(r"^[G][A-Z0-9]{55}$").hasMatch(address);
// }
}
/// parse an address uri

View file

@ -10,8 +10,6 @@
import 'package:stackwallet/services/coins/bitcoincash/bitcoincash_wallet.dart'
as bch;
import 'package:stackwallet/services/coins/dogecoin/dogecoin_wallet.dart'
as doge;
import 'package:stackwallet/services/coins/ecash/ecash_wallet.dart' as ecash;
import 'package:stackwallet/services/coins/epiccash/epiccash_wallet.dart'
as epic;
@ -393,7 +391,7 @@ extension CoinExt on Coin {
case Coin.dogecoin:
case Coin.dogecoinTestNet:
return doge.MINIMUM_CONFIRMATIONS;
throw UnimplementedError("moved");
case Coin.epicCash:
return epic.MINIMUM_CONFIRMATIONS;

View file

@ -6,7 +6,7 @@ import 'package:stackwallet/utilities/enums/coin_enum.dart';
import 'package:stackwallet/wallets/isar/models/wallet_info.dart';
import 'package:stackwallet/wallets/isar/providers/util/watcher.dart';
final _wiProvider = ChangeNotifierProvider.autoDispose.family<Watcher, String>(
final _wiProvider = ChangeNotifierProvider.family<Watcher, String>(
(ref, walletId) {
final collection = ref.watch(mainDBProvider).isar.walletInfo;
@ -21,55 +21,55 @@ final _wiProvider = ChangeNotifierProvider.autoDispose.family<Watcher, String>(
},
);
final pWalletInfo = Provider.autoDispose.family<WalletInfo, String>(
final pWalletInfo = Provider.family<WalletInfo, String>(
(ref, walletId) {
return ref.watch(_wiProvider(walletId)).value as WalletInfo;
},
);
final pWalletCoin = Provider.autoDispose.family<Coin, String>(
final pWalletCoin = Provider.family<Coin, String>(
(ref, walletId) {
return ref.watch(_wiProvider(walletId)
.select((value) => (value.value as WalletInfo).coin));
},
);
final pWalletBalance = Provider.autoDispose.family<Balance, String>(
final pWalletBalance = Provider.family<Balance, String>(
(ref, walletId) {
return ref.watch(_wiProvider(walletId)
.select((value) => (value.value as WalletInfo).cachedBalance));
},
);
final pWalletBalanceSecondary = Provider.autoDispose.family<Balance, String>(
final pWalletBalanceSecondary = Provider.family<Balance, String>(
(ref, walletId) {
return ref.watch(_wiProvider(walletId)
.select((value) => (value.value as WalletInfo).cachedSecondaryBalance));
},
);
final pWalletChainHeight = Provider.autoDispose.family<int, String>(
final pWalletChainHeight = Provider.family<int, String>(
(ref, walletId) {
return ref.watch(_wiProvider(walletId)
.select((value) => (value.value as WalletInfo).cachedChainHeight));
},
);
final pWalletIsFavourite = Provider.autoDispose.family<bool, String>(
final pWalletIsFavourite = Provider.family<bool, String>(
(ref, walletId) {
return ref.watch(_wiProvider(walletId)
.select((value) => (value.value as WalletInfo).isFavourite));
},
);
final pWalletName = Provider.autoDispose.family<String, String>(
final pWalletName = Provider.family<String, String>(
(ref, walletId) {
return ref.watch(_wiProvider(walletId)
.select((value) => (value.value as WalletInfo).name));
},
);
final pWalletReceivingAddress = Provider.autoDispose.family<String, String>(
final pWalletReceivingAddress = Provider.family<String, String>(
(ref, walletId) {
return ref.watch(_wiProvider(walletId)
.select((value) => (value.value as WalletInfo).cachedReceivingAddress));

View file

@ -25,6 +25,7 @@ class TxData {
final List<({String address, Amount amount})>? recipients;
final Set<UTXO>? utxos;
final List<UTXO>? usedUTXOs;
final String? changeAddress;
@ -56,6 +57,7 @@ class TxData {
this.memo,
this.recipients,
this.utxos,
this.usedUTXOs,
this.changeAddress,
this.frostMSConfig,
this.paynymAccountLite,
@ -89,6 +91,7 @@ class TxData {
String? noteOnChain,
String? memo,
Set<UTXO>? utxos,
List<UTXO>? usedUTXOs,
List<({String address, Amount amount})>? recipients,
String? frostMSConfig,
String? changeAddress,
@ -112,6 +115,7 @@ class TxData {
noteOnChain: noteOnChain ?? this.noteOnChain,
memo: memo ?? this.memo,
utxos: utxos ?? this.utxos,
usedUTXOs: usedUTXOs ?? this.usedUTXOs,
recipients: recipients ?? this.recipients,
frostMSConfig: frostMSConfig ?? this.frostMSConfig,
changeAddress: changeAddress ?? this.changeAddress,
@ -140,6 +144,7 @@ class TxData {
'memo: $memo, '
'recipients: $recipients, '
'utxos: $utxos, '
'usedUTXOs: $usedUTXOs, '
'frostMSConfig: $frostMSConfig, '
'changeAddress: $changeAddress, '
'paynymAccountLite: $paynymAccountLite, '

View file

@ -106,4 +106,70 @@ class BitcoinWallet extends Bip39HDWallet with ElectrumXMixin {
fractionDigits: info.coin.decimals,
);
}
@override
int estimateTxFee({required int vSize, required int feeRatePerKB}) {
return vSize * (feeRatePerKB / 1000).ceil();
}
//
// @override
// Future<TxData> coinSelection({required TxData txData}) async {
// final isCoinControl = txData.utxos != null;
// final isSendAll = txData.amount == info.cachedBalance.spendable;
//
// final utxos =
// txData.utxos?.toList() ?? await mainDB.getUTXOs(walletId).findAll();
//
// final currentChainHeight = await chainHeight;
// final List<UTXO> spendableOutputs = [];
// int spendableSatoshiValue = 0;
//
// // Build list of spendable outputs and totaling their satoshi amount
// for (final utxo in utxos) {
// if (utxo.isBlocked == false &&
// utxo.isConfirmed(currentChainHeight, cryptoCurrency.minConfirms) &&
// utxo.used != true) {
// spendableOutputs.add(utxo);
// spendableSatoshiValue += utxo.value;
// }
// }
//
// if (isCoinControl && spendableOutputs.length < utxos.length) {
// throw ArgumentError("Attempted to use an unavailable utxo");
// }
//
// if (spendableSatoshiValue < txData.amount!.raw.toInt()) {
// throw Exception("Insufficient balance");
// } else if (spendableSatoshiValue == txData.amount!.raw.toInt() &&
// !isSendAll) {
// throw Exception("Insufficient balance to pay transaction fee");
// }
//
// if (isCoinControl) {
// } else {
// final selection = cs.coinSelection(
// spendableOutputs
// .map((e) => cs.InputModel(
// i: e.vout,
// txid: e.txid,
// value: e.value,
// address: e.address,
// ))
// .toList(),
// txData.recipients!
// .map((e) => cs.OutputModel(
// address: e.address,
// value: e.amount.raw.toInt(),
// ))
// .toList(),
// txData.feeRateAmount!,
// 10, // TODO: ???????????????????????????????
// );
//
// // .inputs and .outputs will be null if no solution was found
// if (selection.inputs!.isEmpty || selection.outputs!.isEmpty) {
// throw Exception("coin selection failed");
// }
// }
// }
}

View file

@ -347,6 +347,11 @@ class BitcoincashWallet extends Bip39HDWallet with ElectrumXMixin {
);
}
@override
int estimateTxFee({required int vSize, required int feeRatePerKB}) {
return vSize * (feeRatePerKB / 1000).ceil();
}
// not all coins need to override this. BCH does due to cash addr string formatting
@override
Future<({List<Address> addresses, int index})> checkGaps(

View file

@ -100,4 +100,9 @@ class DogecoinWallet extends Bip39HDWallet with ElectrumXMixin {
fractionDigits: cryptoCurrency.fractionDigits,
);
}
@override
int estimateTxFee({required int vSize, required int feeRatePerKB}) {
return vSize * (feeRatePerKB / 1000).ceil();
}
}

View file

@ -2,11 +2,10 @@ import 'package:bip39/bip39.dart' as bip39;
import 'package:coinlib_flutter/coinlib_flutter.dart' as coinlib;
import 'package:isar/isar.dart';
import 'package:stackwallet/models/balance.dart';
import 'package:stackwallet/models/isar/models/isar_models.dart';
import 'package:stackwallet/models/isar/models/blockchain_data/address.dart';
import 'package:stackwallet/utilities/amount/amount.dart';
import 'package:stackwallet/utilities/enums/derive_path_type_enum.dart';
import 'package:stackwallet/wallets/crypto_currency/intermediate/bip39_hd_currency.dart';
import 'package:stackwallet/wallets/models/tx_data.dart';
import 'package:stackwallet/wallets/wallet/intermediate/bip39_wallet.dart';
import 'package:stackwallet/wallets/wallet/mixins/multi_address.dart';
@ -49,7 +48,6 @@ abstract class Bip39HDWallet<T extends Bip39HDCurrency> extends Bip39Wallet<T>
/// highest index found in the current wallet db.
@override
Future<void> generateNewChangeAddress() async {
await mainDB.isar.writeTxn(() async {
final current = await getCurrentChangeAddress();
final index = current?.derivationIndex ?? 0;
const chain = 1; // change address
@ -60,6 +58,7 @@ abstract class Bip39HDWallet<T extends Bip39HDCurrency> extends Bip39Wallet<T>
derivePathType: DerivePathTypeExt.primaryFor(info.coin),
);
await mainDB.isar.writeTxn(() async {
await mainDB.isar.addresses.put(address);
});
}
@ -164,16 +163,4 @@ abstract class Bip39HDWallet<T extends Bip39HDCurrency> extends Bip39Wallet<T>
await info.updateBalance(newBalance: balance, isar: mainDB.isar);
}
@override
Future<TxData> confirmSend({required TxData txData}) {
// TODO: implement confirmSend
throw UnimplementedError();
}
@override
Future<TxData> prepareSend({required TxData txData}) {
// TODO: implement prepareSend
throw UnimplementedError();
}
}

View file

@ -10,23 +10,23 @@ abstract class Bip39Wallet<T extends Bip39Currency> extends Wallet<T>
List<FilterOperation> get standardReceivingAddressFilters => [
FilterCondition.equalTo(
property: "type",
value: [info.mainAddressType],
property: r"type",
value: info.mainAddressType,
),
const FilterCondition.equalTo(
property: "subType",
value: [AddressSubType.receiving],
property: r"subType",
value: AddressSubType.receiving,
),
];
List<FilterOperation> get standardChangeAddressFilters => [
FilterCondition.equalTo(
property: "type",
value: [info.mainAddressType],
property: r"type",
value: info.mainAddressType,
),
const FilterCondition.equalTo(
property: "subType",
value: [AddressSubType.change],
property: r"subType",
value: AddressSubType.change,
),
];

View file

@ -2,6 +2,7 @@ import 'dart:convert';
import 'dart:math';
import 'package:bip47/src/util.dart';
import 'package:bitcoindart/bitcoindart.dart' as bitcoindart;
import 'package:coinlib_flutter/coinlib_flutter.dart' as coinlib;
import 'package:decimal/decimal.dart';
import 'package:isar/isar.dart';
@ -9,11 +10,14 @@ import 'package:stackwallet/electrumx_rpc/cached_electrumx.dart';
import 'package:stackwallet/electrumx_rpc/electrumx.dart';
import 'package:stackwallet/models/isar/models/isar_models.dart';
import 'package:stackwallet/models/paymint/fee_object_model.dart';
import 'package:stackwallet/models/signing_data.dart';
import 'package:stackwallet/services/mixins/paynym_wallet_interface.dart';
import 'package:stackwallet/utilities/amount/amount.dart';
import 'package:stackwallet/utilities/enums/coin_enum.dart';
import 'package:stackwallet/utilities/enums/derive_path_type_enum.dart';
import 'package:stackwallet/utilities/enums/fee_rate_type_enum.dart';
import 'package:stackwallet/utilities/logger.dart';
import 'package:stackwallet/wallets/models/tx_data.dart';
import 'package:stackwallet/wallets/wallet/intermediate/bip39_hd_wallet.dart';
import 'package:uuid/uuid.dart';
@ -21,6 +25,637 @@ mixin ElectrumXMixin on Bip39HDWallet {
late ElectrumX electrumX;
late CachedElectrumX electrumXCached;
List<({String address, Amount amount})> _helperRecipientsConvert(
List<String> addrs, List<int> satValues) {
final List<({String address, Amount amount})> results = [];
for (int i = 0; i < addrs.length; i++) {
results.add((
address: addrs[i],
amount: Amount(
rawValue: BigInt.from(satValues[i]),
fractionDigits: cryptoCurrency.fractionDigits,
),
));
}
return results;
}
Future<TxData> coinSelection({
required TxData txData,
required bool coinControl,
required bool isSendAll,
int additionalOutputs = 0,
List<UTXO>? utxos,
}) async {
Logging.instance
.log("Starting coinSelection ----------", level: LogLevel.Info);
// TODO: multiple recipients one day
assert(txData.recipients!.length == 1);
final recipientAddress = txData.recipients!.first.address;
final satoshiAmountToSend = txData.amount!.raw.toInt();
final int? satsPerVByte = txData.satsPerVByte;
final selectedTxFeeRate = txData.feeRateAmount!;
final List<UTXO> availableOutputs =
utxos ?? await mainDB.getUTXOs(walletId).findAll();
final currentChainHeight = await chainHeight;
final List<UTXO> spendableOutputs = [];
int spendableSatoshiValue = 0;
// Build list of spendable outputs and totaling their satoshi amount
for (final utxo in availableOutputs) {
if (utxo.isBlocked == false &&
utxo.isConfirmed(currentChainHeight, cryptoCurrency.minConfirms) &&
utxo.used != true) {
spendableOutputs.add(utxo);
spendableSatoshiValue += utxo.value;
}
}
if (coinControl) {
if (spendableOutputs.length < availableOutputs.length) {
throw ArgumentError("Attempted to use an unavailable utxo");
}
}
// don't care about sorting if using all utxos
if (!coinControl) {
// sort spendable by age (oldest first)
spendableOutputs.sort((a, b) => b.blockTime!.compareTo(a.blockTime!));
}
Logging.instance.log("spendableOutputs.length: ${spendableOutputs.length}",
level: LogLevel.Info);
Logging.instance.log("availableOutputs.length: ${availableOutputs.length}",
level: LogLevel.Info);
Logging.instance
.log("spendableOutputs: $spendableOutputs", level: LogLevel.Info);
Logging.instance.log("spendableSatoshiValue: $spendableSatoshiValue",
level: LogLevel.Info);
Logging.instance
.log("satoshiAmountToSend: $satoshiAmountToSend", level: LogLevel.Info);
// If the amount the user is trying to send is smaller than the amount that they have spendable,
// then return 1, which indicates that they have an insufficient balance.
if (spendableSatoshiValue < satoshiAmountToSend) {
// return 1;
throw Exception("Insufficient balance");
// If the amount the user wants to send is exactly equal to the amount they can spend, then return
// 2, which indicates that they are not leaving enough over to pay the transaction fee
} else if (spendableSatoshiValue == satoshiAmountToSend && !isSendAll) {
throw Exception("Insufficient balance to pay transaction fee");
// return 2;
}
// If neither of these statements pass, we assume that the user has a spendable balance greater
// than the amount they're attempting to send. Note that this value still does not account for
// the added transaction fee, which may require an extra input and will need to be checked for
// later on.
// Possible situation right here
int satoshisBeingUsed = 0;
int inputsBeingConsumed = 0;
List<UTXO> utxoObjectsToUse = [];
if (!coinControl) {
for (var i = 0;
satoshisBeingUsed < satoshiAmountToSend &&
i < spendableOutputs.length;
i++) {
utxoObjectsToUse.add(spendableOutputs[i]);
satoshisBeingUsed += spendableOutputs[i].value;
inputsBeingConsumed += 1;
}
for (int i = 0;
i < additionalOutputs &&
inputsBeingConsumed < spendableOutputs.length;
i++) {
utxoObjectsToUse.add(spendableOutputs[inputsBeingConsumed]);
satoshisBeingUsed += spendableOutputs[inputsBeingConsumed].value;
inputsBeingConsumed += 1;
}
} else {
satoshisBeingUsed = spendableSatoshiValue;
utxoObjectsToUse = spendableOutputs;
inputsBeingConsumed = spendableOutputs.length;
}
Logging.instance
.log("satoshisBeingUsed: $satoshisBeingUsed", level: LogLevel.Info);
Logging.instance
.log("inputsBeingConsumed: $inputsBeingConsumed", level: LogLevel.Info);
Logging.instance
.log('utxoObjectsToUse: $utxoObjectsToUse', level: LogLevel.Info);
// numberOfOutputs' length must always be equal to that of recipientsArray and recipientsAmtArray
List<String> recipientsArray = [recipientAddress];
List<int> recipientsAmtArray = [satoshiAmountToSend];
// gather required signing data
final utxoSigningData = await fetchBuildTxData(utxoObjectsToUse);
if (isSendAll) {
Logging.instance
.log("Attempting to send all $cryptoCurrency", level: LogLevel.Info);
final int vSizeForOneOutput = buildTransaction(
utxoSigningData: utxoSigningData,
txData: txData.copyWith(
recipients: _helperRecipientsConvert(
[recipientAddress],
[satoshisBeingUsed - 1],
),
),
).vSize!;
int feeForOneOutput = satsPerVByte != null
? (satsPerVByte * vSizeForOneOutput)
: estimateTxFee(
vSize: vSizeForOneOutput,
feeRatePerKB: selectedTxFeeRate,
);
if (satsPerVByte == null) {
final int roughEstimate = roughFeeEstimate(
spendableOutputs.length,
1,
selectedTxFeeRate,
).raw.toInt();
if (feeForOneOutput < roughEstimate) {
feeForOneOutput = roughEstimate;
}
}
final int amount = satoshiAmountToSend - feeForOneOutput;
final data = await buildTransaction(
txData: txData,
utxoSigningData: utxoSigningData,
);
return data.copyWith(
fee: Amount(
rawValue: BigInt.from(feeForOneOutput),
fractionDigits: cryptoCurrency.fractionDigits,
),
usedUTXOs: utxoSigningData.map((e) => e.utxo).toList(),
);
}
final int vSizeForOneOutput;
try {
vSizeForOneOutput = buildTransaction(
utxoSigningData: utxoSigningData,
txData: txData.copyWith(
recipients: _helperRecipientsConvert(
[recipientAddress],
[satoshisBeingUsed - 1],
),
),
).vSize!;
} catch (e) {
Logging.instance.log("vSizeForOneOutput: $e", level: LogLevel.Error);
rethrow;
}
final int vSizeForTwoOutPuts;
try {
vSizeForTwoOutPuts = buildTransaction(
utxoSigningData: utxoSigningData,
txData: txData.copyWith(
recipients: _helperRecipientsConvert(
[recipientAddress, (await getCurrentChangeAddress())!.value],
[
satoshiAmountToSend,
max(0, satoshisBeingUsed - satoshiAmountToSend - 1)
],
),
),
).vSize!;
} catch (e) {
Logging.instance.log("vSizeForTwoOutPuts: $e", level: LogLevel.Error);
rethrow;
}
// Assume 1 output, only for recipient and no change
final feeForOneOutput = satsPerVByte != null
? (satsPerVByte * vSizeForOneOutput)
: estimateTxFee(
vSize: vSizeForOneOutput,
feeRatePerKB: selectedTxFeeRate,
);
// Assume 2 outputs, one for recipient and one for change
final feeForTwoOutputs = satsPerVByte != null
? (satsPerVByte * vSizeForTwoOutPuts)
: estimateTxFee(
vSize: vSizeForTwoOutPuts,
feeRatePerKB: selectedTxFeeRate,
);
Logging.instance
.log("feeForTwoOutputs: $feeForTwoOutputs", level: LogLevel.Info);
Logging.instance
.log("feeForOneOutput: $feeForOneOutput", level: LogLevel.Info);
if (satoshisBeingUsed - satoshiAmountToSend > feeForOneOutput) {
if (satoshisBeingUsed - satoshiAmountToSend >
feeForOneOutput + cryptoCurrency.dustLimit.raw.toInt()) {
// Here, we know that theoretically, we may be able to include another output(change) but we first need to
// factor in the value of this output in satoshis.
int changeOutputSize =
satoshisBeingUsed - satoshiAmountToSend - feeForTwoOutputs;
// We check to see if the user can pay for the new transaction with 2 outputs instead of one. If they can and
// the second output's size > cryptoCurrency.dustLimit satoshis, we perform the mechanics required to properly generate and use a new
// change address.
if (changeOutputSize > cryptoCurrency.dustLimit.raw.toInt() &&
satoshisBeingUsed - satoshiAmountToSend - changeOutputSize ==
feeForTwoOutputs) {
// generate new change address if current change address has been used
await checkChangeAddressForTransactions();
final String newChangeAddress =
(await getCurrentChangeAddress())!.value;
int feeBeingPaid =
satoshisBeingUsed - satoshiAmountToSend - changeOutputSize;
recipientsArray.add(newChangeAddress);
recipientsAmtArray.add(changeOutputSize);
// At this point, we have the outputs we're going to use, the amounts to send along with which addresses
// we intend to send these amounts to. We have enough to send instructions to build the transaction.
Logging.instance.log('2 outputs in tx', level: LogLevel.Info);
Logging.instance
.log('Input size: $satoshisBeingUsed', level: LogLevel.Info);
Logging.instance.log('Recipient output size: $satoshiAmountToSend',
level: LogLevel.Info);
Logging.instance.log('Change Output Size: $changeOutputSize',
level: LogLevel.Info);
Logging.instance.log(
'Difference (fee being paid): $feeBeingPaid sats',
level: LogLevel.Info);
Logging.instance
.log('Estimated fee: $feeForTwoOutputs', level: LogLevel.Info);
var txn = buildTransaction(
utxoSigningData: utxoSigningData,
txData: txData.copyWith(
recipients: _helperRecipientsConvert(
recipientsArray,
recipientsAmtArray,
),
),
);
// make sure minimum fee is accurate if that is being used
if (txn.vSize! - feeBeingPaid == 1) {
int changeOutputSize =
satoshisBeingUsed - satoshiAmountToSend - txn.vSize!;
feeBeingPaid =
satoshisBeingUsed - satoshiAmountToSend - changeOutputSize;
recipientsAmtArray.removeLast();
recipientsAmtArray.add(changeOutputSize);
Logging.instance.log('Adjusted Input size: $satoshisBeingUsed',
level: LogLevel.Info);
Logging.instance.log(
'Adjusted Recipient output size: $satoshiAmountToSend',
level: LogLevel.Info);
Logging.instance.log(
'Adjusted Change Output Size: $changeOutputSize',
level: LogLevel.Info);
Logging.instance.log(
'Adjusted Difference (fee being paid): $feeBeingPaid sats',
level: LogLevel.Info);
Logging.instance.log('Adjusted Estimated fee: $feeForTwoOutputs',
level: LogLevel.Info);
txn = buildTransaction(
utxoSigningData: utxoSigningData,
txData: txData.copyWith(
recipients: _helperRecipientsConvert(
recipientsArray,
recipientsAmtArray,
),
),
);
}
return txn.copyWith(
fee: Amount(
rawValue: BigInt.from(feeBeingPaid),
fractionDigits: cryptoCurrency.fractionDigits,
),
usedUTXOs: utxoSigningData.map((e) => e.utxo).toList(),
);
} else {
// Something went wrong here. It either overshot or undershot the estimated fee amount or the changeOutputSize
// is smaller than or equal to cryptoCurrency.dustLimit. Revert to single output transaction.
Logging.instance.log('1 output in tx', level: LogLevel.Info);
Logging.instance
.log('Input size: $satoshisBeingUsed', level: LogLevel.Info);
Logging.instance.log('Recipient output size: $satoshiAmountToSend',
level: LogLevel.Info);
Logging.instance.log(
'Difference (fee being paid): ${satoshisBeingUsed - satoshiAmountToSend} sats',
level: LogLevel.Info);
Logging.instance
.log('Estimated fee: $feeForOneOutput', level: LogLevel.Info);
final txn = buildTransaction(
utxoSigningData: utxoSigningData,
txData: txData.copyWith(
recipients: _helperRecipientsConvert(
recipientsArray,
recipientsAmtArray,
),
),
);
return txn.copyWith(
fee: Amount(
rawValue: BigInt.from(satoshisBeingUsed - satoshiAmountToSend),
fractionDigits: cryptoCurrency.fractionDigits,
),
usedUTXOs: utxoSigningData.map((e) => e.utxo).toList(),
);
}
} else {
// No additional outputs needed since adding one would mean that it'd be smaller than cryptoCurrency.dustLimit sats
// which makes it uneconomical to add to the transaction. Here, we pass data directly to instruct
// the wallet to begin crafting the transaction that the user requested.
Logging.instance.log('1 output in tx', level: LogLevel.Info);
Logging.instance
.log('Input size: $satoshisBeingUsed', level: LogLevel.Info);
Logging.instance.log('Recipient output size: $satoshiAmountToSend',
level: LogLevel.Info);
Logging.instance.log(
'Difference (fee being paid): ${satoshisBeingUsed - satoshiAmountToSend} sats',
level: LogLevel.Info);
Logging.instance
.log('Estimated fee: $feeForOneOutput', level: LogLevel.Info);
final txn = buildTransaction(
utxoSigningData: utxoSigningData,
txData: txData.copyWith(
recipients: _helperRecipientsConvert(
recipientsArray,
recipientsAmtArray,
),
),
);
return txn.copyWith(
fee: Amount(
rawValue: BigInt.from(satoshisBeingUsed - satoshiAmountToSend),
fractionDigits: cryptoCurrency.fractionDigits,
),
usedUTXOs: utxoSigningData.map((e) => e.utxo).toList(),
);
}
} else if (satoshisBeingUsed - satoshiAmountToSend == feeForOneOutput) {
// In this scenario, no additional change output is needed since inputs - outputs equal exactly
// what we need to pay for fees. Here, we pass data directly to instruct the wallet to begin
// crafting the transaction that the user requested.
Logging.instance.log('1 output in tx', level: LogLevel.Info);
Logging.instance
.log('Input size: $satoshisBeingUsed', level: LogLevel.Info);
Logging.instance.log('Recipient output size: $satoshiAmountToSend',
level: LogLevel.Info);
Logging.instance.log(
'Fee being paid: ${satoshisBeingUsed - satoshiAmountToSend} sats',
level: LogLevel.Info);
Logging.instance
.log('Estimated fee: $feeForOneOutput', level: LogLevel.Info);
final txn = buildTransaction(
utxoSigningData: utxoSigningData,
txData: txData.copyWith(
recipients: _helperRecipientsConvert(
recipientsArray,
recipientsAmtArray,
),
),
);
return txn.copyWith(
fee: Amount(
rawValue: BigInt.from(feeForOneOutput),
fractionDigits: cryptoCurrency.fractionDigits,
),
usedUTXOs: utxoSigningData.map((e) => e.utxo).toList(),
);
} else {
// Remember that returning 2 indicates that the user does not have a sufficient balance to
// pay for the transaction fee. Ideally, at this stage, we should check if the user has any
// additional outputs they're able to spend and then recalculate fees.
Logging.instance.log(
'Cannot pay tx fee - checking for more outputs and trying again',
level: LogLevel.Warning);
// try adding more outputs
if (spendableOutputs.length > inputsBeingConsumed) {
return coinSelection(
txData: txData,
isSendAll: isSendAll,
additionalOutputs: additionalOutputs + 1,
utxos: utxos,
coinControl: coinControl,
);
}
throw Exception("Insufficient balance to pay transaction fee");
// return 2;
}
}
Future<List<SigningData>> fetchBuildTxData(
List<UTXO> utxosToUse,
) async {
// return data
List<SigningData> signingData = [];
try {
// Populating the addresses to check
for (var i = 0; i < utxosToUse.length; i++) {
final derivePathType =
cryptoCurrency.addressType(address: utxosToUse[i].address!);
signingData.add(
SigningData(
derivePathType: derivePathType,
utxo: utxosToUse[i],
),
);
}
final root = await getRootHDNode();
for (final sd in signingData) {
coinlib.HDPrivateKey? keys;
final address = await mainDB.getAddress(walletId, sd.utxo.address!);
if (address?.derivationPath != null) {
if (address!.subType == AddressSubType.paynymReceive) {
// TODO paynym
// final code = await paymentCodeStringByKey(address.otherData!);
//
// final bip47base = await getBip47BaseNode();
//
// final privateKey = await getPrivateKeyForPaynymReceivingAddress(
// paymentCodeString: code!,
// index: address.derivationIndex,
// );
//
// keys = coinlib.HDPrivateKey.fromKeyAndChainCode(
// privateKey,
// bip47base.chainCode,
// );
} else {
keys = root.derivePath(address.derivationPath!.value);
}
}
if (keys == null) {
throw Exception(
"Failed to fetch signing data. Local db corrupt. Rescan wallet.");
}
final coinlib.Input input;
switch (sd.derivePathType) {
case DerivePathType.bip44:
input = coinlib.P2PKHInput(
prevOut: coinlib.OutPoint.fromHex(sd.utxo.txid, sd.utxo.vout),
publicKey: keys.publicKey,
);
// data = P2PKH(
// data: PaymentData(
// pubkey: Format.stringToUint8List(pubKey),
// ),
// network: _network,
// ).data;
break;
//
// case DerivePathType.bip49:
//
// input = P2s
//
// final p2wpkh = P2WPKH(
// data: PaymentData(
// pubkey: Format.stringToUint8List(pubKey),
// ),
// network: _network,
// ).data;
// redeemScript = p2wpkh.output;
// data = P2SH(
// data: PaymentData(redeem: p2wpkh),
// network: _network,
// ).data;
// break;
case DerivePathType.bip84:
input = coinlib.P2WPKHInput(
prevOut: coinlib.OutPoint.fromHex(sd.utxo.txid, sd.utxo.vout),
publicKey: keys.publicKey,
);
// data = P2WPKH(
// data: PaymentData(
// pubkey: Format.stringToUint8List(pubKey),
// ),
// network: _network,
// ).data;
break;
default:
throw Exception("DerivePathType unsupported");
}
sd.output = input.toBytes();
sd.keyPair = bitcoindart.ECPair.fromPrivateKey(
keys.privateKey.data,
compressed: keys.privateKey.compressed,
network: bitcoindart.NetworkType(
messagePrefix: cryptoCurrency.networkParams.messagePrefix,
bech32: cryptoCurrency.networkParams.bech32Hrp,
bip32: bitcoindart.Bip32Type(
public: cryptoCurrency.networkParams.pubHDPrefix,
private: cryptoCurrency.networkParams.privHDPrefix,
),
pubKeyHash: cryptoCurrency.networkParams.p2pkhPrefix,
scriptHash: cryptoCurrency.networkParams.p2shPrefix,
wif: cryptoCurrency.networkParams.wifPrefix,
),
);
}
return signingData;
} catch (e, s) {
Logging.instance
.log("fetchBuildTxData() threw: $e,\n$s", level: LogLevel.Error);
rethrow;
}
}
/// Builds and signs a transaction
TxData buildTransaction({
required TxData txData,
required List<SigningData> utxoSigningData,
}) {
Logging.instance
.log("Starting buildTransaction ----------", level: LogLevel.Info);
// TODO: use coinlib
final txb = bitcoindart.TransactionBuilder(
network: bitcoindart.NetworkType(
messagePrefix: cryptoCurrency.networkParams.messagePrefix,
bech32: cryptoCurrency.networkParams.bech32Hrp,
bip32: bitcoindart.Bip32Type(
public: cryptoCurrency.networkParams.pubHDPrefix,
private: cryptoCurrency.networkParams.privHDPrefix,
),
pubKeyHash: cryptoCurrency.networkParams.p2pkhPrefix,
scriptHash: cryptoCurrency.networkParams.p2shPrefix,
wif: cryptoCurrency.networkParams.wifPrefix,
),
);
txb.setVersion(1);
// Add transaction inputs
for (var i = 0; i < utxoSigningData.length; i++) {
final txid = utxoSigningData[i].utxo.txid;
txb.addInput(
txid,
utxoSigningData[i].utxo.vout,
null,
utxoSigningData[i].output!,
);
}
// Add transaction output
for (var i = 0; i < txData.recipients!.length; i++) {
txb.addOutput(
txData.recipients![i].address,
txData.recipients![i].amount.raw.toInt(),
);
}
try {
// Sign the transaction accordingly
for (var i = 0; i < utxoSigningData.length; i++) {
txb.sign(
vin: i,
keyPair: utxoSigningData[i].keyPair!,
witnessValue: utxoSigningData[i].utxo.value,
redeemScript: utxoSigningData[i].redeemScript,
);
}
} catch (e, s) {
Logging.instance.log("Caught exception while signing transaction: $e\n$s",
level: LogLevel.Error);
rethrow;
}
final builtTx = txb.build();
final vSize = builtTx.virtualSize();
return txData.copyWith(
raw: builtTx.toHex(),
vSize: vSize,
);
}
Future<int> fetchChainHeight() async {
try {
final result = await electrumX.getBlockHeadTip();
@ -708,7 +1343,9 @@ mixin ElectrumXMixin on Bip39HDWallet {
needsGenerate = true;
} else {
final txCount = await fetchTxCount(
addressScriptHash: currentReceiving.value,
addressScriptHash: cryptoCurrency.addressToScriptHash(
address: currentReceiving.value,
),
);
needsGenerate = txCount > 0 || currentReceiving.derivationIndex < 0;
}
@ -743,7 +1380,9 @@ mixin ElectrumXMixin on Bip39HDWallet {
needsGenerate = true;
} else {
final txCount = await fetchTxCount(
addressScriptHash: currentChange.value,
addressScriptHash: cryptoCurrency.addressToScriptHash(
address: currentChange.value,
),
);
needsGenerate = txCount > 0 || currentChange.derivationIndex < 0;
}
@ -757,7 +1396,7 @@ mixin ElectrumXMixin on Bip39HDWallet {
}
} catch (e, s) {
Logging.instance.log(
"Exception rethrown from _checkReceivingAddressForTransactions"
"Exception rethrown from _checkChangeAddressForTransactions"
"($cryptoCurrency): $e\n$s",
level: LogLevel.Error,
);
@ -939,9 +1578,129 @@ mixin ElectrumXMixin on Bip39HDWallet {
}
}
@override
Future<TxData> confirmSend({required TxData txData}) async {
try {
Logging.instance.log("confirmSend txData: $txData", level: LogLevel.Info);
final txHash = await electrumX.broadcastTransaction(
rawTx: txData.raw!,
);
Logging.instance.log("Sent txHash: $txHash", level: LogLevel.Info);
txData = txData.copyWith(
usedUTXOs:
txData.usedUTXOs!.map((e) => e.copyWith(used: true)).toList(),
// TODO revisit setting these both
txHash: txHash,
txid: txHash,
);
// mark utxos as used
await mainDB.putUTXOs(txData.usedUTXOs!);
return txData;
} catch (e, s) {
Logging.instance.log("Exception rethrown from confirmSend(): $e\n$s",
level: LogLevel.Error);
rethrow;
}
}
@override
Future<TxData> prepareSend({required TxData txData}) async {
try {
final feeRateType = txData.feeRateType;
final customSatsPerVByte = txData.satsPerVByte;
final feeRateAmount = txData.feeRateAmount;
final utxos = txData.utxos;
if (customSatsPerVByte != null) {
// check for send all
bool isSendAll = false;
if (txData.amount == info.cachedBalance.spendable) {
isSendAll = true;
}
final bool coinControl = utxos != null;
final result = await coinSelection(
txData: txData.copyWith(feeRateAmount: -1),
isSendAll: isSendAll,
utxos: utxos?.toList(),
coinControl: coinControl,
);
Logging.instance
.log("PREPARE SEND RESULT: $result", level: LogLevel.Info);
if (txData.fee!.raw.toInt() < txData.vSize!) {
throw Exception(
"Error in fee calculation: Transaction fee cannot be less than vSize");
}
return result;
} else if (feeRateType is FeeRateType || feeRateAmount is int) {
late final int rate;
if (feeRateType is FeeRateType) {
int fee = 0;
final feeObject = await fees;
switch (feeRateType) {
case FeeRateType.fast:
fee = feeObject.fast;
break;
case FeeRateType.average:
fee = feeObject.medium;
break;
case FeeRateType.slow:
fee = feeObject.slow;
break;
default:
throw ArgumentError("Invalid use of custom fee");
}
rate = fee;
} else {
rate = feeRateAmount as int;
}
// check for send all
bool isSendAll = false;
if (txData.amount == info.cachedBalance.spendable) {
isSendAll = true;
}
final bool coinControl = utxos != null;
final result = await coinSelection(
txData: txData.copyWith(
feeRateAmount: rate,
),
isSendAll: isSendAll,
utxos: utxos?.toList(),
coinControl: coinControl,
);
Logging.instance.log("prepare send: $result", level: LogLevel.Info);
if (txData.fee!.raw.toInt() < txData.vSize!) {
throw Exception(
"Error in fee calculation: Transaction fee cannot be less than vSize");
}
return result;
} else {
throw ArgumentError("Invalid fee rate argument provided!");
}
} catch (e, s) {
Logging.instance.log("Exception rethrown from prepareSend(): $e\n$s",
level: LogLevel.Error);
rethrow;
}
}
// ===========================================================================
// ========== Interface functions ============================================
int estimateTxFee({required int vSize, required int feeRatePerKB});
Amount roughFeeEstimate(int inputCount, int outputCount, int feeRatePerKB);
Future<List<Address>> fetchAllOwnAddresses();

View file

@ -135,11 +135,11 @@ abstract class Wallet<T extends CryptoCurrency> {
case WalletType.bip39HD:
await secureStorageInterface.write(
key: mnemonicKey(walletId: walletInfo.walletId),
value: mnemonic,
value: mnemonic!,
);
await secureStorageInterface.write(
key: mnemonicPassphraseKey(walletId: walletInfo.walletId),
value: mnemonicPassphrase,
value: mnemonicPassphrase!,
);
break;
@ -147,11 +147,17 @@ abstract class Wallet<T extends CryptoCurrency> {
break;
case WalletType.privateKeyBased:
await secureStorageInterface.write(
key: privateKeyKey(walletId: walletInfo.walletId),
value: privateKey!,
);
break;
}
// Store in db after wallet creation
await wallet.mainDB.isar.writeTxn(() async {
await wallet.mainDB.isar.walletInfo.put(wallet.info);
});
return wallet;
}
@ -475,10 +481,12 @@ abstract class Wallet<T extends CryptoCurrency> {
@mustCallSuper
Future<void> init() async {
final address = await getCurrentReceivingAddress();
if (address != null) {
await info.updateReceivingAddress(
newAddress: address!.value,
newAddress: address.value,
isar: mainDB.isar,
);
}
// TODO: make sure subclasses override this if they require some set up
// especially xmr/wow/epiccash
@ -502,14 +510,14 @@ abstract class Wallet<T extends CryptoCurrency> {
.buildQuery<Address>(
whereClauses: [
IndexWhereClause.equalTo(
indexName: "walletId",
indexName: r"walletId",
value: [walletId],
),
],
filter: filterOperation,
sortBy: [
const SortProperty(
property: "derivationIndex",
property: r"derivationIndex",
sort: Sort.desc,
),
],