replace error-prone refresh mutex/lock with wallet state coordination for xelis to start out with
What changed, and why it matters
This commit rewrites how Stack Wallet's Xelis wallet handles background synchronization. It replaces a single refresh lock with a new 'operation coordinator' and an 'event batcher' that groups rapid blockchain notifications before acting on them. The stated goal is to fix race conditions and inconsistent state caused by the old mutex-based design. The change is defensive refactoring rather than a patch for a known exploit, but concurrency bugs in wallet code can historically lead to incorrect balances, missed transactions, or crashes.
Treat as a hardening/refactoring change. Review the new coordinator and batcher logic for remaining race conditions, especially around exit() suppressing events and the 500 ms event flush window. Run the new unit tests and consider additional integration tests for rescan/connect/refresh interleaving. Monitor for regressions in balance display or missed transactions.
Security signals we found
Concurrency/synchronization redesign for wallet refresh and blockchain event handling
Old refreshMutex described by author as 'error-prone'
New event batching could reduce race windows between balance/transaction/height updates
Adds rethrowErrors paths and explicit error handling in refresh/event flows
No explicit vulnerability identifier or vendor security statement in commit or references
Evidence from the diff
The patch removes direct use of refreshMutex in XelisWallet and LibXelisWallet, introducing XelisOperationCoordinator (serializes connect/refresh/rescan/event/exit operations and lets duplicate callers join an in-flight operation) and XelisEventBatcher (buffers transaction, topoheight, and balance events for 500 ms, then flushes a single batched update). It also adds rethrowErrors flags to updateBalance/updateChainHeight, changes pingCheck to no longer toggle online/offline state, makes connect idempotent with joinExisting/disconnectFirst, and moves periodic refresh timer setup into a shared helper. Unit tests cover batching and coordinator behavior. No CVE, advisory, or vendor security disclosure is present in the supplied materials.
Changed components
lib/wallets/wallet/impl/xelis_wallet.dartlib/wallets/wallet/intermediate/lib_xelis_wallet.dartlib/wallets/wallet/intermediate/xelis_event_batcher.dartlib/wallets/wallet/intermediate/xelis_operation_coordinator.dartlib/wallets/wallet/wallet.darttest/wallets/xelis_event_batcher_test.darttest/wallets/xelis_operation_coordinator_test.dartInspect captured patch +845 / −153
diff --git a/lib/wallets/wallet/impl/xelis_wallet.dart b/lib/wallets/wallet/impl/xelis_wallet.dart
index 66b551b..fa5579b 100644
--- a/lib/wallets/wallet/impl/xelis_wallet.dart
+++ b/lib/wallets/wallet/impl/xelis_wallet.dart
@@ -22,6 +22,7 @@ import '../../../wl_gen/interfaces/lib_xelis_interface.dart';
import '../../crypto_currency/crypto_currency.dart';
import '../../models/tx_data.dart';
import '../intermediate/lib_xelis_wallet.dart';
+import '../intermediate/xelis_event_batcher.dart';
import '../wallet.dart';
class XelisWallet extends LibXelisWallet {
@@ -200,7 +201,7 @@ class XelisWallet extends LibXelisWallet {
@override
Future<void> recover({required bool isRescan}) async {
if (isRescan) {
- await refreshMutex.protect(() async {
+ await runXelisRescan(() async {
await mainDB.deleteWalletBlockchainData(walletId);
await updateTransactions(isRescan: true, topoheight: 0);
});
@@ -229,10 +230,8 @@ class XelisWallet extends LibXelisWallet {
Future<bool> pingCheck() async {
try {
await libXelis.getDaemonInfo(wallet!);
- await handleOnline();
return true;
} catch (_) {
- await handleOffline();
return false;
}
}
@@ -240,7 +239,10 @@ class XelisWallet extends LibXelisWallet {
final _balanceUpdateMutex = Mutex();
@override
- Future<void> updateBalance({int? newBalance}) async {
+ Future<void> updateBalance({
+ int? newBalance,
+ bool rethrowErrors = false,
+ }) async {
await _balanceUpdateMutex.protect(() async {
try {
if (await libXelis.hasXelisBalance(wallet!)) {
@@ -273,6 +275,9 @@ class XelisWallet extends LibXelisWallet {
error: e,
stackTrace: s,
);
+ if (rethrowErrors) {
+ rethrow;
+ }
}
});
}
@@ -288,7 +293,10 @@ class XelisWallet extends LibXelisWallet {
}
@override
- Future<void> updateChainHeight({int? topoheight}) async {
+ Future<void> updateChainHeight({
+ int? topoheight,
+ bool rethrowErrors = false,
+ }) async {
try {
final height = topoheight ?? await _fetchChainHeight();
@@ -302,17 +310,16 @@ class XelisWallet extends LibXelisWallet {
error: e,
stackTrace: s,
);
+ if (rethrowErrors) {
+ rethrow;
+ }
}
}
@override
Future<void> updateNode() async {
try {
- final bool online = await libXelis.isOnline(wallet!);
- if (online == true) {
- await libXelis.offlineMode(wallet!);
- }
- await super.connect();
+ await connect(disconnectFirst: true);
} catch (e, s) {
Logging.instance.e(
"Error rethrown from $runtimeType updateNode()",
@@ -897,55 +904,52 @@ class XelisWallet extends LibXelisWallet {
}
@override
- Future<void> handleNewTopoHeight(int height) async {
- await info.updateCachedChainHeight(newHeight: height, isar: mainDB.isar);
- }
+ Future<void> handleNewTopoHeight(int _) async =>
+ eventBatcher.queueTopoheightChanged();
@override
- Future<void> handleNewTransaction(TransactionEntryWrapper tx) async {
- try {
- final txList = [tx];
- final newTxIds = await updateTransactions(
- isRescan: false,
- objTransactions: txList,
- );
-
- await updateBalance();
+ Future<void> handleNewTransaction(TransactionEntryWrapper tx) async =>
+ eventBatcher.queueTransaction(tx);
- // Logging.instance.log(
- // "New transaction processed: ${newTxIds.first}",
- // level: LogLevel.Info,
- // );
- } catch (e, s) {
- Logging.instance.e(
- "Error in $runtimeType handleNewTransaction($tx)",
- error: e,
- stackTrace: s,
- );
+ @override
+ Future<void> handleBalanceChanged(BalanceChanged event) async {
+ if (event.asset == libXelis.xelisAsset) {
+ eventBatcher.queueBalanceChanged();
}
}
@override
- Future<void> handleBalanceChanged(BalanceChanged event) async {
+ Future<void> applyXelisEventBatch(
+ XelisEventBatch<TransactionEntryWrapper> batch,
+ ) async {
try {
- final asset = event.asset;
- if (asset == libXelis.xelisAsset) {
- await updateBalance(newBalance: event.balance);
+ if (batch.topoheightChanged) {
+ await updateChainHeight(rethrowErrors: true);
}
- // TODO: Update asset balances if needed
+ if (batch.transactions.isNotEmpty) {
+ await updateTransactions(
+ isRescan: false,
+ objTransactions: batch.transactions,
+ );
+ }
+
+ if (batch.balanceChanged || batch.transactions.isNotEmpty) {
+ await updateBalance(rethrowErrors: true);
+ }
} catch (e, s) {
Logging.instance.e(
- "Error in $runtimeType handleBalanceChanged($event)",
+ "Error in $runtimeType applyXelisEventBatch()",
error: e,
stackTrace: s,
);
+ unawaited(refresh());
}
}
@override
Future<void> handleRescan(int startTopoheight) async {
- await refreshMutex.protect(() async {
+ await runXelisRescan(() async {
await mainDB.deleteWalletBlockchainData(walletId);
await updateTransactions(isRescan: true, topoheight: startTopoheight);
await updateBalance();
@@ -953,19 +957,7 @@ class XelisWallet extends LibXelisWallet {
}
@override
- Future<void> handleOnline() async {
- await updateChainHeight();
- await updateBalance();
- await updateTransactions();
- GlobalEventBus.instance.fire(
- WalletSyncStatusChangedEvent(
- WalletSyncStatus.synced,
- walletId,
- info.coin,
- ),
- );
- unawaited(refresh());
- }
+ Future<void> handleOnline() => runXelisSyncEvent();
@override
Future<void> handleOffline() async {
@@ -979,18 +971,7 @@ class XelisWallet extends LibXelisWallet {
}
@override
- Future<void> handleHistorySynced(int topoheight) async {
- await updateChainHeight();
- await updateBalance();
- await updateTransactions();
- GlobalEventBus.instance.fire(
- WalletSyncStatusChangedEvent(
- WalletSyncStatus.synced,
- walletId,
- info.coin,
- ),
- );
- }
+ Future<void> handleHistorySynced(int _) => runXelisSyncEvent();
@override
Future<void> handleNewAsset(NewAsset asset) async {
@@ -1000,30 +981,59 @@ class XelisWallet extends LibXelisWallet {
}
@override
- Future<void> refresh({int? topoheight}) async {
- await refreshMutex.protect(() async {
- try {
- final bool online = await libXelis.isOnline(wallet!);
- if (online == true) {
- await updateChainHeight(topoheight: topoheight);
- await updateBalance();
- await updateTransactions();
- } else {
+ Future<void> performXelisRefresh() async {
+ try {
+ final bool online = await libXelis.isOnline(wallet!);
+ if (online == true) {
+ if (!doNotFireRefreshEvents) {
GlobalEventBus.instance.fire(
WalletSyncStatusChangedEvent(
- WalletSyncStatus.unableToSync,
+ WalletSyncStatus.syncing,
walletId,
info.coin,
),
);
}
- } catch (e, s) {
- Logging.instance.e(
- "Error in $runtimeType refresh()",
- error: e,
- stackTrace: s,
+
+ await updateChainHeight(rethrowErrors: true);
+ await updateBalance(rethrowErrors: true);
+ await updateTransactions();
+
+ if (!doNotFireRefreshEvents) {
+ GlobalEventBus.instance.fire(
+ WalletSyncStatusChangedEvent(
+ WalletSyncStatus.synced,
+ walletId,
+ info.coin,
+ ),
+ );
+ }
+ ensurePeriodicRefreshTimer();
+ } else if (!doNotFireRefreshEvents) {
+ GlobalEventBus.instance.fire(
+ WalletSyncStatusChangedEvent(
+ WalletSyncStatus.unableToSync,
+ walletId,
+ info.coin,
+ ),
);
}
- });
+ } catch (e, s) {
+ if (!doNotFireRefreshEvents) {
+ GlobalEventBus.instance.fire(
+ WalletSyncStatusChangedEvent(
+ WalletSyncStatus.unableToSync,
+ walletId,
+ info.coin,
+ ),
+ );
+ }
+ Logging.instance.e(
+ "Error in $runtimeType performXelisRefresh()",
+ error: e,
+ stackTrace: s,
+ );
+ rethrow;
+ }
}
}
diff --git a/lib/wallets/wallet/intermediate/lib_xelis_wallet.dart b/lib/wallets/wallet/intermediate/lib_xelis_wallet.dart
index eb81802..4938bea 100644
--- a/lib/wallets/wallet/intermediate/lib_xelis_wallet.dart
+++ b/lib/wallets/wallet/intermediate/lib_xelis_wallet.dart
@@ -12,6 +12,8 @@ import '../../../wl_gen/interfaces/lib_xelis_interface.dart';
import '../../crypto_currency/intermediate/electrum_currency.dart';
import '../wallet_mixin_interfaces/mnemonic_interface.dart';
import 'external_wallet.dart';
+import 'xelis_event_batcher.dart';
+import 'xelis_operation_coordinator.dart';
abstract class LibXelisWallet<T extends ElectrumCurrency>
extends ExternalWallet<T>
@@ -38,6 +40,18 @@ abstract class LibXelisWallet<T extends ElectrumCurrency>
Timer? timer;
StreamSubscription<void>? _eventSubscription;
+ late final XelisOperationCoordinator _operationCoordinator =
+ XelisOperationCoordinator(refreshMutex);
+
+ static const _eventFlushInterval = Duration(milliseconds: 500);
+
+ @protected
+ late final XelisEventBatcher<TransactionEntryWrapper> eventBatcher =
+ XelisEventBatcher(
+ flushInterval: _eventFlushInterval,
+ flush: (batch) =>
+ runXelisEventUpdate(() => applyXelisEventBatch(batch)),
+ );
Future<String> getPrecomputedTablesPath() async {
if (kIsWeb) {
@@ -88,31 +102,70 @@ abstract class LibXelisWallet<T extends ElectrumCurrency>
Future<void> handleHistorySynced(int topoheight) async {}
Future<void> handleNewAsset(NewAsset asset) async {}
- @override
- Future<void> refresh({int? topoheight});
-
- Future<void> connect() async {
- final node = getCurrentNode();
- try {
- checkInitialized();
- _eventSubscription = libXelis.eventsStream(wallet!).listen(handleEvent);
-
- Logging.instance.i("Connecting to node: ${node.host}:${node.port}");
- await libXelis.onlineMode(
- wallet!,
- daemonAddress: "${node.host}:${node.port}",
- );
- await super.refresh();
- } catch (e, s) {
- Logging.instance.e(
- "rethrowing error connecting to node: $node",
- error: e,
- stackTrace: s,
- );
- rethrow;
- }
+ @protected
+ Future<void> performXelisRefresh();
+
+ @protected
+ Future<void> applyXelisEventBatch(
+ XelisEventBatch<TransactionEntryWrapper> batch,
+ );
+
+ @protected
+ Future<void> runXelisRescan(Future<void> Function() operation) {
+ eventBatcher.reset();
+ return _operationCoordinator.rescan(operation);
}
+ @protected
+ Future<void> runXelisEventUpdate(Future<void> Function() operation) =>
+ _operationCoordinator.processEvent(operation);
+
+ @protected
+ Future<void> runXelisSyncEvent() =>
+ _operationCoordinator.processSyncEvent(performXelisRefresh);
+
+ // Intentionally swallow logged errors because refresh is often unawaited.
+ @override
+ Future<void> refresh() =>
+ _operationCoordinator.refresh(performXelisRefresh).catchError((_) {});
+
+ Future<void> connect({bool disconnectFirst = false}) =>
+ _operationCoordinator.connect(() async {
+ final node = getCurrentNode();
+ try {
+ checkInitialized();
+
+ final wasOnline = await libXelis.isOnline(wallet!);
+ await _eventSubscription?.cancel();
+ _eventSubscription = null;
+
+ if (wasOnline && disconnectFirst) {
+ await libXelis.offlineMode(wallet!);
+ }
+
+ _eventSubscription = libXelis.eventsStream(wallet!).listen((event) {
+ unawaited(handleEvent(event));
+ });
+
+ if (!wasOnline || disconnectFirst) {
+ Logging.instance.i("Connecting to node: ${node.host}:${node.port}");
+ await libXelis.onlineMode(
+ wallet!,
+ daemonAddress: "${node.host}:${node.port}",
+ );
+ }
+
+ await performXelisRefresh();
+ } catch (e, s) {
+ Logging.instance.e(
+ "rethrowing error connecting to node: $node",
+ error: e,
+ stackTrace: s,
+ );
+ rethrow;
+ }
+ }, joinExisting: !disconnectFirst);
+
List<FilterOperation> get standardReceivingAddressFilters => [
FilterCondition.equalTo(property: r"type", value: info.mainAddressType),
const FilterCondition.equalTo(
@@ -139,45 +192,22 @@ abstract class LibXelisWallet<T extends ElectrumCurrency>
}
@override
- Future<void> open() async {
- while (exitInProgress) {
- await Future<void>.delayed(const Duration(milliseconds: 500));
- }
+ Future<void> open() => connect();
- try {
- await connect();
- } catch (e) {
- // Logging.instance.log(
- // "Failed to start sync: $e",
- // level: LogLevel.Error,
- // );
- rethrow;
- }
- unawaited(refresh());
- }
+ @override
+ Future<void> exit() => _operationCoordinator.exit(() async {
+ timer?.cancel();
+ timer = null;
- bool exitInProgress = false;
+ eventBatcher.reset();
+ await _eventSubscription?.cancel();
+ _eventSubscription = null;
- @override
- Future<void> exit() async {
- exitInProgress = true;
- try {
- await refreshMutex.protect(() async {
- timer?.cancel();
- timer = null;
-
- await _eventSubscription?.cancel();
- _eventSubscription = null;
-
- if (wallet != null && await libXelis.isOnline(wallet!)) {
- await libXelis.offlineMode(wallet!);
- }
- await super.exit();
- });
- } finally {
- exitInProgress = false;
+ if (wallet != null && await libXelis.isOnline(wallet!)) {
+ await libXelis.offlineMode(wallet!);
}
- }
+ await super.exit();
+ });
void invalidSeedLengthCheck(int length) {
if (!(length == 25)) {
diff --git a/lib/wallets/wallet/intermediate/xelis_event_batcher.dart b/lib/wallets/wallet/intermediate/xelis_event_batcher.dart
new file mode 100644
index 0000000..031d7cd
--- /dev/null
+++ b/lib/wallets/wallet/intermediate/xelis_event_batcher.dart
@@ -0,0 +1,84 @@
+import 'dart:async';
+
+final class XelisEventBatch<T> {
+ const XelisEventBatch({
+ required this.transactions,
+ required this.topoheightChanged,
+ required this.balanceChanged,
+ });
+
+ final List<T> transactions;
+ final bool topoheightChanged;
+ final bool balanceChanged;
+
+ bool get isEmpty =>
+ transactions.isEmpty && !topoheightChanged && !balanceChanged;
+}
+
+final class XelisEventBatcher<T> {
+ XelisEventBatcher({required this.flushInterval, required this.flush});
+
+ final Duration flushInterval;
+ final Future<void> Function(XelisEventBatch<T> batch) flush;
+
+ final List<T> _transactions = [];
+ bool _topoheightChanged = false;
+ bool _balanceChanged = false;
+ bool _isFlushing = false;
+ Timer? _flushTimer;
+
+ void queueTransaction(T transaction) {
+ _transactions.add(transaction);
+ _scheduleFlush();
+ }
+
+ void queueTopoheightChanged() {
+ _topoheightChanged = true;
+ _scheduleFlush();
+ }
+
+ void queueBalanceChanged() {
+ _balanceChanged = true;
+ _scheduleFlush();
+ }
+
+ void reset() {
+ _flushTimer?.cancel();
+ _flushTimer = null;
+ _transactions.clear();
+ _topoheightChanged = false;
+ _balanceChanged = false;
+ }
+
+ void _scheduleFlush() {
+ if (!_isFlushing) {
+ _flushTimer ??= Timer(flushInterval, () => unawaited(_flushNow()));
+ }
+ }
+
+ Future<void> _flushNow() async {
+ _flushTimer = null;
+ final batch = XelisEventBatch<T>(
+ transactions: List.of(_transactions),
+ topoheightChanged: _topoheightChanged,
+ balanceChanged: _balanceChanged,
+ );
+ _transactions.clear();
+ _topoheightChanged = false;
+ _balanceChanged = false;
+
+ if (batch.isEmpty) {
+ return;
+ }
+
+ _isFlushing = true;
+ try {
+ await flush(batch);
+ } finally {
+ _isFlushing = false;
+ if (_transactions.isNotEmpty || _topoheightChanged || _balanceChanged) {
+ _scheduleFlush();
+ }
+ }
+ }
+}
diff --git a/lib/wallets/wallet/intermediate/xelis_operation_coordinator.dart b/lib/wallets/wallet/intermediate/xelis_operation_coordinator.dart
new file mode 100644
index 0000000..11ca003
--- /dev/null
+++ b/lib/wallets/wallet/intermediate/xelis_operation_coordinator.dart
@@ -0,0 +1,145 @@
+import 'package:mutex/mutex.dart';
+
+enum XelisOperation {
+ idle,
+ connecting,
+ refreshing,
+ rescanning,
+ processingEvent,
+ exiting,
+}
+
+final class XelisOperationCoordinator {
+ XelisOperationCoordinator(this._mutex);
+
+ final Mutex _mutex;
+
+ Future<void>? _latestSyncFuture;
+ Future<void>? _pendingExitFuture;
+ ({XelisOperation operation, Future<void> future})? _latestLifecycle;
+
+ XelisOperation _activeOperation = XelisOperation.idle;
+
+ XelisOperation get activeOperation => _activeOperation;
+
+ Future<void> connect(
+ Future<void> Function() operation, {
+ bool joinExisting = true,
+ }) {
+ final latestLifecycle = _latestLifecycle;
+ if (joinExisting &&
+ latestLifecycle?.operation == XelisOperation.connecting) {
+ return latestLifecycle!.future;
+ }
+
+ late final Future<void> future;
+ future = _run(XelisOperation.connecting, operation).whenComplete(() {
+ _clearLatestLifecycle(future);
+ _clearLatestSync(future);
+ });
+
+ _latestLifecycle = (operation: XelisOperation.connecting, future: future);
+ _latestSyncFuture = future;
+ return future;
+ }
+
+ Future<void> refresh(Future<void> Function() operation) {
+ final latestSyncFuture = _latestSyncFuture;
+ if (latestSyncFuture != null) {
+ return latestSyncFuture;
+ }
+
+ if (_pendingExitFuture != null) {
+ return Future<void>.value();
+ }
+
+ return _scheduleSync(XelisOperation.refreshing, operation);
+ }
+
+ Future<void> rescan(Future<void> Function() operation) {
+ if (_pendingExitFuture != null) {
+ return Future<void>.error(
+ StateError('Cannot rescan a Xelis wallet while it is exiting'),
+ );
+ }
+
+ return _scheduleSync(XelisOperation.rescanning, operation);
+ }
+
+ Future<void> processEvent(Future<void> Function() operation) {
+ if (_pendingExitFuture != null) {
+ return Future<void>.value();
+ }
+
+ return _run(XelisOperation.processingEvent, operation);
+ }
+
+ Future<void> processSyncEvent(Future<void> Function() operation) {
+ if (_pendingExitFuture != null) {
+ return Future<void>.value();
+ }
+
+ return refresh(operation);
+ }
+
+ Future<void> exit(Future<void> Function() operation) {
+ final latestLifecycle = _latestLifecycle;
+ if (latestLifecycle?.operation == XelisOperation.exiting) {
+ return latestLifecycle!.future;
+ }
+
+ _latestSyncFuture = null;
+
+ late final Future<void> future;
+ future = _run(XelisOperation.exiting, operation).whenComplete(() {
+ if (identical(_pendingExitFuture, future)) {
+ _pendingExitFuture = null;
+ }
+ _clearLatestLifecycle(future);
+ });
+
+ _latestLifecycle = (operation: XelisOperation.exiting, future: future);
+ _pendingExitFuture = future;
+ return future;
+ }
+
+ Future<void> _scheduleSync(
+ XelisOperation operationType,
+ Future<void> Function() operation,
+ ) {
+ late final Future<void> future;
+ future = _run(operationType, operation).whenComplete(() {
+ _clearLatestSync(future);
+ });
+
+ _latestSyncFuture = future;
+ return future;
+ }
+
+ Future<void> _run(
+ XelisOperation operationType,
+ Future<void> Function() operation,
+ ) {
+ return _mutex.protect(() async {
+ assert(_activeOperation == XelisOperation.idle);
+ _activeOperation = operationType;
+ try {
+ await operation();
+ } finally {
+ _activeOperation = XelisOperation.idle;
+ }
+ });
+ }
+
+ void _clearLatestSync(Future<void> completedFuture) {
+ if (identical(_latestSyncFuture, completedFuture)) {
+ _latestSyncFuture = null;
+ }
+ }
+
+ void _clearLatestLifecycle(Future<void> completedFuture) {
+ if (identical(_latestLifecycle?.future, completedFuture)) {
+ _latestLifecycle = null;
+ }
+ }
+}
diff --git a/lib/wallets/wallet/wallet.dart b/lib/wallets/wallet/wallet.dart
index 1aa40ef..f89b682 100644
--- a/lib/wallets/wallet/wallet.dart
+++ b/lib/wallets/wallet/wallet.dart
@@ -556,21 +556,7 @@ abstract class Wallet<T extends CryptoCurrency> {
),
);
}
- if (shouldAutoSync) {
- _periodicRefreshTimer ??= Timer.periodic(const Duration(seconds: 150), (
- timer,
- ) async {
- // chain height check currently broken
- // if ((await chainHeight) != (await storedChainHeight)) {
-
- // TODO: [prio=med] some kind of quick check if wallet needs to refresh to replace the old refreshIfThereIsNewData call
- // if (await refreshIfThereIsNewData()) {
- unawaited(refresh());
-
- // }
- // }
- });
- }
+ ensurePeriodicRefreshTimer();
},
onError: (Object e, StackTrace s) {
if (!doNotFireRefreshEvents) {
@@ -602,6 +588,16 @@ abstract class Wallet<T extends CryptoCurrency> {
return future;
}
+ @protected
+ void ensurePeriodicRefreshTimer() {
+ if (shouldAutoSync) {
+ _periodicRefreshTimer ??= Timer.periodic(
+ const Duration(seconds: 150),
+ (_) => unawaited(refresh()),
+ );
+ }
+ }
+
void _fireRefreshPercentChange(double percent) {
if (this is ElectrumXInterface) {
(this as ElectrumXInterface?)?.refreshingPercent = percent;
diff --git a/test/wallets/xelis_event_batcher_test.dart b/test/wallets/xelis_event_batcher_test.dart
new file mode 100644
index 0000000..3ba6b4e
--- /dev/null
+++ b/test/wallets/xelis_event_batcher_test.dart
@@ -0,0 +1,130 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/wallets/wallet/intermediate/xelis_event_batcher.dart';
+
+const _interval = Duration(milliseconds: 20);
+const _afterFlush = Duration(milliseconds: 60);
+
+void main() {
+ test('a burst of events flushes as one batch', () async {
+ final batches = <XelisEventBatch<String>>[];
+ final batcher = XelisEventBatcher<String>(
+ flushInterval: _interval,
+ flush: (batch) async => batches.add(batch),
+ );
+
+ batcher.queueTransaction('a');
+ batcher.queueTransaction('b');
+ batcher.queueTopoheightChanged();
+ batcher.queueTopoheightChanged();
+ batcher.queueBalanceChanged();
+
+ expect(batches, isEmpty);
+ await Future<void>.delayed(_afterFlush);
+
+ expect(batches, hasLength(1));
+ expect(batches.single.transactions, ['a', 'b']);
+ expect(batches.single.topoheightChanged, isTrue);
+ expect(batches.single.balanceChanged, isTrue);
+ });
+
+ test('events arriving after a flush start a new batch', () async {
+ final batches = <XelisEventBatch<String>>[];
+ final batcher = XelisEventBatcher<String>(
+ flushInterval: _interval,
+ flush: (batch) async => batches.add(batch),
+ );
+
+ batcher.queueTransaction('a');
+ await Future<void>.delayed(_afterFlush);
+ batcher.queueTransaction('b');
+ await Future<void>.delayed(_afterFlush);
+
+ expect(batches, hasLength(2));
+ expect(batches[0].transactions, ['a']);
+ expect(batches[1].transactions, ['b']);
+ expect(batches[1].topoheightChanged, isFalse);
+ expect(batches[1].balanceChanged, isFalse);
+ });
+
+ test('no flush runs while nothing is queued', () async {
+ int flushCount = 0;
+ XelisEventBatcher<String>(
+ flushInterval: _interval,
+ flush: (batch) async => flushCount++,
+ );
+
+ await Future<void>.delayed(_afterFlush);
+ expect(flushCount, 0);
+ });
+
+ test('reset drops pending events and cancels the scheduled flush', () async {
+ int flushCount = 0;
+ final batcher = XelisEventBatcher<String>(
+ flushInterval: _interval,
+ flush: (batch) async => flushCount++,
+ );
+
+ batcher.queueTransaction('a');
+ batcher.queueBalanceChanged();
+ batcher.reset();
+
+ await Future<void>.delayed(_afterFlush);
+ expect(flushCount, 0);
+
+ batcher.queueTransaction('b');
+ await Future<void>.delayed(_afterFlush);
+ expect(flushCount, 1);
+ });
+
+ test('delayed topoheight notifications read current height', () async {
+ int daemonHeight = 100;
+ int cachedHeight = 0;
+ int liveHeightReads = 0;
+ final batcher = XelisEventBatcher<void>(
+ flushInterval: _interval,
+ flush: (batch) async {
+ if (batch.topoheightChanged) {
+ liveHeightReads++;
+ cachedHeight = daemonHeight;
+ }
+ },
+ );
+
+ batcher.queueTopoheightChanged();
+ daemonHeight = 101;
+ cachedHeight = daemonHeight;
+
+ await Future<void>.delayed(_afterFlush);
+ expect(cachedHeight, 101);
+ expect(liveHeightReads, 1);
+ });
+
+ test('slow flush retains one trailing batch', () async {
+ final releaseFirstFlush = Completer<void>();
+ final batches = <XelisEventBatch<String>>[];
+ final batcher = XelisEventBatcher<String>(
+ flushInterval: _interval,
+ flush: (batch) async {
+ batches.add(batch);
+ if (batches.length == 1) {
+ await releaseFirstFlush.future;
+ }
+ },
+ );
+
+ batcher.queueTransaction('a');
+ await Future<void>.delayed(_afterFlush);
+
+ batcher.queueTransaction('b');
+ batcher.queueTransaction('c');
+ await Future<void>.delayed(_afterFlush);
+ expect(batches, hasLength(1));
+
+ releaseFirstFlush.complete();
+ await Future<void>.delayed(_afterFlush);
+ expect(batches, hasLength(2));
+ expect(batches.last.transactions, ['b', 'c']);
+ });
+}
diff --git a/test/wallets/xelis_operation_coordinator_test.dart b/test/wallets/xelis_operation_coordinator_test.dart
new file mode 100644
index 0000000..7f70308
--- /dev/null
+++ b/test/wallets/xelis_operation_coordinator_test.dart
@@ -0,0 +1,297 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:mutex/mutex.dart';
+import 'package:stackwallet/wallets/wallet/intermediate/xelis_operation_coordinator.dart';
+
+void main() {
+ test('concurrent refresh callers join one operation', () async {
+ final coordinator = XelisOperationCoordinator(Mutex());
+ final releaseRefresh = Completer<void>();
+ int refreshCount = 0;
+
+ final first = coordinator.refresh(() async {
+ refreshCount++;
+ await releaseRefresh.future;
+ });
+ final second = coordinator.refresh(() async {
+ fail('the joined refresh operation must not run');
+ });
+
+ expect(identical(first, second), isTrue);
+ await _flushMicrotasks();
+ expect(refreshCount, 1);
+ expect(coordinator.activeOperation, XelisOperation.refreshing);
+
+ releaseRefresh.complete();
+ await first;
+ expect(coordinator.activeOperation, XelisOperation.idle);
+ });
+
+ test('refresh joins the latest queued synchronization', () async {
+ final coordinator = XelisOperationCoordinator(Mutex());
+ final releaseRefresh = Completer<void>();
+ final releaseRescan = Completer<void>();
+ final order = <String>[];
+
+ final refresh = coordinator.refresh(() async {
+ order.add('refresh:start');
+ await releaseRefresh.future;
+ order.add('refresh:end');
+ });
+ await _flushMicrotasks();
+
+ final rescan = coordinator.rescan(() async {
+ order.add('rescan:start');
+ await releaseRescan.future;
+ order.add('rescan:end');
+ });
+ final joined = coordinator.refresh(() async {
+ fail('refresh must join the queued rescan');
+ });
+
+ expect(identical(joined, rescan), isTrue);
+ releaseRefresh.complete();
+ await refresh;
+ await _flushMicrotasks();
+ expect(order, ['refresh:start', 'refresh:end', 'rescan:start']);
+
+ releaseRescan.complete();
+ await rescan;
+ expect(order, [
+ 'refresh:start',
+ 'refresh:end',
+ 'rescan:start',
+ 'rescan:end',
+ ]);
+ });
+
+ test('distinct rescans retain their requested order', () async {
+ final coordinator = XelisOperationCoordinator(Mutex());
+ final releaseFirst = Completer<void>();
+ final order = <String>[];
+
+ final first = coordinator.rescan(() async {
+ order.add('first:start');
+ await releaseFirst.future;
+ order.add('first:end');
+ });
+ await _flushMicrotasks();
+
+ final second = coordinator.rescan(() async {
+ order.add('second');
+ });
+ final joined = coordinator.refresh(() async {
+ fail('refresh must join the most recently queued rescan');
+ });
+
+ expect(identical(first, second), isFalse);
+ expect(identical(joined, second), isTrue);
+ releaseFirst.complete();
+ await Future.wait([first, second]);
+ expect(order, ['first:start', 'first:end', 'second']);
+ });
+
+ test('connect, exit, connect intent is preserved without polling', () async {
+ final coordinator = XelisOperationCoordinator(Mutex());
+ final releaseFirstConnect = Completer<void>();
+ final releaseSecondConnect = Completer<void>();
+ final order = <String>[];
+
+ final firstConnect = coordinator.connect(() async {
+ order.add('connect 1:start');
+ await releaseFirstConnect.future;
+ order.add('connect 1:end');
+ });
+ await _flushMicrotasks();
+
+ final exit = coordinator.exit(() async {
+ order.add('exit');
+ });
+ final secondConnect = coordinator.connect(() async {
+ order.add('connect 2:start');
+ await releaseSecondConnect.future;
+ order.add('connect 2:end');
+ });
+ final joinedConnect = coordinator.connect(() async {
+ fail('matching connect calls must join');
+ });
+ final joinedRefresh = coordinator.refresh(() async {
+ fail('refresh must join the connect queued after exit');
+ });
+ bool staleEventRan = false;
+ await coordinator.processEvent(() async {
+ staleEventRan = true;
+ });
+ bool staleSyncEventRan = false;
+ await coordinator.processSyncEvent(() async {
+ staleSyncEventRan = true;
+ });
+
+ unawaited(joinedRefresh.then((_) => order.add('joined refresh done')));
+
+ expect(identical(firstConnect, secondConnect), isFalse);
+ expect(identical(secondConnect, joinedConnect), isTrue);
+ expect(staleEventRan, isFalse);
+ expect(staleSyncEventRan, isFalse);
+
+ releaseFirstConnect.complete();
+ await firstConnect;
+ await _flushMicrotasks();
+ expect(order, [
+ 'connect 1:start',
+ 'connect 1:end',
+ 'exit',
+ 'connect 2:start',
+ ]);
+
+ releaseSecondConnect.complete();
+ await Future.wait([exit, secondConnect, joinedRefresh]);
+ await _flushMicrotasks();
+ expect(order.sublist(order.length - 2), [
+ 'connect 2:end',
+ 'joined refresh done',
+ ]);
+ });
+
+ test('a reconnect can retain its distinct node-change intent', () async {
+ final coordinator = XelisOperationCoordinator(Mutex());
+ final releaseFirstConnect = Completer<void>();
+ final order = <String>[];
+
+ final firstConnect = coordinator.connect(() async {
+ order.add('connect');
+ await releaseFirstConnect.future;
+ });
+ await _flushMicrotasks();
+
+ final reconnect = coordinator.connect(() async {
+ order.add('reconnect');
+ }, joinExisting: false);
+
+ expect(identical(firstConnect, reconnect), isFalse);
+ releaseFirstConnect.complete();
+ await Future.wait([firstConnect, reconnect]);
+ expect(order, ['connect', 'reconnect']);
+ });
+
+ test(
+ 'exit suppresses new updates and releases the queue for later work',
+ () async {
+ final coordinator = XelisOperationCoordinator(Mutex());
+ final releaseEvent = Completer<void>();
+ final order = <String>[];
+
+ final event = coordinator.processEvent(() async {
+ order.add('event:start');
+ await releaseEvent.future;
+ order.add('event:end');
+ });
+ await _flushMicrotasks();
+
+ final exit = coordinator.exit(() async {
+ order.add('exit');
+ });
+ await expectLater(
+ coordinator.rescan(() async {
+ fail('rescans scheduled while exiting must not run');
+ }),
+ throwsStateError,
+ );
+ await coordinator.processEvent(() async {
+ fail('events scheduled while exiting must be ignored');
+ });
+ await coordinator.refresh(() async {
+ fail('refreshes scheduled while exiting must be ignored');
+ });
+
+ releaseEvent.complete();
+ await Future.wait([event, exit]);
+
+ await coordinator.refresh(() async {
+ order.add('refresh');
+ });
+ expect(order, ['event:start', 'event:end', 'exit', 'refresh']);
+ },
+ );
+
+ test(
+ 'refresh callers joining a failing connect see the same error',
+ () async {
+ final coordinator = XelisOperationCoordinator(Mutex());
+ final failure = StateError('connect failed');
+ final releaseConnect = Completer<void>();
+
+ final connect = coordinator.connect(() async {
+ await releaseConnect.future;
+ throw failure;
+ });
+ await _flushMicrotasks();
+
+ final joined = coordinator.refresh(() async {
+ fail('refresh must join the in-flight connect');
+ });
+ expect(identical(joined, connect), isTrue);
+
+ final connectExpectation = expectLater(connect, throwsA(same(failure)));
+ final joinedExpectation = expectLater(joined, throwsA(same(failure)));
+ releaseConnect.complete();
+ await Future.wait([connectExpectation, joinedExpectation]);
+
+ bool nextRefreshRan = false;
+ await coordinator.refresh(() async {
+ nextRefreshRan = true;
+ });
+ expect(nextRefreshRan, isTrue);
+ },
+ );
+
+ test('connect-time sync events complete before exit', () async {
+ final coordinator = XelisOperationCoordinator(Mutex());
+ const timeout = Duration(seconds: 5);
+ final order = <String>[];
+ late Future<void> onlineEvent;
+ late Future<void> historySyncedEvent;
+
+ final connect = coordinator.connect(() async {
+ order.add('connect');
+ onlineEvent = coordinator.processSyncEvent(() async {
+ fail('the online event must join connect');
+ });
+ historySyncedEvent = coordinator.processSyncEvent(() async {
+ fail('the history synced event must join connect');
+ });
+ });
+ await connect.timeout(timeout);
+ await Future.wait([onlineEvent, historySyncedEvent]).timeout(timeout);
+ await coordinator
+ .exit(() async {
+ order.add('exit');
+ })
+ .timeout(timeout);
+
+ expect(order, ['connect', 'exit']);
+ });
+
+ test('a failed operation does not latch the queue or join state', () async {
+ final coordinator = XelisOperationCoordinator(Mutex());
+ final failure = StateError('refresh failed');
+
+ await expectLater(
+ coordinator.refresh(() async {
+ throw failure;
+ }),
+ throwsA(same(failure)),
+ );
+
+ bool nextRefreshRan = false;
+ await coordinator.refresh(() async {
+ nextRefreshRan = true;
+ });
+
+ expect(nextRefreshRan, isTrue);
+ expect(coordinator.activeOperation, XelisOperation.idle);
+ });
+}
+
+Future<void> _flushMicrotasks() => Future<void>.delayed(Duration.zero);
Why this scored 35/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.