stopsync monero (TODO)

This commit is contained in:
Matthew Fosse 2024-09-18 12:39:25 -07:00
parent e68b2eaa57
commit b3495fe714

View file

@ -46,8 +46,8 @@ const MIN_RESTORE_HEIGHT = 1000;
class MoneroWallet = MoneroWalletBase with _$MoneroWallet; class MoneroWallet = MoneroWalletBase with _$MoneroWallet;
abstract class MoneroWalletBase extends WalletBase<MoneroBalance, abstract class MoneroWalletBase
MoneroTransactionHistory, MoneroTransactionInfo> with Store { extends WalletBase<MoneroBalance, MoneroTransactionHistory, MoneroTransactionInfo> with Store {
MoneroWalletBase( MoneroWalletBase(
{required WalletInfo walletInfo, {required WalletInfo walletInfo,
required Box<UnspentCoinsInfo> unspentCoinsInfo, required Box<UnspentCoinsInfo> unspentCoinsInfo,
@ -68,16 +68,13 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
transactionHistory = MoneroTransactionHistory(); transactionHistory = MoneroTransactionHistory();
walletAddresses = MoneroWalletAddresses(walletInfo, transactionHistory); walletAddresses = MoneroWalletAddresses(walletInfo, transactionHistory);
_onAccountChangeReaction = _onAccountChangeReaction = reaction((_) => walletAddresses.account, (Account? account) {
reaction((_) => walletAddresses.account, (Account? account) {
if (account == null) return; if (account == null) return;
balance = ObservableMap<CryptoCurrency, MoneroBalance>.of(<CryptoCurrency, balance = ObservableMap<CryptoCurrency, MoneroBalance>.of(<CryptoCurrency, MoneroBalance>{
MoneroBalance>{
currency: MoneroBalance( currency: MoneroBalance(
fullBalance: monero_wallet.getFullBalance(accountIndex: account.id), fullBalance: monero_wallet.getFullBalance(accountIndex: account.id),
unlockedBalance: unlockedBalance: monero_wallet.getUnlockedBalance(accountIndex: account.id))
monero_wallet.getUnlockedBalance(accountIndex: account.id))
}); });
_updateSubAddress(isEnabledAutoGenerateSubaddress, account: account); _updateSubAddress(isEnabledAutoGenerateSubaddress, account: account);
_askForUpdateTransactionHistory(); _askForUpdateTransactionHistory();
@ -123,8 +120,7 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
publicSpendKey: monero_wallet.getPublicSpendKey(), publicSpendKey: monero_wallet.getPublicSpendKey(),
publicViewKey: monero_wallet.getPublicViewKey()); publicViewKey: monero_wallet.getPublicViewKey());
int? get restoreHeight => int? get restoreHeight => transactionHistory.transactions.values.firstOrNull?.height;
transactionHistory.transactions.values.firstOrNull?.height;
monero_wallet.SyncListener? _listener; monero_wallet.SyncListener? _listener;
ReactionDisposer? _onAccountChangeReaction; ReactionDisposer? _onAccountChangeReaction;
@ -136,13 +132,11 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
Future<void> init() async { Future<void> init() async {
await walletAddresses.init(); await walletAddresses.init();
balance = ObservableMap<CryptoCurrency, MoneroBalance>.of(<CryptoCurrency, balance = ObservableMap<CryptoCurrency, MoneroBalance>.of(<CryptoCurrency, MoneroBalance>{
MoneroBalance>{
currency: MoneroBalance( currency: MoneroBalance(
fullBalance: monero_wallet.getFullBalance( fullBalance: monero_wallet.getFullBalance(accountIndex: walletAddresses.account!.id),
accountIndex: walletAddresses.account!.id), unlockedBalance:
unlockedBalance: monero_wallet.getUnlockedBalance( monero_wallet.getUnlockedBalance(accountIndex: walletAddresses.account!.id))
accountIndex: walletAddresses.account!.id))
}); });
_setListeners(); _setListeners();
await updateTransactions(); await updateTransactions();
@ -151,13 +145,12 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
monero_wallet.setRecoveringFromSeed(isRecovery: walletInfo.isRecovery); monero_wallet.setRecoveringFromSeed(isRecovery: walletInfo.isRecovery);
if (monero_wallet.getCurrentHeight() <= 1) { if (monero_wallet.getCurrentHeight() <= 1) {
monero_wallet.setRefreshFromBlockHeight( monero_wallet.setRefreshFromBlockHeight(height: walletInfo.restoreHeight);
height: walletInfo.restoreHeight);
} }
} }
_autoSaveTimer = Timer.periodic( _autoSaveTimer =
Duration(seconds: _autoSaveInterval), (_) async => await save()); Timer.periodic(Duration(seconds: _autoSaveInterval), (_) async => await save());
} }
@override @override
@ -223,14 +216,22 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
} }
} }
@override
Future<void> stopSync() async {
syncStatus = NotConnectedSyncStatus();
_listener?.stop();
// TODO: find a better way to stop syncing than setting an invalid address:
monero_wallet.setupNode(address: "");
}
@override @override
Future<PendingTransaction> createTransaction(Object credentials) async { Future<PendingTransaction> createTransaction(Object credentials) async {
final _credentials = credentials as MoneroTransactionCreationCredentials; final _credentials = credentials as MoneroTransactionCreationCredentials;
final inputs = <String>[]; final inputs = <String>[];
final outputs = _credentials.outputs; final outputs = _credentials.outputs;
final hasMultiDestination = outputs.length > 1; final hasMultiDestination = outputs.length > 1;
final unlockedBalance = monero_wallet.getUnlockedBalance( final unlockedBalance =
accountIndex: walletAddresses.account!.id); monero_wallet.getUnlockedBalance(accountIndex: walletAddresses.account!.id);
var allInputsAmount = 0; var allInputsAmount = 0;
PendingTransactionDescription pendingTransactionDescription; PendingTransactionDescription pendingTransactionDescription;
@ -252,20 +253,16 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
final spendAllCoins = inputs.length == unspentCoins.length; final spendAllCoins = inputs.length == unspentCoins.length;
if (hasMultiDestination) { if (hasMultiDestination) {
if (outputs.any( if (outputs.any((item) => item.sendAll || (item.formattedCryptoAmount ?? 0) <= 0)) {
(item) => item.sendAll || (item.formattedCryptoAmount ?? 0) <= 0)) { throw MoneroTransactionCreationException('You do not have enough XMR to send this amount.');
throw MoneroTransactionCreationException(
'You do not have enough XMR to send this amount.');
} }
final int totalAmount = outputs.fold( final int totalAmount =
0, (acc, value) => acc + (value.formattedCryptoAmount ?? 0)); outputs.fold(0, (acc, value) => acc + (value.formattedCryptoAmount ?? 0));
final estimatedFee = final estimatedFee = calculateEstimatedFee(_credentials.priority, totalAmount);
calculateEstimatedFee(_credentials.priority, totalAmount);
if (unlockedBalance < totalAmount) { if (unlockedBalance < totalAmount) {
throw MoneroTransactionCreationException( throw MoneroTransactionCreationException('You do not have enough XMR to send this amount.');
'You do not have enough XMR to send this amount.');
} }
if (!spendAllCoins && (allInputsAmount < totalAmount + estimatedFee)) { if (!spendAllCoins && (allInputsAmount < totalAmount + estimatedFee)) {
@ -273,28 +270,22 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
} }
final moneroOutputs = outputs.map((output) { final moneroOutputs = outputs.map((output) {
final outputAddress = final outputAddress = output.isParsedAddress ? output.extractedAddress : output.address;
output.isParsedAddress ? output.extractedAddress : output.address;
return MoneroOutput( return MoneroOutput(
address: outputAddress!, address: outputAddress!, amount: output.cryptoAmount!.replaceAll(',', '.'));
amount: output.cryptoAmount!.replaceAll(',', '.'));
}).toList(); }).toList();
pendingTransactionDescription = pendingTransactionDescription = await transaction_history.createTransactionMultDest(
await transaction_history.createTransactionMultDest( outputs: moneroOutputs,
outputs: moneroOutputs, priorityRaw: _credentials.priority.serialize(),
priorityRaw: _credentials.priority.serialize(), accountIndex: walletAddresses.account!.id,
accountIndex: walletAddresses.account!.id, preferredInputs: inputs);
preferredInputs: inputs);
} else { } else {
final output = outputs.first; final output = outputs.first;
final address = final address = output.isParsedAddress ? output.extractedAddress : output.address;
output.isParsedAddress ? output.extractedAddress : output.address; final amount = output.sendAll ? null : output.cryptoAmount!.replaceAll(',', '.');
final amount = final formattedAmount = output.sendAll ? null : output.formattedCryptoAmount;
output.sendAll ? null : output.cryptoAmount!.replaceAll(',', '.');
final formattedAmount =
output.sendAll ? null : output.formattedCryptoAmount;
if ((formattedAmount != null && unlockedBalance < formattedAmount) || if ((formattedAmount != null && unlockedBalance < formattedAmount) ||
(formattedAmount == null && unlockedBalance <= 0)) { (formattedAmount == null && unlockedBalance <= 0)) {
@ -304,22 +295,19 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
'You do not have enough unlocked balance. Unlocked: $formattedBalance. Transaction amount: ${output.cryptoAmount}.'); 'You do not have enough unlocked balance. Unlocked: $formattedBalance. Transaction amount: ${output.cryptoAmount}.');
} }
final estimatedFee = final estimatedFee = calculateEstimatedFee(_credentials.priority, formattedAmount);
calculateEstimatedFee(_credentials.priority, formattedAmount);
if (!spendAllCoins && if (!spendAllCoins &&
((formattedAmount != null && ((formattedAmount != null && allInputsAmount < (formattedAmount + estimatedFee)) ||
allInputsAmount < (formattedAmount + estimatedFee)) ||
formattedAmount == null)) { formattedAmount == null)) {
throw MoneroTransactionNoInputsException(inputs.length); throw MoneroTransactionNoInputsException(inputs.length);
} }
pendingTransactionDescription = pendingTransactionDescription = await transaction_history.createTransaction(
await transaction_history.createTransaction( address: address!,
address: address!, amount: amount,
amount: amount, priorityRaw: _credentials.priority.serialize(),
priorityRaw: _credentials.priority.serialize(), accountIndex: walletAddresses.account!.id,
accountIndex: walletAddresses.account!.id, preferredInputs: inputs);
preferredInputs: inputs);
} }
return PendingMoneroTransaction(pendingTransactionDescription); return PendingMoneroTransaction(pendingTransactionDescription);
@ -384,10 +372,8 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
} }
try { try {
// -- rename the waller folder -- // -- rename the waller folder --
final currentWalletDir = final currentWalletDir = Directory(await pathForWalletDir(name: name, type: type));
Directory(await pathForWalletDir(name: name, type: type)); final newWalletDirPath = await pathForWalletDir(name: newWalletName, type: type);
final newWalletDirPath =
await pathForWalletDir(name: newWalletName, type: type);
await currentWalletDir.rename(newWalletDirPath); await currentWalletDir.rename(newWalletDirPath);
// -- use new waller folder to rename files with old names still -- // -- use new waller folder to rename files with old names still --
@ -397,8 +383,7 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
final currentKeysFile = File('$renamedWalletPath.keys'); final currentKeysFile = File('$renamedWalletPath.keys');
final currentAddressListFile = File('$renamedWalletPath.address.txt'); final currentAddressListFile = File('$renamedWalletPath.address.txt');
final newWalletPath = final newWalletPath = await pathForWallet(name: newWalletName, type: type);
await pathForWallet(name: newWalletName, type: type);
if (currentCacheFile.existsSync()) { if (currentCacheFile.existsSync()) {
await currentCacheFile.rename(newWalletPath); await currentCacheFile.rename(newWalletPath);
@ -418,8 +403,7 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
final currentKeysFile = File('$currentWalletPath.keys'); final currentKeysFile = File('$currentWalletPath.keys');
final currentAddressListFile = File('$currentWalletPath.address.txt'); final currentAddressListFile = File('$currentWalletPath.address.txt');
final newWalletPath = final newWalletPath = await pathForWallet(name: newWalletName, type: type);
await pathForWallet(name: newWalletName, type: type);
// Copies current wallet files into new wallet name's dir and files // Copies current wallet files into new wallet name's dir and files
if (currentCacheFile.existsSync()) { if (currentCacheFile.existsSync()) {
@ -438,8 +422,7 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
} }
@override @override
Future<void> changePassword(String password) async => Future<void> changePassword(String password) async => monero_wallet.setPasswordSync(password);
monero_wallet.setPasswordSync(password);
Future<int> getNodeHeight() async => monero_wallet.getNodeHeight(); Future<int> getNodeHeight() async => monero_wallet.getNodeHeight();
@ -547,15 +530,13 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
Future<void> _refreshUnspentCoinsInfo() async { Future<void> _refreshUnspentCoinsInfo() async {
try { try {
final List<dynamic> keys = <dynamic>[]; final List<dynamic> keys = <dynamic>[];
final currentWalletUnspentCoins = unspentCoinsInfo.values.where( final currentWalletUnspentCoins = unspentCoinsInfo.values.where((element) =>
(element) => element.walletId.contains(id) && element.accountIndex == walletAddresses.account!.id);
element.walletId.contains(id) &&
element.accountIndex == walletAddresses.account!.id);
if (currentWalletUnspentCoins.isNotEmpty) { if (currentWalletUnspentCoins.isNotEmpty) {
currentWalletUnspentCoins.forEach((element) { currentWalletUnspentCoins.forEach((element) {
final existUnspentCoins = unspentCoins final existUnspentCoins =
.where((coin) => element.keyImage!.contains(coin.keyImage!)); unspentCoins.where((coin) => element.keyImage!.contains(coin.keyImage!));
if (existUnspentCoins.isEmpty) { if (existUnspentCoins.isEmpty) {
keys.add(element.key); keys.add(element.key);
@ -572,15 +553,13 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
} }
String getTransactionAddress(int accountIndex, int addressIndex) => String getTransactionAddress(int accountIndex, int addressIndex) =>
monero_wallet.getAddress( monero_wallet.getAddress(accountIndex: accountIndex, addressIndex: addressIndex);
accountIndex: accountIndex, addressIndex: addressIndex);
@override @override
Future<Map<String, MoneroTransactionInfo>> fetchTransactions() async { Future<Map<String, MoneroTransactionInfo>> fetchTransactions() async {
transaction_history.refreshTransactions(); transaction_history.refreshTransactions();
return _getAllTransactionsOfAccount(walletAddresses.account?.id) return _getAllTransactionsOfAccount(walletAddresses.account?.id)
.fold<Map<String, MoneroTransactionInfo>>( .fold<Map<String, MoneroTransactionInfo>>(<String, MoneroTransactionInfo>{},
<String, MoneroTransactionInfo>{},
(Map<String, MoneroTransactionInfo> acc, MoneroTransactionInfo tx) { (Map<String, MoneroTransactionInfo> acc, MoneroTransactionInfo tx) {
acc[tx.id] = tx; acc[tx.id] = tx;
return acc; return acc;
@ -608,31 +587,28 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
String getSubaddressLabel(int accountIndex, int addressIndex) => String getSubaddressLabel(int accountIndex, int addressIndex) =>
monero_wallet.getSubaddressLabel(accountIndex, addressIndex); monero_wallet.getSubaddressLabel(accountIndex, addressIndex);
List<MoneroTransactionInfo> _getAllTransactionsOfAccount(int? accountIndex) => List<MoneroTransactionInfo> _getAllTransactionsOfAccount(int? accountIndex) => transaction_history
transaction_history .getAllTransactions()
.getAllTransactions() .map(
.map( (row) => MoneroTransactionInfo(
(row) => MoneroTransactionInfo( row.hash,
row.hash, row.blockheight,
row.blockheight, row.isSpend ? TransactionDirection.outgoing : TransactionDirection.incoming,
row.isSpend row.timeStamp,
? TransactionDirection.outgoing row.isPending,
: TransactionDirection.incoming, row.amount,
row.timeStamp, row.accountIndex,
row.isPending, 0,
row.amount, row.fee,
row.accountIndex, row.confirmations,
0, )..additionalInfo = <String, dynamic>{
row.fee, 'key': row.key,
row.confirmations, 'accountIndex': row.accountIndex,
)..additionalInfo = <String, dynamic>{ 'addressIndex': row.addressIndex
'key': row.key, },
'accountIndex': row.accountIndex, )
'addressIndex': row.addressIndex .where((element) => element.accountIndex == (accountIndex ?? 0))
}, .toList();
)
.where((element) => element.accountIndex == (accountIndex ?? 0))
.toList();
void _setListeners() { void _setListeners() {
_listener?.stop(); _listener?.stop();
@ -666,8 +642,7 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
} }
int _getHeightDistance(DateTime date) { int _getHeightDistance(DateTime date) {
final distance = final distance = DateTime.now().millisecondsSinceEpoch - date.millisecondsSinceEpoch;
DateTime.now().millisecondsSinceEpoch - date.millisecondsSinceEpoch;
final daysTmp = (distance / 86400).round(); final daysTmp = (distance / 86400).round();
final days = daysTmp < 1 ? 1 : daysTmp; final days = daysTmp < 1 ? 1 : daysTmp;
@ -695,27 +670,22 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
balance[currency]!.unlockedBalance != unlockedBalance || balance[currency]!.unlockedBalance != unlockedBalance ||
balance[currency]!.frozenBalance != frozenBalance) { balance[currency]!.frozenBalance != frozenBalance) {
balance[currency] = MoneroBalance( balance[currency] = MoneroBalance(
fullBalance: fullBalance, fullBalance: fullBalance, unlockedBalance: unlockedBalance, frozenBalance: frozenBalance);
unlockedBalance: unlockedBalance,
frozenBalance: frozenBalance);
} }
} }
Future<void> _askForUpdateTransactionHistory() async => Future<void> _askForUpdateTransactionHistory() async => await updateTransactions();
await updateTransactions();
int _getFullBalance() => int _getFullBalance() => monero_wallet.getFullBalance(accountIndex: walletAddresses.account!.id);
monero_wallet.getFullBalance(accountIndex: walletAddresses.account!.id);
int _getUnlockedBalance() => monero_wallet.getUnlockedBalance( int _getUnlockedBalance() =>
accountIndex: walletAddresses.account!.id); monero_wallet.getUnlockedBalance(accountIndex: walletAddresses.account!.id);
int _getFrozenBalance() { int _getFrozenBalance() {
var frozenBalance = 0; var frozenBalance = 0;
for (var coin in unspentCoinsInfo.values.where((element) => for (var coin in unspentCoinsInfo.values.where((element) =>
element.walletId == id && element.walletId == id && element.accountIndex == walletAddresses.account!.id)) {
element.accountIndex == walletAddresses.account!.id)) {
if (coin.isFrozen) frozenBalance += coin.value; if (coin.isFrozen) frozenBalance += coin.value;
} }
@ -788,5 +758,4 @@ abstract class MoneroWalletBase extends WalletBase<MoneroBalance,
return monero_wallet.verifyMessage(message, address, signature); return monero_wallet.verifyMessage(message, address, signature);
} }
} }