From 63bd09bb28abbf9bdc4d7ac9c7a8ef4f781e986a Mon Sep 17 00:00:00 2001 From: sneurlax Date: Wed, 25 Nov 2026 18:06:59 -0600 Subject: [PATCH 1/5] Report Monero sync from the wallet and daemon heights --- .../intermediate/lib_monero_wallet.dart | 79 ++++++------------- .../interfaces/cs_monero_interface.dart | 4 +- pubspec.lock | 2 +- .../templates/pubspec.template.yaml | 1 + test/wallets/monero_scan_progress_test.dart | 72 +++++++++++++++++ ...XMR_cs_monero_interface_impl.template.dart | 9 ++- 6 files changed, 109 insertions(+), 58 deletions(-) create mode 100644 test/wallets/monero_scan_progress_test.dart diff --git a/lib/wallets/wallet/intermediate/lib_monero_wallet.dart b/lib/wallets/wallet/intermediate/lib_monero_wallet.dart index cdc807f510..bc2a58ce1f 100644 --- a/lib/wallets/wallet/intermediate/lib_monero_wallet.dart +++ b/lib/wallets/wallet/intermediate/lib_monero_wallet.dart @@ -434,11 +434,7 @@ abstract class LibMoneroWallet // clear blockchain info await mainDB.deleteWalletBlockchainData(walletId); - highestPercentCached = 0; await csMonero.rescanBlockchain(wallet!); - // Reset again once the worker has accepted the rescan. A progress - // reading from before it can land in between and pin the guard near - // 100%, which hides every later reading until the rescan passes it. highestPercentCached = 0; await csMonero.startSyncing(wallet!); unawaited(save()); @@ -812,35 +808,27 @@ abstract class LibMoneroWallet required int syncHeight, required int nodeHeight, String? message, + bool refreshTransactions = true, }) { - if (nodeHeight > 0 && syncHeight >= 0) { + if (nodeHeight > 0 && syncHeight >= 0 && syncHeight <= nodeHeight) { currentKnownChainHeight = nodeHeight; updateChainHeight(); final blocksLeft = nodeHeight - syncHeight; final lib_monero_compat.SyncStatus status; - if (blocksLeft < 100) { + if (blocksLeft == 0) { status = lib_monero_compat.SyncedSyncStatus(); - - // if (!_hasSyncAfterStartup) { - // _hasSyncAfterStartup = true; - // await save(); - // } - // - // if (walletInfo.isRecovery!) { - // await setAsRecovered(); - // } } else { final percent = syncHeight / currentKnownChainHeight; status = lib_monero_compat.SyncingSyncStatus( blocksLeft, percent, - currentKnownChainHeight, + syncHeight, ); } _setSyncStatus(status); - _refreshTxDataHelper(); + if (refreshTransactions) _refreshTxDataHelper(); } } @@ -934,35 +922,19 @@ abstract class LibMoneroWallet if (_syncStatus is lib_monero_compat.SyncingSyncStatus) { final int blocksLeft = _syncStatus.blocksLeft; - // ensure at least 1 to prevent math errors - final int height = max(1, _syncStatus.height); - - final nodeHeight = height + blocksLeft; - currentKnownChainHeight = nodeHeight; - - // final percent = height / nodeHeight; - final percent = _syncStatus.ptc; - - final highest = max(highestPercentCached, percent); - - final unchanged = highest == highestPercentCached; - if (unchanged) { - return; - } - - // update cached - if (highestPercentCached < percent) { - highestPercentCached = percent; - } - + status = WalletSyncStatus.syncing; + highestPercentCached = _syncStatus.ptc; GlobalEventBus.instance.fire( - RefreshPercentChangedEvent(highest, walletId), + RefreshPercentChangedEvent(highestPercentCached, walletId), ); GlobalEventBus.instance.fire( BlocksRemainingEvent(blocksLeft, walletId), ); } else if (_syncStatus is lib_monero_compat.SyncedSyncStatus) { + highestPercentCached = 1; + GlobalEventBus.instance.fire(RefreshPercentChangedEvent(1, walletId)); status = WalletSyncStatus.synced; + GlobalEventBus.instance.fire(BlocksRemainingEvent(0, walletId)); } else if (_syncStatus is lib_monero_compat.NotConnectedSyncStatus) { status = WalletSyncStatus.unableToSync; xmrAndWowSyncSpecificFunctionThatShouldBeGottenRidOfInTheFuture(false); @@ -1195,22 +1167,21 @@ abstract class LibMoneroWallet if (info.otherData[WalletInfoKeys.reuseAddress] != true) { await checkReceivingAddressForTransactions(); } - }); - - Logging.instance.t( - "$runtimeType refresh() wallet != null && await csMonero.isSynced(wallet!)", - ); - final synced = wallet != null && await csMonero.isSynced(wallet!); - Logging.instance.t( - "$runtimeType refresh() wallet != null && await csMonero.isSynced(wallet!) == $synced", - ); - if (synced) { - Logging.instance.t( - "$runtimeType refresh() _setSyncStatus(lib_monero_compat.SyncedSyncStatus());", - ); - _setSyncStatus(lib_monero_compat.SyncedSyncStatus()); - } + final currentWallet = wallet; + if (currentWallet == null) return; + final previousStatus = syncStatus; + final heights = await csMonero.getSyncHeights(currentWallet); + // A listener or node change can deliver newer information during the read. + if (identical(currentWallet, wallet) && + identical(previousStatus, syncStatus)) { + onSyncingUpdate( + syncHeight: heights.syncHeight, + nodeHeight: heights.nodeHeight, + refreshTransactions: false, + ); + } + }); } @override diff --git a/lib/wl_gen/interfaces/cs_monero_interface.dart b/lib/wl_gen/interfaces/cs_monero_interface.dart index 4989bf5c68..009145a8a2 100644 --- a/lib/wl_gen/interfaces/cs_monero_interface.dart +++ b/lib/wl_gen/interfaces/cs_monero_interface.dart @@ -80,7 +80,9 @@ abstract class CsMoneroInterface { Future getPublicSpendKey(WrappedWallet wallet); Future getPrivateSpendKey(WrappedWallet wallet); - Future isSynced(WrappedWallet wallet); + Future<({int syncHeight, int nodeHeight})> getSyncHeights( + WrappedWallet wallet, + ); Future startSyncing(WrappedWallet wallet); Future stopSyncing(WrappedWallet wallet); diff --git a/pubspec.lock b/pubspec.lock index e4b66315c0..562251cc8a 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -960,7 +960,7 @@ packages: source: hosted version: "2.0.1" fake_async: - dependency: transitive + dependency: "direct dev" description: name: fake_async sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44" diff --git a/scripts/app_config/templates/pubspec.template.yaml b/scripts/app_config/templates/pubspec.template.yaml index 3761771c1e..15221258b5 100644 --- a/scripts/app_config/templates/pubspec.template.yaml +++ b/scripts/app_config/templates/pubspec.template.yaml @@ -278,6 +278,7 @@ dependencies: wallet: 0.0.18 dev_dependencies: + fake_async: ^1.3.3 args: ^2.7.0 test: ^1.31.1 yaml: ^3.1.3 diff --git a/test/wallets/monero_scan_progress_test.dart b/test/wallets/monero_scan_progress_test.dart new file mode 100644 index 0000000000..d6e3f6565f --- /dev/null +++ b/test/wallets/monero_scan_progress_test.dart @@ -0,0 +1,72 @@ +import 'package:compat/compat.dart' show SyncedSyncStatus, SyncingSyncStatus; +import 'package:fake_async/fake_async.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/services/event_bus/events/global/blocks_remaining_event.dart'; +import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart'; +import 'package:stackwallet/services/event_bus/global_event_bus.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; +import 'package:stackwallet/wallets/wallet/impl/monero_wallet.dart'; + +class _Wallet extends MoneroWallet { + _Wallet() : super(CryptoCurrencyNetwork.main); + + @override + String get walletId => 'sync-test'; + + @override + late final info = WalletInfo( + walletId: walletId, + name: 'XMR', + mainAddressType: AddressType.cryptonote, + coinName: cryptoCurrency.identifier, + ); + + @override + Future updateChainHeight() async {} + + // Keep the asynchronous history refresh pending while delivering scan events. + @override + Future updateTransactions() => + Future.delayed(const Duration(seconds: 1)); +} + +void main() { + test('XMR publishes syncing until the scan reaches the current tip', () { + fakeAsync((clock) { + final wallet = _Wallet(); + final statuses = []; + final blocks = []; + final statusSubscription = GlobalEventBus.instance + .on() + .listen((event) => statuses.add(event.newStatus)); + final blocksSubscription = GlobalEventBus.instance + .on() + .listen((event) => blocks.add(event.blocksRemaining)); + + wallet.onSyncingUpdate(syncHeight: 0, nodeHeight: 0); + wallet.onSyncingUpdate(syncHeight: 101, nodeHeight: 100); + expect(wallet.syncStatus, isNull); + wallet.onSyncingUpdate(syncHeight: 1, nodeHeight: 100); + wallet.onSyncingUpdate(syncHeight: 99, nodeHeight: 100); + expect(wallet.currentKnownChainHeight, 100); + expect(wallet.syncStatus!.progress(), .99); + wallet.onSyncingUpdate(syncHeight: 100, nodeHeight: 100); + expect(wallet.syncStatus, isA()); + wallet.onSyncingUpdate(syncHeight: 100, nodeHeight: 101); + expect(wallet.syncStatus, isA()); + clock.flushMicrotasks(); + + expect(statuses, [ + WalletSyncStatus.syncing, + WalletSyncStatus.syncing, + WalletSyncStatus.synced, + WalletSyncStatus.syncing, + ]); + expect(blocks, [99, 1, 0, 1]); + statusSubscription.cancel(); + blocksSubscription.cancel(); + }); + }); +} diff --git a/tool/wl_templates/XMR_cs_monero_interface_impl.template.dart b/tool/wl_templates/XMR_cs_monero_interface_impl.template.dart index ad63def12b..6afa27f1b8 100644 --- a/tool/wl_templates/XMR_cs_monero_interface_impl.template.dart +++ b/tool/wl_templates/XMR_cs_monero_interface_impl.template.dart @@ -217,8 +217,13 @@ class _CsMoneroInterfaceImpl extends CsMoneroInterface { wallet.get().getPrivateSpendKey(); @override - Future isSynced(WrappedWallet wallet) => - wallet.get().isSynced(); + Future<({int syncHeight, int nodeHeight})> getSyncHeights( + WrappedWallet wallet, + ) async { + final native = wallet.get(); + final syncHeight = await native.getCurrentWalletSyncingHeight(); + return (syncHeight: syncHeight, nodeHeight: await native.getDaemonHeight()); + } @override Future startSyncing(WrappedWallet wallet) => From b1161f9068dda66537ab0b103941df6e21f407f1 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Fri, 27 Nov 2026 14:12:55 -0600 Subject: [PATCH 2/5] fix: harden Monero sync height updates --- .../intermediate/lib_monero_wallet.dart | 52 +++++++++++----- test/wallets/monero_scan_progress_test.dart | 60 ++++++++++++++++++- 2 files changed, 97 insertions(+), 15 deletions(-) diff --git a/lib/wallets/wallet/intermediate/lib_monero_wallet.dart b/lib/wallets/wallet/intermediate/lib_monero_wallet.dart index bc2a58ce1f..83d48e5817 100644 --- a/lib/wallets/wallet/intermediate/lib_monero_wallet.dart +++ b/lib/wallets/wallet/intermediate/lib_monero_wallet.dart @@ -5,6 +5,7 @@ import 'dart:math'; import 'package:compat/compat.dart' as lib_monero_compat; import 'package:isar_community/isar.dart'; +import 'package:meta/meta.dart'; import 'package:mutex/mutex.dart'; import 'package:stack_wallet_backup/generate_password.dart'; @@ -114,6 +115,7 @@ abstract class LibMoneroWallet lib_monero_compat.SyncStatus? get syncStatus => _syncStatus; lib_monero_compat.SyncStatus? _syncStatus; int _syncedCount = 0; + int _syncUpdateGeneration = 0; void _setSyncStatus(lib_monero_compat.SyncStatus status) { if (status is lib_monero_compat.SyncedSyncStatus) { if (_syncStatus is lib_monero_compat.SyncedSyncStatus) { @@ -808,12 +810,24 @@ abstract class LibMoneroWallet required int syncHeight, required int nodeHeight, String? message, - bool refreshTransactions = true, }) { - if (nodeHeight > 0 && syncHeight >= 0 && syncHeight <= nodeHeight) { + _syncUpdateGeneration++; + _applySyncingUpdate( + syncHeight: syncHeight, + nodeHeight: nodeHeight, + refreshTransactions: true, + ); + } + + void _applySyncingUpdate({ + required int syncHeight, + required int nodeHeight, + required bool refreshTransactions, + }) { + if (nodeHeight > 0 && syncHeight >= 0) { currentKnownChainHeight = nodeHeight; updateChainHeight(); - final blocksLeft = nodeHeight - syncHeight; + final blocksLeft = max(0, nodeHeight - syncHeight); final lib_monero_compat.SyncStatus status; if (blocksLeft == 0) { status = lib_monero_compat.SyncedSyncStatus(); @@ -832,6 +846,23 @@ abstract class LibMoneroWallet } } + @protected + Future updateSyncStatusFromPolledHeights({ + required WrappedWallet currentWallet, + required Future<({int syncHeight, int nodeHeight})> Function() readHeights, + }) async { + final generation = _syncUpdateGeneration; + final heights = await readHeights(); + if (identical(currentWallet, wallet) && + generation == _syncUpdateGeneration) { + _applySyncingUpdate( + syncHeight: heights.syncHeight, + nodeHeight: heights.nodeHeight, + refreshTransactions: false, + ); + } + } + void onBalancesChanged({ required BigInt newBalance, required BigInt newUnlockedBalance, @@ -1170,17 +1201,10 @@ abstract class LibMoneroWallet final currentWallet = wallet; if (currentWallet == null) return; - final previousStatus = syncStatus; - final heights = await csMonero.getSyncHeights(currentWallet); - // A listener or node change can deliver newer information during the read. - if (identical(currentWallet, wallet) && - identical(previousStatus, syncStatus)) { - onSyncingUpdate( - syncHeight: heights.syncHeight, - nodeHeight: heights.nodeHeight, - refreshTransactions: false, - ); - } + await updateSyncStatusFromPolledHeights( + currentWallet: currentWallet, + readHeights: () => csMonero.getSyncHeights(currentWallet), + ); }); } diff --git a/test/wallets/monero_scan_progress_test.dart b/test/wallets/monero_scan_progress_test.dart index d6e3f6565f..c8094890f2 100644 --- a/test/wallets/monero_scan_progress_test.dart +++ b/test/wallets/monero_scan_progress_test.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:compat/compat.dart' show SyncedSyncStatus, SyncingSyncStatus; import 'package:fake_async/fake_async.dart'; import 'package:flutter_test/flutter_test.dart'; @@ -8,6 +10,8 @@ import 'package:stackwallet/services/event_bus/global_event_bus.dart'; import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; import 'package:stackwallet/wallets/wallet/impl/monero_wallet.dart'; +import 'package:stackwallet/wl_gen/interfaces/cs_salvium_interface.dart' + show WrappedWallet; class _Wallet extends MoneroWallet { _Wallet() : super(CryptoCurrencyNetwork.main); @@ -30,6 +34,13 @@ class _Wallet extends MoneroWallet { @override Future updateTransactions() => Future.delayed(const Duration(seconds: 1)); + + Future applyPolledHeights( + Future<({int syncHeight, int nodeHeight})> Function() readHeights, + ) => updateSyncStatusFromPolledHeights( + currentWallet: wallet!, + readHeights: readHeights, + ); } void main() { @@ -46,7 +57,6 @@ void main() { .listen((event) => blocks.add(event.blocksRemaining)); wallet.onSyncingUpdate(syncHeight: 0, nodeHeight: 0); - wallet.onSyncingUpdate(syncHeight: 101, nodeHeight: 100); expect(wallet.syncStatus, isNull); wallet.onSyncingUpdate(syncHeight: 1, nodeHeight: 100); wallet.onSyncingUpdate(syncHeight: 99, nodeHeight: 100); @@ -69,4 +79,52 @@ void main() { blocksSubscription.cancel(); }); }); + + test('XMR treats a wallet ahead of its node as caught up', () { + fakeAsync((_) { + final wallet = _Wallet(); + wallet.onSyncingUpdate(syncHeight: 99, nodeHeight: 100); + expect(wallet.syncStatus, isA()); + + wallet.onSyncingUpdate(syncHeight: 101, nodeHeight: 100); + expect(wallet.syncStatus, isA()); + expect(wallet.syncStatus!.progress(), 1); + }); + }); + + test('a delayed height read cannot overwrite a newer listener update', () { + fakeAsync((clock) { + final wallet = _Wallet()..wallet = const WrappedWallet('test-wallet'); + + unawaited( + wallet.applyPolledHeights( + () async => (syncHeight: 99, nodeHeight: 100), + ), + ); + clock.flushMicrotasks(); + expect(wallet.syncStatus, isA()); + + // Saturate the repeated-synced suppression so the next listener update + // does not replace the status object used by the old identity guard. + for (var i = 0; i < 4; i++) { + wallet.onSyncingUpdate(syncHeight: 100, nodeHeight: 100); + } + + final heights = Completer<({int syncHeight, int nodeHeight})>(); + var completed = false; + unawaited( + wallet + .applyPolledHeights(() => heights.future) + .then((_) => completed = true), + ); + clock.flushMicrotasks(); + + wallet.onSyncingUpdate(syncHeight: 101, nodeHeight: 101); + heights.complete((syncHeight: 99, nodeHeight: 100)); + clock.flushMicrotasks(); + + expect(completed, isTrue); + expect(wallet.syncStatus, isA()); + }); + }); } From 55999130c5a2075c8b8fe3a10233ab417aa5ed44 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Mon, 30 Nov 2026 11:10:41 -0600 Subject: [PATCH 3/5] fix: verify Monero daemon sync readiness and invalidate polls on status changes --- .../intermediate/lib_monero_wallet.dart | 55 +++- .../interfaces/cs_monero_interface.dart | 1 + test/wallets/monero_scan_progress_test.dart | 285 +++++++++++++++--- ...XMR_cs_monero_interface_impl.template.dart | 4 + 4 files changed, 297 insertions(+), 48 deletions(-) diff --git a/lib/wallets/wallet/intermediate/lib_monero_wallet.dart b/lib/wallets/wallet/intermediate/lib_monero_wallet.dart index 83d48e5817..cd056360a8 100644 --- a/lib/wallets/wallet/intermediate/lib_monero_wallet.dart +++ b/lib/wallets/wallet/intermediate/lib_monero_wallet.dart @@ -117,6 +117,7 @@ abstract class LibMoneroWallet int _syncedCount = 0; int _syncUpdateGeneration = 0; void _setSyncStatus(lib_monero_compat.SyncStatus status) { + _syncUpdateGeneration++; if (status is lib_monero_compat.SyncedSyncStatus) { if (_syncStatus is lib_monero_compat.SyncedSyncStatus) { _syncedCount++; @@ -548,6 +549,7 @@ abstract class LibMoneroWallet @override Future updateNode() async { + _syncUpdateGeneration++; final node = getCurrentNode(); if (await _torNodeMismatchGuard(node)) { @@ -775,6 +777,7 @@ abstract class LibMoneroWallet @override Future exit() async { + _syncUpdateGeneration++; await super.exit(); Logging.instance.i("exit called on monero $walletId!"); if (wallet != null) { @@ -811,12 +814,13 @@ abstract class LibMoneroWallet required int nodeHeight, String? message, }) { - _syncUpdateGeneration++; - _applySyncingUpdate( - syncHeight: syncHeight, - nodeHeight: nodeHeight, - refreshTransactions: true, - ); + if (nodeHeight > 0 && syncHeight >= 0 && syncHeight <= nodeHeight) { + _applySyncingUpdate( + syncHeight: syncHeight, + nodeHeight: nodeHeight, + refreshTransactions: true, + ); + } } void _applySyncingUpdate({ @@ -850,17 +854,37 @@ abstract class LibMoneroWallet Future updateSyncStatusFromPolledHeights({ required WrappedWallet currentWallet, required Future<({int syncHeight, int nodeHeight})> Function() readHeights, + required Future Function() isSynced, + int? expectedGeneration, }) async { - final generation = _syncUpdateGeneration; + final generation = expectedGeneration ?? _syncUpdateGeneration; + if (!identical(currentWallet, wallet) || + generation != _syncUpdateGeneration) { + return; + } + final heights = await readHeights(); - if (identical(currentWallet, wallet) && - generation == _syncUpdateGeneration) { - _applySyncingUpdate( - syncHeight: heights.syncHeight, - nodeHeight: heights.nodeHeight, - refreshTransactions: false, - ); + if (!identical(currentWallet, wallet) || + generation != _syncUpdateGeneration || + heights.nodeHeight <= 0 || + heights.syncHeight < 0) { + return; + } + + if (heights.syncHeight >= heights.nodeHeight) { + final synced = await isSynced(); + if (!identical(currentWallet, wallet) || + generation != _syncUpdateGeneration || + !synced) { + return; + } } + + _applySyncingUpdate( + syncHeight: heights.syncHeight, + nodeHeight: heights.nodeHeight, + refreshTransactions: false, + ); } void onBalancesChanged({ @@ -1186,6 +1210,7 @@ abstract class LibMoneroWallet "$runtimeType refresh() _setSyncStatus(lib_monero_compat.StartingSyncStatus());", ); _setSyncStatus(lib_monero_compat.StartingSyncStatus()); + final syncGeneration = _syncUpdateGeneration; Logging.instance.t("$runtimeType refresh() await updateTransactions();"); await updateTransactions(); @@ -1203,7 +1228,9 @@ abstract class LibMoneroWallet if (currentWallet == null) return; await updateSyncStatusFromPolledHeights( currentWallet: currentWallet, + expectedGeneration: syncGeneration, readHeights: () => csMonero.getSyncHeights(currentWallet), + isSynced: () => csMonero.isSynced(currentWallet), ); }); } diff --git a/lib/wl_gen/interfaces/cs_monero_interface.dart b/lib/wl_gen/interfaces/cs_monero_interface.dart index 009145a8a2..2aa3d031ae 100644 --- a/lib/wl_gen/interfaces/cs_monero_interface.dart +++ b/lib/wl_gen/interfaces/cs_monero_interface.dart @@ -80,6 +80,7 @@ abstract class CsMoneroInterface { Future getPublicSpendKey(WrappedWallet wallet); Future getPrivateSpendKey(WrappedWallet wallet); + Future isSynced(WrappedWallet wallet); Future<({int syncHeight, int nodeHeight})> getSyncHeights( WrappedWallet wallet, ); diff --git a/test/wallets/monero_scan_progress_test.dart b/test/wallets/monero_scan_progress_test.dart index c8094890f2..5486b0993b 100644 --- a/test/wallets/monero_scan_progress_test.dart +++ b/test/wallets/monero_scan_progress_test.dart @@ -1,20 +1,36 @@ import 'dart:async'; -import 'package:compat/compat.dart' show SyncedSyncStatus, SyncingSyncStatus; +import 'package:compat/compat.dart' + show FailedSyncStatus, SyncedSyncStatus, SyncingSyncStatus; import 'package:fake_async/fake_async.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/models/node_model.dart'; import 'package:stackwallet/services/event_bus/events/global/blocks_remaining_event.dart'; import 'package:stackwallet/services/event_bus/events/global/wallet_sync_status_changed_event.dart'; import 'package:stackwallet/services/event_bus/global_event_bus.dart'; +import 'package:stackwallet/utilities/enums/sync_type_enum.dart'; +import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart'; +import 'package:stackwallet/utilities/prefs.dart'; import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; import 'package:stackwallet/wallets/wallet/impl/monero_wallet.dart'; import 'package:stackwallet/wl_gen/interfaces/cs_salvium_interface.dart' show WrappedWallet; +class _Prefs extends Fake implements Prefs { + @override + bool get useTor => false; + + @override + SyncingType get syncType => SyncingType.allWalletsOnStartup; +} + class _Wallet extends MoneroWallet { - _Wallet() : super(CryptoCurrencyNetwork.main); + _Wallet() : super(CryptoCurrencyNetwork.main) { + prefs = _Prefs(); + secureStorageInterface = FakeSecureStorage(); + } @override String get walletId => 'sync-test'; @@ -27,6 +43,22 @@ class _Wallet extends MoneroWallet { coinName: cryptoCurrency.identifier, ); + @override + NodeModel getCurrentNode() => NodeModel( + host: 'https://node.example.com', + port: 18081, + name: 'Test Node', + id: 'test-node', + useSSL: true, + enabled: true, + coinName: cryptoCurrency.identifier, + isFailover: false, + isDown: false, + torEnabled: false, + clearnetEnabled: true, + isPrimary: true, + ); + @override Future updateChainHeight() async {} @@ -36,10 +68,14 @@ class _Wallet extends MoneroWallet { Future.delayed(const Duration(seconds: 1)); Future applyPolledHeights( - Future<({int syncHeight, int nodeHeight})> Function() readHeights, - ) => updateSyncStatusFromPolledHeights( + Future<({int syncHeight, int nodeHeight})> Function() readHeights, { + Future Function()? isSynced, + int? expectedGeneration, + }) => updateSyncStatusFromPolledHeights( currentWallet: wallet!, + expectedGeneration: expectedGeneration, readHeights: readHeights, + isSynced: isSynced ?? () async => true, ); } @@ -56,39 +92,133 @@ void main() { .on() .listen((event) => blocks.add(event.blocksRemaining)); - wallet.onSyncingUpdate(syncHeight: 0, nodeHeight: 0); - expect(wallet.syncStatus, isNull); - wallet.onSyncingUpdate(syncHeight: 1, nodeHeight: 100); - wallet.onSyncingUpdate(syncHeight: 99, nodeHeight: 100); - expect(wallet.currentKnownChainHeight, 100); - expect(wallet.syncStatus!.progress(), .99); - wallet.onSyncingUpdate(syncHeight: 100, nodeHeight: 100); - expect(wallet.syncStatus, isA()); - wallet.onSyncingUpdate(syncHeight: 100, nodeHeight: 101); - expect(wallet.syncStatus, isA()); - clock.flushMicrotasks(); + try { + wallet.onSyncingUpdate(syncHeight: 0, nodeHeight: 0); + wallet.onSyncingUpdate(syncHeight: 101, nodeHeight: 100); + expect(wallet.syncStatus, isNull); + expect(wallet.currentKnownChainHeight, 0); + + wallet.onSyncingUpdate(syncHeight: 1, nodeHeight: 100); + wallet.onSyncingUpdate(syncHeight: 99, nodeHeight: 100); + expect(wallet.currentKnownChainHeight, 100); + expect(wallet.syncStatus!.progress(), .99); + wallet.onSyncingUpdate(syncHeight: 100, nodeHeight: 100); + expect(wallet.syncStatus, isA()); + wallet.onSyncingUpdate(syncHeight: 100, nodeHeight: 101); + expect(wallet.syncStatus, isA()); + clock.flushMicrotasks(); - expect(statuses, [ - WalletSyncStatus.syncing, - WalletSyncStatus.syncing, - WalletSyncStatus.synced, - WalletSyncStatus.syncing, - ]); - expect(blocks, [99, 1, 0, 1]); - statusSubscription.cancel(); - blocksSubscription.cancel(); + expect(statuses, [ + WalletSyncStatus.syncing, + WalletSyncStatus.syncing, + WalletSyncStatus.synced, + WalletSyncStatus.syncing, + ]); + expect(blocks, [99, 1, 0, 1]); + } finally { + statusSubscription.cancel(); + blocksSubscription.cancel(); + } }); }); - test('XMR treats a wallet ahead of its node as caught up', () { - fakeAsync((_) { - final wallet = _Wallet(); - wallet.onSyncingUpdate(syncHeight: 99, nodeHeight: 100); + test('polled heights require native sync before reporting caught up', () { + fakeAsync((clock) { + final wallet = _Wallet()..wallet = const WrappedWallet('test-wallet'); + + // Reopened wallet whose saved height is ahead of a catching-up daemon. + unawaited( + wallet.applyPolledHeights( + () async => (syncHeight: 200, nodeHeight: 100), + isSynced: () async => false, + ), + ); + clock.flushMicrotasks(); + expect(wallet.syncStatus, isNull); + expect(wallet.canEstimateFee, isFalse); + expect(wallet.currentKnownChainHeight, 0); + expect(wallet.highestPercentCached, 0); + + // Reopened wallet equal to a catching-up daemon is also not ready. + unawaited( + wallet.applyPolledHeights( + () async => (syncHeight: 100, nodeHeight: 100), + isSynced: () async => false, + ), + ); + clock.flushMicrotasks(); + expect(wallet.syncStatus, isNull); + expect(wallet.canEstimateFee, isFalse); + + // Invalid daemon height does not query isSynced or change status. + var isSyncedCalls = 0; + unawaited( + wallet.applyPolledHeights( + () async => (syncHeight: 0, nodeHeight: 0), + isSynced: () async { + isSyncedCalls++; + return true; + }, + ), + ); + clock.flushMicrotasks(); + expect(isSyncedCalls, 0); + expect(wallet.syncStatus, isNull); + + // Behind daemon reports syncing directly without needing isSynced. + unawaited( + wallet.applyPolledHeights( + () async => (syncHeight: 99, nodeHeight: 100), + isSynced: () async { + isSyncedCalls++; + return false; + }, + ), + ); + clock.flushMicrotasks(); + expect(isSyncedCalls, 0); expect(wallet.syncStatus, isA()); + expect((wallet.syncStatus as SyncingSyncStatus).blocksLeft, 1); + expect(wallet.canEstimateFee, isFalse); - wallet.onSyncingUpdate(syncHeight: 101, nodeHeight: 100); + // Equal to a catching-up daemon preserves the syncing status. + unawaited( + wallet.applyPolledHeights( + () async => (syncHeight: 100, nodeHeight: 100), + isSynced: () async => false, + ), + ); + clock.flushMicrotasks(); + expect(wallet.syncStatus, isA()); + expect(wallet.canEstimateFee, isFalse); + + // Once the daemon is synced, ahead-of-tip reports caught up. + unawaited( + wallet.applyPolledHeights( + () async => (syncHeight: 200, nodeHeight: 100), + isSynced: () async => true, + ), + ); + clock.flushMicrotasks(); expect(wallet.syncStatus, isA()); expect(wallet.syncStatus!.progress(), 1); + expect(wallet.currentKnownChainHeight, 100); + expect(wallet.canEstimateFee, isTrue); + + // Reset to syncing, then reach tip with native sync confirmed. + wallet.onSyncingUpdate(syncHeight: 100, nodeHeight: 101); + expect(wallet.syncStatus, isA()); + expect(wallet.canEstimateFee, isFalse); + + unawaited( + wallet.applyPolledHeights( + () async => (syncHeight: 101, nodeHeight: 101), + isSynced: () async => true, + ), + ); + clock.flushMicrotasks(); + expect(wallet.syncStatus, isA()); + expect(wallet.canEstimateFee, isTrue); }); }); @@ -96,11 +226,13 @@ void main() { fakeAsync((clock) { final wallet = _Wallet()..wallet = const WrappedWallet('test-wallet'); - unawaited( - wallet.applyPolledHeights( - () async => (syncHeight: 99, nodeHeight: 100), - ), - ); + // Ignored listener readings do not invalidate an in-flight poll. + final validPoll = Completer<({int syncHeight, int nodeHeight})>(); + unawaited(wallet.applyPolledHeights(() => validPoll.future)); + clock.flushMicrotasks(); + wallet.onSyncingUpdate(syncHeight: 0, nodeHeight: 0); + wallet.onSyncingUpdate(syncHeight: 101, nodeHeight: 100); + validPoll.complete((syncHeight: 99, nodeHeight: 100)); clock.flushMicrotasks(); expect(wallet.syncStatus, isA()); @@ -127,4 +259,89 @@ void main() { expect(wallet.syncStatus, isA()); }); }); + + test('a failed node switch invalidates pending height reads', () { + fakeAsync((clock) { + final wallet = _Wallet()..wallet = const WrappedWallet('test-wallet'); + final statuses = []; + final statusSubscription = GlobalEventBus.instance + .on() + .listen((event) => statuses.add(event.newStatus)); + + try { + // Case 1: readHeights is pending when updateNode fails. + final heights = Completer<({int syncHeight, int nodeHeight})>(); + unawaited(wallet.applyPolledHeights(() => heights.future)); + clock.flushMicrotasks(); + + unawaited(wallet.updateNode()); + clock.flushMicrotasks(); + expect(wallet.syncStatus, isA()); + expect(wallet.canEstimateFee, isFalse); + + heights.complete((syncHeight: 99, nodeHeight: 100)); + clock.flushMicrotasks(); + expect(wallet.syncStatus, isA()); + expect(wallet.canEstimateFee, isFalse); + expect(statuses.last, WalletSyncStatus.unableToSync); + + // Case 2: isSynced is pending when updateNode fails. + final isSynced = Completer(); + unawaited( + wallet.applyPolledHeights( + () async => (syncHeight: 100, nodeHeight: 100), + isSynced: () => isSynced.future, + ), + ); + clock.flushMicrotasks(); + + unawaited(wallet.updateNode()); + clock.flushMicrotasks(); + expect(wallet.syncStatus, isA()); + + isSynced.complete(true); + clock.flushMicrotasks(); + expect(wallet.syncStatus, isA()); + expect(wallet.canEstimateFee, isFalse); + expect(statuses.last, WalletSyncStatus.unableToSync); + + // Case 3: stale expectedGeneration skips readHeights altogether. + var readCalled = false; + unawaited( + wallet.applyPolledHeights(() async { + readCalled = true; + return (syncHeight: 99, nodeHeight: 100); + }, expectedGeneration: 0), + ); + clock.flushMicrotasks(); + expect(readCalled, isFalse); + expect(wallet.syncStatus, isA()); + expect(wallet.canEstimateFee, isFalse); + } finally { + statusSubscription.cancel(); + } + }); + }); + + test('exit invalidates pending height reads', () { + fakeAsync((clock) { + final wallet = _Wallet()..wallet = const WrappedWallet('test-wallet'); + final heights = Completer<({int syncHeight, int nodeHeight})>(); + unawaited(wallet.applyPolledHeights(() => heights.future)); + clock.flushMicrotasks(); + + Object? exitError; + unawaited( + wallet.exit().catchError((Object error) { + exitError = error; + }), + ); + clock.flushMicrotasks(); + expect(exitError, isA()); + + heights.complete((syncHeight: 99, nodeHeight: 100)); + clock.flushMicrotasks(); + expect(wallet.syncStatus, isNull); + }); + }); } diff --git a/tool/wl_templates/XMR_cs_monero_interface_impl.template.dart b/tool/wl_templates/XMR_cs_monero_interface_impl.template.dart index 6afa27f1b8..abda1395f5 100644 --- a/tool/wl_templates/XMR_cs_monero_interface_impl.template.dart +++ b/tool/wl_templates/XMR_cs_monero_interface_impl.template.dart @@ -216,6 +216,10 @@ class _CsMoneroInterfaceImpl extends CsMoneroInterface { Future getPrivateSpendKey(WrappedWallet wallet) => wallet.get().getPrivateSpendKey(); + @override + Future isSynced(WrappedWallet wallet) => + wallet.get().isSynced(); + @override Future<({int syncHeight, int nodeHeight})> getSyncHeights( WrappedWallet wallet, From 29055f979720578a4bf2131aeb990e9e596ecf97 Mon Sep 17 00:00:00 2001 From: sneurlax Date: Mon, 30 Nov 2026 11:39:14 -0600 Subject: [PATCH 4/5] fix: poll new Monero node after a switch during refresh --- .../intermediate/lib_monero_wallet.dart | 113 ++++-- test/wallets/monero_scan_progress_test.dart | 333 +++++++++++++++++- 2 files changed, 425 insertions(+), 21 deletions(-) diff --git a/lib/wallets/wallet/intermediate/lib_monero_wallet.dart b/lib/wallets/wallet/intermediate/lib_monero_wallet.dart index cd056360a8..3ce0f34d8e 100644 --- a/lib/wallets/wallet/intermediate/lib_monero_wallet.dart +++ b/lib/wallets/wallet/intermediate/lib_monero_wallet.dart @@ -116,8 +116,15 @@ abstract class LibMoneroWallet lib_monero_compat.SyncStatus? _syncStatus; int _syncedCount = 0; int _syncUpdateGeneration = 0; + bool _isRefreshing = false; + int? _pendingNodeSwitchPollGeneration; void _setSyncStatus(lib_monero_compat.SyncStatus status) { _syncUpdateGeneration++; + if (status is lib_monero_compat.ConnectedSyncStatus && _isRefreshing) { + _pendingNodeSwitchPollGeneration = _syncUpdateGeneration; + } else { + _pendingNodeSwitchPollGeneration = null; + } if (status is lib_monero_compat.SyncedSyncStatus) { if (_syncStatus is lib_monero_compat.SyncedSyncStatus) { _syncedCount++; @@ -547,9 +554,15 @@ abstract class LibMoneroWallet } } + @protected + void onNodeConnected() { + _setSyncStatus(lib_monero_compat.ConnectedSyncStatus()); + } + @override Future updateNode() async { _syncUpdateGeneration++; + _pendingNodeSwitchPollGeneration = null; final node = getCurrentNode(); if (await _torNodeMismatchGuard(node)) { @@ -601,7 +614,7 @@ abstract class LibMoneroWallet await csMonero.startListeners(wallet!); csMonero.startAutoSaving(wallet!); - _setSyncStatus(lib_monero_compat.ConnectedSyncStatus()); + onNodeConnected(); } catch (e, s) { _setSyncStatus(lib_monero_compat.FailedSyncStatus()); Logging.instance.e( @@ -778,6 +791,7 @@ abstract class LibMoneroWallet @override Future exit() async { _syncUpdateGeneration++; + _pendingNodeSwitchPollGeneration = null; await super.exit(); Logging.instance.i("exit called on monero $walletId!"); if (wallet != null) { @@ -1173,8 +1187,16 @@ abstract class LibMoneroWallet await info.updateBalance(newBalance: balance, isar: mainDB.isar); } - @override - Future refresh() async { + @protected + Future runRefreshWithSyncStatusPoll({ + required Future Function() prepareRefresh, + required Future Function() refreshData, + required Future<({int syncHeight, int nodeHeight})> Function( + WrappedWallet wallet, + ) + readHeights, + required Future Function(WrappedWallet wallet) isSynced, + }) async { // Awaiting this lock could be dangerous. // Since refresh is periodic (generally) if (refreshMutex.isLocked) { @@ -1190,6 +1212,68 @@ abstract class LibMoneroWallet "$runtimeType refresh() refreshMutex.acquire() waiting...", ); await refreshMutex.protect(() async { + _isRefreshing = true; + var refreshFailed = false; + try { + await prepareRefresh(); + Logging.instance.t( + "$runtimeType refresh() " + "_setSyncStatus(lib_monero_compat.StartingSyncStatus());", + ); + _setSyncStatus(lib_monero_compat.StartingSyncStatus()); + final syncGeneration = _syncUpdateGeneration; + + await refreshData(); + + final currentWallet = wallet; + if (currentWallet == null) return; + await updateSyncStatusFromPolledHeights( + currentWallet: currentWallet, + expectedGeneration: syncGeneration, + readHeights: () => readHeights(currentWallet), + isSynced: () => isSynced(currentWallet), + ); + } catch (_) { + refreshFailed = true; + rethrow; + } finally { + try { + while (true) { + final pendingGeneration = _pendingNodeSwitchPollGeneration; + final currentWallet = wallet; + if (pendingGeneration == null || + currentWallet == null || + pendingGeneration != _syncUpdateGeneration) { + _pendingNodeSwitchPollGeneration = null; + break; + } + _pendingNodeSwitchPollGeneration = null; + try { + await updateSyncStatusFromPolledHeights( + currentWallet: currentWallet, + expectedGeneration: pendingGeneration, + readHeights: () => readHeights(currentWallet), + isSynced: () => isSynced(currentWallet), + ); + } catch (e, s) { + if (!refreshFailed) rethrow; + Logging.instance.w( + "Pending node switch height check failed: ", + error: e, + stackTrace: s, + ); + } + } + } finally { + _isRefreshing = false; + } + } + }); + } + + @override + Future refresh() => runRefreshWithSyncStatusPoll( + prepareRefresh: () async { Logging.instance.t( "$runtimeType refresh() final node = getCurrentNode();", ); @@ -1206,12 +1290,8 @@ abstract class LibMoneroWallet "$runtimeType refresh() it csMonero.startSyncing(wallet!);", ); await csMonero.startSyncing(wallet!); - Logging.instance.t( - "$runtimeType refresh() _setSyncStatus(lib_monero_compat.StartingSyncStatus());", - ); - _setSyncStatus(lib_monero_compat.StartingSyncStatus()); - final syncGeneration = _syncUpdateGeneration; - + }, + refreshData: () async { Logging.instance.t("$runtimeType refresh() await updateTransactions();"); await updateTransactions(); Logging.instance.t("$runtimeType refresh() await updateBalance();"); @@ -1223,17 +1303,10 @@ abstract class LibMoneroWallet if (info.otherData[WalletInfoKeys.reuseAddress] != true) { await checkReceivingAddressForTransactions(); } - - final currentWallet = wallet; - if (currentWallet == null) return; - await updateSyncStatusFromPolledHeights( - currentWallet: currentWallet, - expectedGeneration: syncGeneration, - readHeights: () => csMonero.getSyncHeights(currentWallet), - isSynced: () => csMonero.isSynced(currentWallet), - ); - }); - } + }, + readHeights: csMonero.getSyncHeights, + isSynced: csMonero.isSynced, + ); @override Future generateNewReceivingAddress() async { diff --git a/test/wallets/monero_scan_progress_test.dart b/test/wallets/monero_scan_progress_test.dart index 5486b0993b..bc0da0eb10 100644 --- a/test/wallets/monero_scan_progress_test.dart +++ b/test/wallets/monero_scan_progress_test.dart @@ -1,7 +1,12 @@ import 'dart:async'; import 'package:compat/compat.dart' - show FailedSyncStatus, SyncedSyncStatus, SyncingSyncStatus; + show + ConnectedSyncStatus, + FailedSyncStatus, + StartingSyncStatus, + SyncedSyncStatus, + SyncingSyncStatus; import 'package:fake_async/fake_async.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; @@ -77,6 +82,23 @@ class _Wallet extends MoneroWallet { readHeights: readHeights, isSynced: isSynced ?? () async => true, ); + + Future runTestRefresh({ + Future Function()? prepareRefresh, + required Future Function() refreshData, + required Future<({int syncHeight, int nodeHeight})> Function( + WrappedWallet wallet, + ) + readHeights, + Future Function(WrappedWallet wallet)? isSynced, + }) => runRefreshWithSyncStatusPoll( + prepareRefresh: prepareRefresh ?? () async {}, + refreshData: refreshData, + readHeights: readHeights, + isSynced: isSynced ?? (_) async => true, + ); + + void notifyNodeConnected() => onNodeConnected(); } void main() { @@ -344,4 +366,313 @@ void main() { expect(wallet.syncStatus, isNull); }); }); + + test( + 'a successful node switch during refreshData polls the new node once', + () { + fakeAsync((clock) { + final wallet = _Wallet()..wallet = const WrappedWallet('test-wallet'); + final statuses = []; + final statusSubscription = GlobalEventBus.instance + .on() + .listen((event) => statuses.add(event.newStatus)); + + try { + final refreshData = Completer(); + var refreshDataCalls = 0; + var readHeightsCalls = 0; + var isSyncedCalls = 0; + + unawaited( + wallet.runTestRefresh( + refreshData: () { + refreshDataCalls++; + return refreshData.future; + }, + readHeights: (_) async { + readHeightsCalls++; + return (syncHeight: 100, nodeHeight: 100); + }, + isSynced: (_) async { + isSyncedCalls++; + return true; + }, + ), + ); + clock.flushMicrotasks(); + expect(wallet.refreshMutex.isLocked, isTrue); + expect(wallet.syncStatus, isA()); + + // Simulate a successful node switch while refreshData is in flight. + wallet.notifyNodeConnected(); + expect(wallet.syncStatus, isA()); + expect(wallet.canEstimateFee, isFalse); + + // Simulate nodeChangeNotifier's follow-up refreshes while locked. + unawaited( + wallet.runTestRefresh( + refreshData: () async { + refreshDataCalls++; + }, + readHeights: (_) async { + readHeightsCalls++; + return (syncHeight: 100, nodeHeight: 100); + }, + ), + ); + unawaited( + wallet.runTestRefresh( + refreshData: () async { + refreshDataCalls++; + }, + readHeights: (_) async { + readHeightsCalls++; + return (syncHeight: 100, nodeHeight: 100); + }, + ), + ); + clock.flushMicrotasks(); + expect(refreshDataCalls, 1); + expect(readHeightsCalls, 0); + + refreshData.complete(); + clock.flushMicrotasks(); + + expect(readHeightsCalls, 1); + expect(isSyncedCalls, 1); + expect(wallet.syncStatus, isA()); + expect(wallet.canEstimateFee, isTrue); + expect(wallet.refreshMutex.isLocked, isFalse); + expect(statuses.last, WalletSyncStatus.synced); + } finally { + statusSubscription.cancel(); + } + }); + }, + ); + + test('a successful node switch during an active height check polls the new ' + 'node', () { + fakeAsync((clock) { + final wallet = _Wallet()..wallet = const WrappedWallet('test-wallet'); + final oldPoll = Completer<({int syncHeight, int nodeHeight})>(); + var readHeightsCalls = 0; + var isSyncedCalls = 0; + + unawaited( + wallet.runTestRefresh( + refreshData: () async {}, + readHeights: (_) { + readHeightsCalls++; + if (readHeightsCalls == 1) { + return oldPoll.future; + } + return Future.value((syncHeight: 100, nodeHeight: 100)); + }, + isSynced: (_) async { + isSyncedCalls++; + return true; + }, + ), + ); + clock.flushMicrotasks(); + expect(readHeightsCalls, 1); + + wallet.notifyNodeConnected(); + expect(wallet.syncStatus, isA()); + + oldPoll.complete((syncHeight: 99, nodeHeight: 100)); + clock.flushMicrotasks(); + + expect(readHeightsCalls, 2); + expect(isSyncedCalls, 1); + expect(wallet.syncStatus, isA()); + expect(wallet.canEstimateFee, isTrue); + expect(wallet.refreshMutex.isLocked, isFalse); + }); + }); + + test('chained node switches during the queued height check', () { + fakeAsync((clock) { + final wallet = _Wallet()..wallet = const WrappedWallet('test-wallet'); + + // Case 1: second node switch fails while the queued poll is pending. + final refreshData1 = Completer(); + final queuedRead1 = Completer<({int syncHeight, int nodeHeight})>(); + var readCalls1 = 0; + unawaited( + wallet.runTestRefresh( + refreshData: () => refreshData1.future, + readHeights: (_) { + readCalls1++; + return queuedRead1.future; + }, + ), + ); + clock.flushMicrotasks(); + + wallet.notifyNodeConnected(); + refreshData1.complete(); + clock.flushMicrotasks(); + expect(readCalls1, 1); + + unawaited(wallet.updateNode()); + clock.flushMicrotasks(); + expect(wallet.syncStatus, isA()); + + queuedRead1.complete((syncHeight: 100, nodeHeight: 100)); + clock.flushMicrotasks(); + expect(readCalls1, 1); + expect(wallet.syncStatus, isA()); + expect(wallet.canEstimateFee, isFalse); + expect(wallet.refreshMutex.isLocked, isFalse); + + // Case 2: second node switch succeeds while the queued poll is pending. + final refreshData2 = Completer(); + final queuedRead2 = Completer<({int syncHeight, int nodeHeight})>(); + var readCalls2 = 0; + var isSyncedCalls2 = 0; + unawaited( + wallet.runTestRefresh( + refreshData: () => refreshData2.future, + readHeights: (_) { + readCalls2++; + if (readCalls2 == 1) { + return queuedRead2.future; + } + return Future.value((syncHeight: 100, nodeHeight: 100)); + }, + isSynced: (_) async { + isSyncedCalls2++; + return true; + }, + ), + ); + clock.flushMicrotasks(); + + wallet.notifyNodeConnected(); + refreshData2.complete(); + clock.flushMicrotasks(); + expect(readCalls2, 1); + + // Switch succeeds again before the first queued poll completes. + wallet.notifyNodeConnected(); + queuedRead2.complete((syncHeight: 99, nodeHeight: 100)); + clock.flushMicrotasks(); + + expect(readCalls2, 2); + expect(isSyncedCalls2, 1); + expect(wallet.syncStatus, isA()); + expect(wallet.canEstimateFee, isTrue); + expect(wallet.refreshMutex.isLocked, isFalse); + }); + }); + + test('live updates, refresh errors, and idle connects handle queued ' + 'polls', () { + fakeAsync((clock) { + final wallet = _Wallet()..wallet = const WrappedWallet('test-wallet'); + + // Case 1: live listener update from the new node supersedes queued poll. + final refreshData1 = Completer(); + var readCalls1 = 0; + unawaited( + wallet.runTestRefresh( + refreshData: () => refreshData1.future, + readHeights: (_) async { + readCalls1++; + return (syncHeight: 99, nodeHeight: 100); + }, + ), + ); + clock.flushMicrotasks(); + + wallet.notifyNodeConnected(); + wallet.onSyncingUpdate(syncHeight: 100, nodeHeight: 100); + refreshData1.complete(); + clock.flushMicrotasks(); + + expect(readCalls1, 0); + expect(wallet.syncStatus, isA()); + expect(wallet.canEstimateFee, isTrue); + + // Case 2: refreshData error does not skip queued poll and preserves + // error. + final refreshData2 = Completer(); + var readCalls2 = 0; + Object? caughtError2; + unawaited( + wallet + .runTestRefresh( + refreshData: () => refreshData2.future, + readHeights: (_) async { + readCalls2++; + return (syncHeight: 100, nodeHeight: 100); + }, + ) + .catchError((Object error) { + caughtError2 = error; + }), + ); + clock.flushMicrotasks(); + + wallet.notifyNodeConnected(); + refreshData2.completeError(StateError('refresh failed')); + clock.flushMicrotasks(); + + expect(caughtError2, isA()); + expect(readCalls2, 1); + expect(wallet.syncStatus, isA()); + expect(wallet.refreshMutex.isLocked, isFalse); + + // Case 3: failing queued poll does not mask the original refresh error. + final refreshData3 = Completer(); + var readCalls3 = 0; + Object? caughtError3; + unawaited( + wallet + .runTestRefresh( + refreshData: () => refreshData3.future, + readHeights: (_) { + readCalls3++; + return Future.error(StateError('poll failed')); + }, + ) + .catchError((Object error) { + caughtError3 = error; + }), + ); + clock.flushMicrotasks(); + + wallet.notifyNodeConnected(); + refreshData3.completeError(ArgumentError('original refresh failure')); + clock.flushMicrotasks(); + + expect(caughtError3, isA()); + expect(readCalls3, 1); + expect(wallet.refreshMutex.isLocked, isFalse); + + // Case 4: idle onNodeConnected does not queue a poll on a later refresh. + wallet.notifyNodeConnected(); + final refreshData4 = Completer(); + var readCalls4 = 0; + unawaited( + wallet.runTestRefresh( + refreshData: () => refreshData4.future, + readHeights: (_) async { + readCalls4++; + return (syncHeight: 100, nodeHeight: 100); + }, + ), + ); + clock.flushMicrotasks(); + + wallet.onSyncingUpdate(syncHeight: 99, nodeHeight: 100); + refreshData4.complete(); + clock.flushMicrotasks(); + + expect(readCalls4, 0); + expect(wallet.syncStatus, isA()); + }); + }); } From fec08d1e8e0f1e834513a93d84f79a6d363aeb3d Mon Sep 17 00:00:00 2001 From: sneurlax Date: Mon, 30 Nov 2026 12:55:36 -0600 Subject: [PATCH 5/5] fix: rerun Monero refresh when reopened during an active refresh --- .../intermediate/lib_monero_wallet.dart | 147 +++++--- test/wallets/monero_scan_progress_test.dart | 316 ++++++++++++++++++ 2 files changed, 408 insertions(+), 55 deletions(-) diff --git a/lib/wallets/wallet/intermediate/lib_monero_wallet.dart b/lib/wallets/wallet/intermediate/lib_monero_wallet.dart index 3ce0f34d8e..0a4e54368a 100644 --- a/lib/wallets/wallet/intermediate/lib_monero_wallet.dart +++ b/lib/wallets/wallet/intermediate/lib_monero_wallet.dart @@ -116,8 +116,11 @@ abstract class LibMoneroWallet lib_monero_compat.SyncStatus? _syncStatus; int _syncedCount = 0; int _syncUpdateGeneration = 0; + int _exitGeneration = 0; bool _isRefreshing = false; + Object? _activeRefreshToken; int? _pendingNodeSwitchPollGeneration; + int? _pendingRefreshExitGeneration; void _setSyncStatus(lib_monero_compat.SyncStatus status) { _syncUpdateGeneration++; if (status is lib_monero_compat.ConnectedSyncStatus && _isRefreshing) { @@ -293,7 +296,7 @@ abstract class LibMoneroWallet await csMonero.startListeners(wallet!); csMonero.startAutoSaving(wallet!); - unawaited(refresh()); + unawaited(_refresh(queueIfBusy: true)); } @Deprecated("Only used in the case of older wallets") @@ -563,6 +566,7 @@ abstract class LibMoneroWallet Future updateNode() async { _syncUpdateGeneration++; _pendingNodeSwitchPollGeneration = null; + _pendingRefreshExitGeneration = null; final node = getCurrentNode(); if (await _torNodeMismatchGuard(node)) { @@ -790,8 +794,10 @@ abstract class LibMoneroWallet @override Future exit() async { + _exitGeneration++; _syncUpdateGeneration++; _pendingNodeSwitchPollGeneration = null; + _pendingRefreshExitGeneration = null; await super.exit(); Logging.instance.i("exit called on monero $walletId!"); if (wallet != null) { @@ -1196,10 +1202,14 @@ abstract class LibMoneroWallet ) readHeights, required Future Function(WrappedWallet wallet) isSynced, + bool queueIfBusy = false, }) async { // Awaiting this lock could be dangerous. // Since refresh is periodic (generally) if (refreshMutex.isLocked) { + if (queueIfBusy && _activeRefreshToken != null) { + _pendingRefreshExitGeneration = _exitGeneration; + } Logging.instance.t( "$runtimeType refresh() refreshMutex.isLocked=true, returning...", ); @@ -1211,68 +1221,92 @@ abstract class LibMoneroWallet Logging.instance.t( "$runtimeType refresh() refreshMutex.acquire() waiting...", ); - await refreshMutex.protect(() async { - _isRefreshing = true; - var refreshFailed = false; - try { - await prepareRefresh(); - Logging.instance.t( - "$runtimeType refresh() " - "_setSyncStatus(lib_monero_compat.StartingSyncStatus());", - ); - _setSyncStatus(lib_monero_compat.StartingSyncStatus()); - final syncGeneration = _syncUpdateGeneration; - - await refreshData(); - - final currentWallet = wallet; - if (currentWallet == null) return; - await updateSyncStatusFromPolledHeights( - currentWallet: currentWallet, - expectedGeneration: syncGeneration, - readHeights: () => readHeights(currentWallet), - isSynced: () => isSynced(currentWallet), - ); - } catch (_) { - refreshFailed = true; - rethrow; - } finally { + final refreshToken = Object(); + try { + await refreshMutex.protect(() async { + _activeRefreshToken = refreshToken; + _isRefreshing = true; + var refreshFailed = false; try { - while (true) { - final pendingGeneration = _pendingNodeSwitchPollGeneration; - final currentWallet = wallet; - if (pendingGeneration == null || - currentWallet == null || - pendingGeneration != _syncUpdateGeneration) { + await prepareRefresh(); + Logging.instance.t( + "$runtimeType refresh() " + "_setSyncStatus(lib_monero_compat.StartingSyncStatus());", + ); + _setSyncStatus(lib_monero_compat.StartingSyncStatus()); + final syncGeneration = _syncUpdateGeneration; + + await refreshData(); + + final currentWallet = wallet; + if (currentWallet == null) return; + await updateSyncStatusFromPolledHeights( + currentWallet: currentWallet, + expectedGeneration: syncGeneration, + readHeights: () => readHeights(currentWallet), + isSynced: () => isSynced(currentWallet), + ); + } catch (_) { + refreshFailed = true; + rethrow; + } finally { + try { + while (true) { + final pendingGeneration = _pendingNodeSwitchPollGeneration; + final currentWallet = wallet; + if (pendingGeneration == null || + currentWallet == null || + pendingGeneration != _syncUpdateGeneration) { + _pendingNodeSwitchPollGeneration = null; + break; + } _pendingNodeSwitchPollGeneration = null; - break; - } - _pendingNodeSwitchPollGeneration = null; - try { - await updateSyncStatusFromPolledHeights( - currentWallet: currentWallet, - expectedGeneration: pendingGeneration, - readHeights: () => readHeights(currentWallet), - isSynced: () => isSynced(currentWallet), - ); - } catch (e, s) { - if (!refreshFailed) rethrow; - Logging.instance.w( - "Pending node switch height check failed: ", - error: e, - stackTrace: s, - ); + try { + await updateSyncStatusFromPolledHeights( + currentWallet: currentWallet, + expectedGeneration: pendingGeneration, + readHeights: () => readHeights(currentWallet), + isSynced: () => isSynced(currentWallet), + ); + } catch (e, s) { + if (!refreshFailed) rethrow; + Logging.instance.w( + "Pending node switch height check failed: ", + error: e, + stackTrace: s, + ); + } } + } finally { + _isRefreshing = false; } - } finally { - _isRefreshing = false; } + }); + } finally { + final pendingRefreshExitGeneration = _pendingRefreshExitGeneration; + _pendingRefreshExitGeneration = null; + if (identical(_activeRefreshToken, refreshToken)) { + _activeRefreshToken = null; } - }); + if (pendingRefreshExitGeneration != null && + pendingRefreshExitGeneration == _exitGeneration && + wallet != null) { + unawaited( + runRefreshWithSyncStatusPoll( + prepareRefresh: prepareRefresh, + refreshData: refreshData, + readHeights: readHeights, + isSynced: isSynced, + ), + ); + } + } } - @override - Future refresh() => runRefreshWithSyncStatusPoll( + Future _refresh({ + bool queueIfBusy = false, + }) => runRefreshWithSyncStatusPoll( + queueIfBusy: queueIfBusy, prepareRefresh: () async { Logging.instance.t( "$runtimeType refresh() final node = getCurrentNode();", @@ -1308,6 +1342,9 @@ abstract class LibMoneroWallet isSynced: csMonero.isSynced, ); + @override + Future refresh() => _refresh(); + @override Future generateNewReceivingAddress() async { try { diff --git a/test/wallets/monero_scan_progress_test.dart b/test/wallets/monero_scan_progress_test.dart index bc0da0eb10..49a1488670 100644 --- a/test/wallets/monero_scan_progress_test.dart +++ b/test/wallets/monero_scan_progress_test.dart @@ -91,11 +91,13 @@ class _Wallet extends MoneroWallet { ) readHeights, Future Function(WrappedWallet wallet)? isSynced, + bool queueIfBusy = false, }) => runRefreshWithSyncStatusPoll( prepareRefresh: prepareRefresh ?? () async {}, refreshData: refreshData, readHeights: readHeights, isSynced: isSynced ?? (_) async => true, + queueIfBusy: queueIfBusy, ); void notifyNodeConnected() => onNodeConnected(); @@ -675,4 +677,318 @@ void main() { expect(wallet.syncStatus, isA()); }); }); + + test( + 'reopening after exit during an active refresh restarts sync and polls', + () { + fakeAsync((clock) { + final wallet = _Wallet()..wallet = const WrappedWallet('test-wallet'); + final firstRefresh = Completer(); + var prepareCalls = 0; + var refreshDataCalls = 0; + var readHeightsCalls = 0; + var isSyncedCalls = 0; + + Future prepare() async { + prepareCalls++; + } + + Future refreshData() { + refreshDataCalls++; + if (refreshDataCalls == 1) { + return firstRefresh.future; + } + return Future.value(); + } + + Future<({int syncHeight, int nodeHeight})> readHeights( + WrappedWallet _, + ) async { + readHeightsCalls++; + return (syncHeight: 100, nodeHeight: 100); + } + + Future isSynced(WrappedWallet _) async { + isSyncedCalls++; + return true; + } + + unawaited( + wallet.runTestRefresh( + prepareRefresh: prepare, + refreshData: refreshData, + readHeights: readHeights, + isSynced: isSynced, + ), + ); + clock.flushMicrotasks(); + expect(prepareCalls, 1); + expect(wallet.syncStatus, isA()); + expect(wallet.refreshMutex.isLocked, isTrue); + + // User leaves the wallet while the refresh still holds refreshMutex. + Object? exitError; + unawaited( + wallet.exit().catchError((Object error) { + exitError = error; + }), + ); + clock.flushMicrotasks(); + expect(exitError, isA()); + + // User reopens the wallet twice while the old refresh is still locked; + // queued reopen refreshes coalesce into one follow-up refresh. + unawaited( + wallet.runTestRefresh( + prepareRefresh: prepare, + refreshData: refreshData, + readHeights: readHeights, + isSynced: isSynced, + queueIfBusy: true, + ), + ); + unawaited( + wallet.runTestRefresh( + prepareRefresh: prepare, + refreshData: refreshData, + readHeights: readHeights, + isSynced: isSynced, + queueIfBusy: true, + ), + ); + clock.flushMicrotasks(); + expect(prepareCalls, 1); + + firstRefresh.complete(); + clock.flushMicrotasks(); + + expect(prepareCalls, 2); + expect(refreshDataCalls, 2); + expect(readHeightsCalls, 1); + expect(isSyncedCalls, 1); + expect(wallet.syncStatus, isA()); + expect(wallet.canEstimateFee, isTrue); + expect(wallet.refreshMutex.isLocked, isFalse); + }); + }, + ); + + test('queued reopen refresh handles second exit, failed node switch, error, ' + 'and default queueIfBusy', () { + fakeAsync((clock) { + final wallet = _Wallet()..wallet = const WrappedWallet('test-wallet'); + + // Case 1: a second exit() cancels a queued reopen refresh. + final refresh1 = Completer(); + var prepareCalls1 = 0; + var refreshDataCalls1 = 0; + var readHeightsCalls1 = 0; + + Future prepare1() async { + prepareCalls1++; + } + + Future refreshData1() { + refreshDataCalls1++; + if (refreshDataCalls1 == 1) return refresh1.future; + return Future.value(); + } + + Future<({int syncHeight, int nodeHeight})> readHeights1( + WrappedWallet _, + ) async { + readHeightsCalls1++; + return (syncHeight: 100, nodeHeight: 100); + } + + unawaited( + wallet.runTestRefresh( + prepareRefresh: prepare1, + refreshData: refreshData1, + readHeights: readHeights1, + ), + ); + clock.flushMicrotasks(); + + unawaited(wallet.exit().catchError((Object _) {})); + clock.flushMicrotasks(); + unawaited( + wallet.runTestRefresh( + prepareRefresh: prepare1, + refreshData: refreshData1, + readHeights: readHeights1, + queueIfBusy: true, + ), + ); + unawaited(wallet.exit().catchError((Object _) {})); + clock.flushMicrotasks(); + + refresh1.complete(); + clock.flushMicrotasks(); + expect(prepareCalls1, 1); + expect(readHeightsCalls1, 0); + expect(wallet.refreshMutex.isLocked, isFalse); + + // Case 2: a failed updateNode() cancels a queued reopen refresh and + // preserves FailedSyncStatus. + final refresh2 = Completer(); + var prepareCalls2 = 0; + var refreshDataCalls2 = 0; + var readHeightsCalls2 = 0; + + Future prepare2() async { + prepareCalls2++; + } + + Future refreshData2() { + refreshDataCalls2++; + if (refreshDataCalls2 == 1) return refresh2.future; + return Future.value(); + } + + Future<({int syncHeight, int nodeHeight})> readHeights2( + WrappedWallet _, + ) async { + readHeightsCalls2++; + return (syncHeight: 100, nodeHeight: 100); + } + + unawaited( + wallet.runTestRefresh( + prepareRefresh: prepare2, + refreshData: refreshData2, + readHeights: readHeights2, + ), + ); + clock.flushMicrotasks(); + + unawaited(wallet.exit().catchError((Object _) {})); + clock.flushMicrotasks(); + unawaited( + wallet.runTestRefresh( + prepareRefresh: prepare2, + refreshData: refreshData2, + readHeights: readHeights2, + queueIfBusy: true, + ), + ); + unawaited(wallet.updateNode()); + clock.flushMicrotasks(); + expect(wallet.syncStatus, isA()); + + refresh2.complete(); + clock.flushMicrotasks(); + expect(prepareCalls2, 1); + expect(readHeightsCalls2, 0); + expect(wallet.syncStatus, isA()); + expect(wallet.canEstimateFee, isFalse); + + // Case 3: an error in the active refresh still runs the queued reopen + // refresh and propagates the original error. + final refresh3 = Completer(); + var prepareCalls3 = 0; + var refreshDataCalls3 = 0; + var readHeightsCalls3 = 0; + Object? caughtError3; + + Future prepare3() async { + prepareCalls3++; + } + + Future refreshData3() { + refreshDataCalls3++; + if (refreshDataCalls3 == 1) return refresh3.future; + return Future.value(); + } + + Future<({int syncHeight, int nodeHeight})> readHeights3( + WrappedWallet _, + ) async { + readHeightsCalls3++; + return (syncHeight: 100, nodeHeight: 100); + } + + unawaited( + wallet + .runTestRefresh( + prepareRefresh: prepare3, + refreshData: refreshData3, + readHeights: readHeights3, + ) + .catchError((Object error) { + caughtError3 = error; + }), + ); + clock.flushMicrotasks(); + + unawaited(wallet.exit().catchError((Object _) {})); + clock.flushMicrotasks(); + unawaited( + wallet.runTestRefresh( + prepareRefresh: prepare3, + refreshData: refreshData3, + readHeights: readHeights3, + queueIfBusy: true, + ), + ); + clock.flushMicrotasks(); + + refresh3.completeError(StateError('active refresh failed')); + clock.flushMicrotasks(); + + expect(caughtError3, isA()); + expect(prepareCalls3, 2); + expect(readHeightsCalls3, 1); + expect(wallet.syncStatus, isA()); + expect(wallet.canEstimateFee, isTrue); + + // Case 4: default queueIfBusy: false does not queue a follow-up refresh. + final refresh4 = Completer(); + var prepareCalls4 = 0; + var refreshDataCalls4 = 0; + var readHeightsCalls4 = 0; + + Future prepare4() async { + prepareCalls4++; + } + + Future refreshData4() { + refreshDataCalls4++; + if (refreshDataCalls4 == 1) return refresh4.future; + return Future.value(); + } + + Future<({int syncHeight, int nodeHeight})> readHeights4( + WrappedWallet _, + ) async { + readHeightsCalls4++; + return (syncHeight: 100, nodeHeight: 100); + } + + unawaited( + wallet.runTestRefresh( + prepareRefresh: prepare4, + refreshData: refreshData4, + readHeights: readHeights4, + ), + ); + clock.flushMicrotasks(); + + unawaited( + wallet.runTestRefresh( + prepareRefresh: prepare4, + refreshData: refreshData4, + readHeights: readHeights4, + ), + ); + clock.flushMicrotasks(); + + refresh4.complete(); + clock.flushMicrotasks(); + + expect(prepareCalls4, 1); + expect(readHeightsCalls4, 1); + expect(wallet.syncStatus, isA()); + }); + }); }