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
262 changes: 197 additions & 65 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,7 +115,19 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
lib_monero_compat.SyncStatus? get syncStatus => _syncStatus;
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) {
_pendingNodeSwitchPollGeneration = _syncUpdateGeneration;
} else {
_pendingNodeSwitchPollGeneration = null;
}
if (status is lib_monero_compat.SyncedSyncStatus) {
if (_syncStatus is lib_monero_compat.SyncedSyncStatus) {
_syncedCount++;
Expand Down Expand Up @@ -283,7 +296,7 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
await csMonero.startListeners(wallet!);
csMonero.startAutoSaving(wallet!);

unawaited(refresh());
unawaited(_refresh(queueIfBusy: true));
}

@Deprecated("Only used in the case of older wallets")
Expand Down Expand Up @@ -434,11 +447,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 @@ -548,8 +557,16 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
}
}

@protected
void onNodeConnected() {
_setSyncStatus(lib_monero_compat.ConnectedSyncStatus());
}

@override
Future<void> updateNode() async {
_syncUpdateGeneration++;
_pendingNodeSwitchPollGeneration = null;
_pendingRefreshExitGeneration = null;
final node = getCurrentNode();

if (await _torNodeMismatchGuard(node)) {
Expand Down Expand Up @@ -601,7 +618,7 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
await csMonero.startListeners(wallet!);
csMonero.startAutoSaving(wallet!);

_setSyncStatus(lib_monero_compat.ConnectedSyncStatus());
onNodeConnected();
} catch (e, s) {
_setSyncStatus(lib_monero_compat.FailedSyncStatus());
Logging.instance.e(
Expand Down Expand Up @@ -777,6 +794,10 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>

@override
Future<void> exit() async {
_exitGeneration++;
_syncUpdateGeneration++;
_pendingNodeSwitchPollGeneration = null;
_pendingRefreshExitGeneration = null;
await super.exit();
Logging.instance.i("exit called on monero $walletId!");
if (wallet != null) {
Expand Down Expand Up @@ -812,36 +833,78 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
required int syncHeight,
required int nodeHeight,
String? message,
}) {
if (nodeHeight > 0 && syncHeight >= 0 && syncHeight <= nodeHeight) {
_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,
required Future<bool> Function() isSynced,
int? expectedGeneration,
}) async {
final generation = expectedGeneration ?? _syncUpdateGeneration;
if (!identical(currentWallet, wallet) ||
generation != _syncUpdateGeneration) {
return;
}

final heights = await readHeights();
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({
Expand Down Expand Up @@ -934,35 +997,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 @@ -1146,11 +1193,23 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
await info.updateBalance(newBalance: balance, isar: mainDB.isar);
}

@override
Future<void> refresh() async {
@protected
Future<void> runRefreshWithSyncStatusPoll({
required Future<void> Function() prepareRefresh,
required Future<void> Function() refreshData,
required Future<({int syncHeight, int nodeHeight})> Function(
WrappedWallet wallet,
)
readHeights,
required Future<bool> 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...",
);
Expand All @@ -1162,7 +1221,93 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
Logging.instance.t(
"$runtimeType refresh() refreshMutex.acquire() waiting...",
);
await refreshMutex.protect(() async {
final refreshToken = Object();
try {
await refreshMutex.protect(() async {
_activeRefreshToken = refreshToken;
_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;
}
}
});
} 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,
),
);
}
}
}

Future<void> _refresh({
bool queueIfBusy = false,
}) => runRefreshWithSyncStatusPoll(
queueIfBusy: queueIfBusy,
prepareRefresh: () async {
Logging.instance.t(
"$runtimeType refresh() final node = getCurrentNode();",
);
Expand All @@ -1179,11 +1324,8 @@ abstract class LibMoneroWallet<T extends CryptonoteCurrency>
"$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());

},
refreshData: () async {
Logging.instance.t("$runtimeType refresh() await updateTransactions();");
await updateTransactions();
Logging.instance.t("$runtimeType refresh() await updateBalance();");
Expand All @@ -1195,23 +1337,13 @@ 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!);
},
readHeights: csMonero.getSyncHeights,
isSynced: csMonero.isSynced,
);

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());
}
}
@override
Future<void> refresh() => _refresh();

@override
Future<void> generateNewReceivingAddress() async {
Expand Down
3 changes: 3 additions & 0 deletions lib/wl_gen/interfaces/cs_monero_interface.dart
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,9 @@ abstract class CsMoneroInterface {
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
Loading
Loading