diff --git a/lib/wallets/wallet/intermediate/lib_monero_wallet.dart b/lib/wallets/wallet/intermediate/lib_monero_wallet.dart index cdc807f510..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) { @@ -434,11 +436,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 +810,56 @@ abstract class LibMoneroWallet required int syncHeight, required int nodeHeight, String? message, + }) { + _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 < 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(); + } + } + + @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, + ); } } @@ -934,35 +953,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 +1198,14 @@ 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());", + final currentWallet = wallet; + if (currentWallet == null) return; + await updateSyncStatusFromPolledHeights( + currentWallet: currentWallet, + readHeights: () => csMonero.getSyncHeights(currentWallet), ); - _setSyncStatus(lib_monero_compat.SyncedSyncStatus()); - } + }); } @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..c8094890f2 --- /dev/null +++ b/test/wallets/monero_scan_progress_test.dart @@ -0,0 +1,130 @@ +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'; +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'; +import 'package:stackwallet/wl_gen/interfaces/cs_salvium_interface.dart' + show WrappedWallet; + +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)); + + Future applyPolledHeights( + Future<({int syncHeight, int nodeHeight})> Function() readHeights, + ) => updateSyncStatusFromPolledHeights( + currentWallet: wallet!, + readHeights: readHeights, + ); +} + +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); + 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(); + }); + }); + + 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()); + }); + }); +} 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) =>