fix: bandaid fix for race condition when checkElectrumAdapter is called concurrently. The architecture of ElectrumXClient and ClientManager needs to be revisited and refactored in a safer way
What changed, and why it matters
This commit adds a temporary lock (mutex) around a function called checkElectrumAdapter in a cryptocurrency wallet app. The developer notes that without the lock, the function could be run by multiple parts of the app at the same time, causing a race condition. The race could potentially lead to duplicate or conflicting Electrum server connections, connection errors, or unexpected behavior when managing which server client is active. The fix is described as a 'bandaid,' meaning the underlying design still needs a safer rewrite.
Treat this as a reliability and potential privacy fix. Users should update to the patched version. Developers should prioritize the refactor mentioned in the commit message to make ElectrumXClient and ClientManager thread-safe by design, rather than relying on a single coarse mutex. Review whether other methods that mutate _electrumAdapterChannel or ClientManager also need synchronization.
Security signals we found
Race condition in connection management
Shared mutable state (_electrumAdapterChannel, ClientManager) without synchronization
Potential for duplicate or orphaned Electrum client connections
Possible use of stale Tor/clearnet proxy settings due to interleaving
Developer-described 'bandaid' fix indicating residual architectural risk
Evidence from the diff
The change wraps the entire body of ElectrumXClient.checkElectrumAdapter() in a new _adapterMutex.protect() block. The function reads and writes shared mutable state including _electrumAdapterChannel, ClientManager.sharedInstance, Tor proxy settings, and failover configuration. Prior to the patch, concurrent calls could interleave these operations, leading to inconsistent state such as a null _electrumAdapterChannel paired with a registered ClientManager entry, duplicate connections, or use of stale proxy/failover settings. The patch serializes access but does not refactor the broader architecture, as acknowledged by the commit message.
Changed components
lib/electrumx_rpc/electrumx_client.dartElectrumXClient.checkElectrumAdapter()ClientManager shared instanceTor/clearnet proxy selection logicElectrum server failover logicInspect captured patch +97 / −91
diff --git a/lib/electrumx_rpc/electrumx_client.dart b/lib/electrumx_rpc/electrumx_client.dart
index abcb012..94b650b 100644
--- a/lib/electrumx_rpc/electrumx_client.dart
+++ b/lib/electrumx_rpc/electrumx_client.dart
@@ -117,6 +117,8 @@ class ElectrumXClient {
final Mutex _torConnectingLock = Mutex();
bool _requireMutex = false;
+ final _adapterMutex = Mutex();
+
ElectrumXClient({
required String host,
required int port,
@@ -219,111 +221,115 @@ class ElectrumXClient {
}
Future<void> checkElectrumAdapter() async {
- ({InternetAddress host, int port})? proxyInfo;
-
- if (AppConfig.hasFeature(AppFeature.tor)) {
- // If we're supposed to use Tor...
- if (_prefs.useTor) {
- // But Tor isn't running...
- if (_torService.status != TorConnectionStatus.connected) {
- // And the killswitch isn't set...
- if (!_prefs.torKillSwitch) {
- // Then we'll just proceed and connect to ElectrumX through
- // clearnet at the bottom of this function.
- Logging.instance.w(
- "Tor preference set but Tor is not enabled, killswitch not set,"
- " connecting to Electrum adapter through clearnet",
- );
+ await _adapterMutex.protect(() async {
+ ({InternetAddress host, int port})? proxyInfo;
+
+ if (AppConfig.hasFeature(AppFeature.tor)) {
+ // If we're supposed to use Tor...
+ if (_prefs.useTor) {
+ // But Tor isn't running...
+ if (_torService.status != TorConnectionStatus.connected) {
+ // And the killswitch isn't set...
+ if (!_prefs.torKillSwitch) {
+ // Then we'll just proceed and connect to ElectrumX through
+ // clearnet at the bottom of this function.
+ Logging.instance.w(
+ "Tor preference set but Tor is not enabled, killswitch not set,"
+ " connecting to Electrum adapter through clearnet",
+ );
+ } else {
+ // ... But if the killswitch is set, then we throw an exception.
+ throw Exception(
+ "Tor preference and killswitch set but Tor is not enabled, "
+ "not connecting to Electrum adapter",
+ );
+ // TODO [prio=low]: Try to start Tor.
+ }
} else {
- // ... But if the killswitch is set, then we throw an exception.
- throw Exception(
- "Tor preference and killswitch set but Tor is not enabled, "
- "not connecting to Electrum adapter",
+ // Get the proxy info from the TorService.
+ proxyInfo = _torService.getProxyInfo();
+ }
+
+ if (netType == TorPlainNetworkOption.clear) {
+ _electrumAdapterChannel = null;
+ await ClientManager.sharedInstance.remove(
+ cryptoCurrency: cryptoCurrency,
);
- // TODO [prio=low]: Try to start Tor.
}
} else {
- // Get the proxy info from the TorService.
- proxyInfo = _torService.getProxyInfo();
- }
-
- if (netType == TorPlainNetworkOption.clear) {
- _electrumAdapterChannel = null;
- await ClientManager.sharedInstance.remove(
- cryptoCurrency: cryptoCurrency,
- );
- }
- } else {
- if (netType == TorPlainNetworkOption.tor) {
- _electrumAdapterChannel = null;
- await ClientManager.sharedInstance.remove(
- cryptoCurrency: cryptoCurrency,
- );
+ if (netType == TorPlainNetworkOption.tor) {
+ _electrumAdapterChannel = null;
+ await ClientManager.sharedInstance.remove(
+ cryptoCurrency: cryptoCurrency,
+ );
+ }
}
}
- }
- // If the current ElectrumAdapterClient is closed, create a new one.
- if (getElectrumAdapter() != null && getElectrumAdapter()!.peer.isClosed) {
- _electrumAdapterChannel = null;
- await ClientManager.sharedInstance.remove(cryptoCurrency: cryptoCurrency);
- }
-
- final String useHost;
- final int usePort;
- final bool useUseSSL;
-
- if (currentFailoverIndex == -1) {
- useHost = host;
- usePort = port;
- useUseSSL = useSSL;
- } else {
- _electrumAdapterChannel = null;
- await ClientManager.sharedInstance.remove(cryptoCurrency: cryptoCurrency);
- useHost = _failovers[currentFailoverIndex].address;
- usePort = _failovers[currentFailoverIndex].port;
- useUseSSL = _failovers[currentFailoverIndex].useSSL;
- }
+ // If the current ElectrumAdapterClient is closed, create a new one.
+ if (getElectrumAdapter() != null && getElectrumAdapter()!.peer.isClosed) {
+ _electrumAdapterChannel = null;
+ await ClientManager.sharedInstance.remove(
+ cryptoCurrency: cryptoCurrency,
+ );
+ }
- _electrumAdapterChannel ??= await electrum_adapter.connect(
- useHost,
- port: usePort,
- connectionTimeout: connectionTimeoutForSpecialCaseJsonRPCClients,
- aliveTimerDuration: connectionTimeoutForSpecialCaseJsonRPCClients,
- acceptUnverified: false,
- useSSL: useUseSSL,
- proxyInfo: proxyInfo,
- );
+ final String useHost;
+ final int usePort;
+ final bool useUseSSL;
- if (getElectrumAdapter() == null) {
- final ElectrumClient newClient;
- if (cryptoCurrency is Firo) {
- newClient = FiroElectrumClient(
- _electrumAdapterChannel!,
- useHost,
- usePort,
- useUseSSL,
- proxyInfo,
- );
+ if (currentFailoverIndex == -1) {
+ useHost = host;
+ usePort = port;
+ useUseSSL = useSSL;
} else {
- newClient = ElectrumClient(
- _electrumAdapterChannel!,
- useHost,
- usePort,
- useUseSSL,
- proxyInfo,
+ _electrumAdapterChannel = null;
+ await ClientManager.sharedInstance.remove(
+ cryptoCurrency: cryptoCurrency,
);
+ useHost = _failovers[currentFailoverIndex].address;
+ usePort = _failovers[currentFailoverIndex].port;
+ useUseSSL = _failovers[currentFailoverIndex].useSSL;
}
- await newClient.request('server.version');
-
- await ClientManager.sharedInstance.addClient(
- newClient,
- cryptoCurrency: cryptoCurrency,
- netType: netType,
+ _electrumAdapterChannel ??= await electrum_adapter.connect(
+ useHost,
+ port: usePort,
+ connectionTimeout: connectionTimeoutForSpecialCaseJsonRPCClients,
+ aliveTimerDuration: connectionTimeoutForSpecialCaseJsonRPCClients,
+ acceptUnverified: false,
+ useSSL: useUseSSL,
+ proxyInfo: proxyInfo,
);
- }
- return;
+ if (getElectrumAdapter() == null) {
+ final ElectrumClient newClient;
+ if (cryptoCurrency is Firo) {
+ newClient = FiroElectrumClient(
+ _electrumAdapterChannel!,
+ useHost,
+ usePort,
+ useUseSSL,
+ proxyInfo,
+ );
+ } else {
+ newClient = ElectrumClient(
+ _electrumAdapterChannel!,
+ useHost,
+ usePort,
+ useUseSSL,
+ proxyInfo,
+ );
+ }
+
+ await newClient.request('server.version');
+
+ await ClientManager.sharedInstance.addClient(
+ newClient,
+ cryptoCurrency: cryptoCurrency,
+ netType: netType,
+ );
+ }
+ });
}
/// Send raw rpc command
Why this scored 45/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.