Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 48 additions & 53 deletions lib/wallets/wallet/intermediate/lib_monero_wallet.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -114,6 +115,7 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
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) {
Expand Down Expand Up @@ -434,11 +436,7 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
// 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());
Expand Down Expand Up @@ -812,35 +810,56 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
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<void> 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,
);
}
}

Expand Down Expand Up @@ -934,35 +953,19 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
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);
Expand Down Expand Up @@ -1195,22 +1198,14 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
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
Expand Down
4 changes: 3 additions & 1 deletion lib/wl_gen/interfaces/cs_monero_interface.dart
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,9 @@ abstract class CsMoneroInterface {
Future<String> getPublicSpendKey(WrappedWallet wallet);
Future<String> getPrivateSpendKey(WrappedWallet wallet);

Future<bool> isSynced(WrappedWallet wallet);
Future<({int syncHeight, int nodeHeight})> getSyncHeights(
WrappedWallet wallet,
);
Future<void> startSyncing(WrappedWallet wallet);
Future<void> stopSyncing(WrappedWallet wallet);

Expand Down
2 changes: 1 addition & 1 deletion pubspec.lock
Original file line number Diff line number Diff line change
Expand Up @@ -960,7 +960,7 @@ packages:
source: hosted
version: "2.0.1"
fake_async:
dependency: transitive
dependency: "direct dev"
description:
name: fake_async
sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"
Expand Down
1 change: 1 addition & 0 deletions scripts/app_config/templates/pubspec.template.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
130 changes: 130 additions & 0 deletions test/wallets/monero_scan_progress_test.dart
Original file line number Diff line number Diff line change
@@ -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<void> updateChainHeight() async {}

// Keep the asynchronous history refresh pending while delivering scan events.
@override
Future<void> updateTransactions() =>
Future<void>.delayed(const Duration(seconds: 1));

Future<void> 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 = <WalletSyncStatus>[];
final blocks = <int>[];
final statusSubscription = GlobalEventBus.instance
.on<WalletSyncStatusChangedEvent>()
.listen((event) => statuses.add(event.newStatus));
final blocksSubscription = GlobalEventBus.instance
.on<BlocksRemainingEvent>()
.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<SyncedSyncStatus>());
wallet.onSyncingUpdate(syncHeight: 100, nodeHeight: 101);
expect(wallet.syncStatus, isA<SyncingSyncStatus>());
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<SyncingSyncStatus>());

wallet.onSyncingUpdate(syncHeight: 101, nodeHeight: 100);
expect(wallet.syncStatus, isA<SyncedSyncStatus>());
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<SyncingSyncStatus>());

// 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<SyncedSyncStatus>());
});
});
}
9 changes: 7 additions & 2 deletions tool/wl_templates/XMR_cs_monero_interface_impl.template.dart
Original file line number Diff line number Diff line change
Expand Up @@ -217,8 +217,13 @@ class _CsMoneroInterfaceImpl extends CsMoneroInterface {
wallet.get<lib_monero.Wallet>().getPrivateSpendKey();

@override
Future<bool> isSynced(WrappedWallet wallet) =>
wallet.get<lib_monero.Wallet>().isSynced();
Future<({int syncHeight, int nodeHeight})> getSyncHeights(
WrappedWallet wallet,
) async {
final native = wallet.get<lib_monero.Wallet>();
final syncHeight = await native.getCurrentWalletSyncingHeight();
return (syncHeight: syncHeight, nodeHeight: await native.getDaemonHeight());
}

@override
Future<void> startSyncing(WrappedWallet wallet) =>
Expand Down
Loading