fix: Electrum wallets stuck on Connecting after a failed connect (#3763)
What changed, and why it matters
This commit fixes a bug in Cake Wallet where Bitcoin-family wallets (BTC, LTC, BCH, DOGE) could get stuck showing 'Connecting' forever after a failed network connection. The root causes were: failed connections were not reported, retries only handled some disconnect cases, and slow or hanging network handshakes had no timeout. The patch makes failures visible, adds timeouts, prevents old/replaced connections from interfering with new ones, and stops closed wallets from reconnecting on their own. It also fixes a related issue where switching servers could stop incoming payment notifications because address subscriptions were not re-sent.
Treat this as a reliability and minor security hardening fix. It primarily prevents denial-of-service-like UX failures and resource leaks rather than enabling remote code execution or theft. Reviewers should verify the new timeouts and the _connectAttempt/_isClosed guards cover all async paths, and that the added tests pass. Users on affected versions should update to avoid stuck wallets and missed transaction notifications.
Security signals we found
Connection-state confusion: failed connects were not reported, leaving the wallet in a 'Connecting' state indefinitely and preventing automatic recovery.
Missing timeout on TLS/SOCKS handshakes allowed connections to hang forever, blocking user-initiated node switches and Tor toggles.
Race between overlapping connection attempts: a late socket from a superseded attempt could overwrite the active socket or flip useSSL, and late onDone/onError could tear down the successor socket.
Late replies on a replaced socket could complete same-id requests of the new session because request IDs restart at 0 after close().
Resource leaks: SOCKS failure did not close the Tor proxy connection; the 5 s reconnect timer was never cancelled, so closed wallets could reopen their Electrum client and leave sockets/keep-alive timers orphaned.
Missed subscriptions after reconnect: the script-hash subscription map was only cleared on a 'disconnected' event, so node switches/Tor toggles/resume reconnects did not re-subscribe addresses, breaking push notifications for incoming payments.
False 'Synced' state: app-resume reconnection could call startSync() on a failed client, syncing a dead client into a false positive.
Evidence from the diff
The patch hardens Electrum client connection handling in cw_bitcoin and the shared ProxySocket wrapper. Key changes: (1) ElectrumClient.connect now always reports ConnectionStatus.failed on error and uses a per-attempt counter so superseded or closed attempts cannot install a late socket or update state; (2) ping() no longer marks the client connected when there is no socket or when the reply arrives on a replaced socket; (3) ProxySocket.connect enforces whole-handshake deadlines (20 s clearnet, 60 s Tor), destroying late sockets and closing timed-out SOCKS sessions; (4) ElectrumWallet tracks _isClosed and a _reconnectTimer, cancels retries in close(), skips reconnects for closed wallets, and resets the script-hash subscription map on reconnect so blockchain.scripthash.subscribe is re-sent; (5) tests are added covering refused connects, stalled TLS/Tor handshakes, superseded connects, late socket closes, and closed-wallet behavior.
Changed components
cw_bitcoin/lib/electrum.dartcw_bitcoin/lib/electrum_wallet.dartcw_core/lib/utils/proxy_socket/abstract.dartBitcoin (BTC), Litecoin (LTC), Bitcoin Cash (BCH), Dogecoin (DOGE) Electrum wallets in Cake Wallet/Monero.comInspect captured patch +845 / −34
### cw_bitcoin/lib/electrum.dart
@@ -50,10 +50,13 @@ class ElectrumClient {
final Map<String, SocketTask> _tasks;
Map<String, SocketTask> get tasks => _tasks;
final Map<String, String> _errors;
- ConnectionStatus _connectionStatus = ConnectionStatus.disconnected;
Timer? _aliveTimer;
String unterminatedString;
+ // Bumped by every connect() and close(). An attempt that is no longer the latest when its
+ // socket arrives (node switch, reconnect, wallet closed) must not install it or report status.
+ int _connectAttempt = 0;
+
Uri? uri;
bool? useSSL;
@@ -66,6 +69,7 @@ class ElectrumClient {
}
Future<void> connect({required String host, required int port}) async {
+ final attempt = ++_connectAttempt;
_setConnectionStatus(ConnectionStatus.connecting);
// Reset internal state to ensure clean connection
@@ -74,37 +78,47 @@ class ElectrumClient {
try {
await socket?.close();
} catch (_) {}
+ if (attempt != _connectAttempt) {
+ return;
+ }
socket = null;
final ssl = !(useSSL == false || (useSSL == null && uri.toString().contains("btc-electrum")));
+ final ProxySocket newSocket;
try {
- socket = await ProxyWrapper()
+ newSocket = await ProxyWrapper()
.getSocksSocket(ssl, host, port, connectionTimeout: connectionTimeout);
} catch (e) {
printV("connect: $e");
- if (e is HandshakeException) {
- useSSL = !(useSSL ?? false);
+ if (attempt != _connectAttempt) {
+ return;
}
- if (_connectionStatus != ConnectionStatus.connecting) {
- _setConnectionStatus(ConnectionStatus.failed);
+ if (e is HandshakeException) {
+ useSSL = !(useSSL ?? false);
}
+ // Always report it: "connecting" is not retried by the wallet, so a failure left
+ // unreported keeps it on the spinner until the app is resumed or restarted.
+ _setConnectionStatus(ConnectionStatus.failed);
return;
}
- if (socket == null) {
- if (_connectionStatus != ConnectionStatus.connecting) {
- _setConnectionStatus(ConnectionStatus.failed);
- }
-
+ if (attempt != _connectAttempt) {
+ newSocket.destroy();
return;
}
+ socket = newSocket;
+
// use ping to determine actual connection status since we could've just not timed out yet:
// _setConnectionStatus(ConnectionStatus.connected);
- socket!.listen(
+ newSocket.listen(
(Uint8List event) {
+ // A replaced socket's late reply must not complete a same-id request of the new session.
+ if (!identical(socket, newSocket)) {
+ return;
+ }
try {
final msg = utf8.decode(event.toList());
final messagesList = msg.split("\n");
@@ -119,6 +133,10 @@ class ElectrumClient {
}
},
onError: (Object error) {
+ // A replaced socket's late error/close must not tear down its successor.
+ if (!identical(socket, newSocket)) {
+ return;
+ }
final errorMsg = error.toString();
printV(errorMsg);
unterminatedString = '';
@@ -128,6 +146,9 @@ class ElectrumClient {
},
onDone: () {
printV("SOCKET CLOSED!!!!!");
+ if (!identical(socket, newSocket)) {
+ return;
+ }
unterminatedString = '';
try {
_setConnectionStatus(ConnectionStatus.disconnected);
@@ -189,11 +210,23 @@ class ElectrumClient {
}
Future<void> ping() async {
+ // The keep-alive timer outlives a dropped socket, and callWithTimeout returns null when there
+ // is no socket, which must not count as a pong. A reply on a since-replaced socket says
+ // nothing about the current one either.
+ final pinged = socket;
+ if (pinged == null || pinged.isClosed) {
+ return;
+ }
+
try {
await callWithTimeout(method: 'server.ping');
- _setConnectionStatus(ConnectionStatus.connected);
+ if (identical(socket, pinged)) {
+ _setConnectionStatus(ConnectionStatus.connected);
+ }
} catch (_) {
- _setConnectionStatus(ConnectionStatus.disconnected);
+ if (identical(socket, pinged)) {
+ _setConnectionStatus(ConnectionStatus.disconnected);
+ }
}
}
@@ -701,6 +734,7 @@ class ElectrumClient {
}
Future<void> close() async {
+ _connectAttempt++;
_aliveTimer?.cancel();
try {
await socket?.close();
@@ -777,7 +811,6 @@ class ElectrumClient {
void _setConnectionStatus(ConnectionStatus status) {
onConnectionStatusChange?.call(status);
- _connectionStatus = status;
if (!isConnected) {
try {
socket?.destroy();
### cw_bitcoin/lib/electrum_wallet.dart
@@ -600,6 +600,8 @@ abstract class ElectrumWalletBase
bool silentPaymentsScanningActive = false;
bool _isTryingToConnect = false;
+ Timer? _reconnectTimer;
+ bool _isClosed = false;
bool? _isBatchSupported;
DateTime? _syncBenchmarkStartTime;
DateTime? _syncStartedAt;
@@ -1051,6 +1053,7 @@ abstract class ElectrumWalletBase
}
Node? node;
+ bool? _connectingViaTor;
Future<bool> getNodeIsElectrs() async {
if (node == null) {
@@ -1108,17 +1111,33 @@ abstract class ElectrumWalletBase
@action
@override
Future<void> connectToNode({required Node node}) async {
+ // A closed wallet is discarded; reconnecting it would leak a socket and its keep-alive.
+ if (_isClosed) {
+ return;
+ }
+ final viaTor = CakeTor.instance?.started ?? false;
+ final isSameConnection = node == this.node && viaTor == _connectingViaTor;
this.node = node;
_isBatchSupported = null;
- if (syncStatus is ConnectingSyncStatus) return;
+ // Only a repeat of the attempt in flight is skipped; dropping a different node or a Tor
+ // toggle here would leave the wallet on the old attempt.
+ if (syncStatus is ConnectingSyncStatus && isSameConnection) {
+ return;
+ }
+ _connectingViaTor = viaTor;
try {
syncStatus = ConnectingSyncStatus();
await _receiveStream?.cancel();
await electrumClient.close();
+ if (_isClosed) {
+ return;
+ }
_isBatchSupported = null;
+ // The new server session has no subscriptions yet.
+ _scripthashesUpdateSubject = {};
electrumClient.onConnectionStatusChange = _onConnectionStatusChange;
@@ -2103,6 +2122,11 @@ abstract class ElectrumWalletBase
Future<void> close({bool shouldCleanup = false}) async {
_missingHistoryQueue.clear();
_unresolvedAccountRetryCount.clear();
+ // A pending or later reconnect (e.g. from a sync still running) would reopen the client of a
+ // closed wallet.
+ _isClosed = true;
+ _reconnectTimer?.cancel();
+ _isTryingToConnect = false;
try {
await _receiveStream?.cancel();
await electrumClient.close();
@@ -4439,11 +4463,11 @@ abstract class ElectrumWalletBase
// Needs to re-subscribe to all scripthashes when reconnected
_scripthashesUpdateSubject = {};
- if (_isTryingToConnect) return;
+ if (_isTryingToConnect || _isClosed) return;
_isTryingToConnect = true;
- Timer(Duration(seconds: 5), () {
+ _reconnectTimer = Timer(Duration(seconds: 5), () {
if (this.syncStatus is NotConnectedSyncStatus ||
this.syncStatus is LostConnectionSyncStatus) {
this.electrumClient.connectToUri(
@@ -4615,6 +4639,9 @@ abstract class ElectrumWalletBase
}
Future<void> _performFullReconnection() async {
+ if (_isClosed) {
+ return;
+ }
try {
SocketHealthLogger().logHealthCheck(
walletType: type,
@@ -4627,12 +4654,23 @@ abstract class ElectrumWalletBase
await _receiveStream?.cancel();
await electrumClient.close();
+ if (_isClosed) {
+ return;
+ }
+ // The new server session has no subscriptions yet.
+ _scripthashesUpdateSubject = {};
if (node != null) {
electrumClient.onConnectionStatusChange = _onConnectionStatusChange;
await electrumClient.connectToUri(node!.uri, useSSL: node!.useSSL);
+ // On failure the client reports `failed` and the 5 s retry takes over. Syncing with no
+ // socket would only fail.
+ if (!electrumClient.isConnected) {
+ return;
+ }
+
await startSync();
SocketHealthLogger().logHealthCheck(
### cw_bitcoin/test/electrum_client_connect_test.dart
@@ -0,0 +1,280 @@
+import "dart:async";
+import "dart:convert";
+import "dart:io";
+
+import "package:cw_bitcoin/electrum.dart";
+import "package:cw_core/utils/proxy_socket/abstract.dart";
+import "package:cw_core/utils/proxy_wrapper.dart";
+import "package:cw_core/utils/tor/disabled.dart";
+import "package:cw_core/utils/tor/socks.dart";
+import "package:flutter_test/flutter_test.dart";
+
+/// Electrum server stand-in that answers every request with a null result.
+class _FakeServer {
+ _FakeServer._(this.server);
+
+ final ServerSocket server;
+ final clients = <Socket>[];
+
+ /// [closeDelay]: after the client closes its side, wait this long before closing ours.
+ static Future<_FakeServer> start({Duration closeDelay = Duration.zero}) async {
+ final fake = _FakeServer._(await ServerSocket.bind(InternetAddress.loopbackIPv4, 0));
+ fake.server.listen((c) {
+ fake.clients.add(c);
+ c.cast<List<int>>().transform(utf8.decoder).transform(const LineSplitter()).listen(
+ (line) {
+ final id = (json.decode(line) as Map)["id"];
+ c.write('{"jsonrpc":"2.0","result":null,"id":${json.encode(id)}}\n');
+ },
+ onDone: () => Future.delayed(closeDelay, () => c.destroy()),
+ onError: (_) {},
+ );
+ });
+ return fake;
+ }
+
+ Uri get uri => Uri.parse("tcp://127.0.0.1:${server.port}");
+}
+
+Future<int> _refusedPort() async {
+ final s = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ final port = s.port;
+ await s.close();
+ return port;
+}
+
+/// SOCKS5 stand-in for Tor. [connectReply] null = never answer CONNECT, as Tor does while it has
+/// no circuit. On 0x00 the stream is piped to 127.0.0.1:[pipeToPort] after [replyDelay].
+/// [closed] gets one future per accepted client, completing when that client goes away.
+Future<ServerSocket> _fakeTor({
+ int? connectReply,
+ int? pipeToPort,
+ Duration replyDelay = Duration.zero,
+ List<Future<void>>? closed,
+}) async {
+ final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ server.listen((c) {
+ final gone = Completer<void>();
+ closed?.add(gone.future);
+ var stage = 0;
+ Socket? upstream;
+ c.listen(
+ (data) async {
+ if (stage == 0) {
+ stage = 1;
+ c.add([0x05, 0x00]);
+ } else if (stage == 1) {
+ stage = 2;
+ if (connectReply == null) {
+ return;
+ }
+ await Future.delayed(replyDelay);
+ c.add([0x05, connectReply, 0x00, 0x01, 0, 0, 0, 0, 0, 0]);
+ if (connectReply == 0x00 && pipeToPort != null) {
+ upstream = await Socket.connect(InternetAddress.loopbackIPv4, pipeToPort);
+ upstream!.listen(c.add, onDone: () => c.destroy(), onError: (_) {});
+ }
+ } else {
+ upstream?.add(data);
+ }
+ },
+ onError: (_) {},
+ onDone: () {
+ upstream?.destroy();
+ if (!gone.isCompleted) {
+ gone.complete();
+ }
+ },
+ );
+ });
+ return server;
+}
+
+ElectrumClient _client(List<ConnectionStatus> log) =>
+ ElectrumClient()..onConnectionStatusChange = log.add;
+
+void main() {
+ setUp(() => CakeTor.instance = CakeTorDisabled());
+
+ test("a refused connection is reported as failed", () async {
+ final log = <ConnectionStatus>[];
+ final client = _client(log);
+
+ await client.connectToUri(Uri.parse("tcp://127.0.0.1:${await _refusedPort()}"), useSSL: false);
+
+ expect(log, [ConnectionStatus.connecting, ConnectionStatus.failed]);
+ });
+
+ test(
+ "a TLS handshake that never finishes fails at the clearnet deadline",
+ () async {
+ final silent = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ silent.listen((c) => c.listen((_) {}, onError: (_) {}));
+ final log = <ConnectionStatus>[];
+ final client = _client(log);
+ final stopwatch = Stopwatch()..start();
+
+ await client.connectToUri(Uri.parse("ssl://127.0.0.1:${silent.port}"), useSSL: true);
+
+ expect(log, [ConnectionStatus.connecting, ConnectionStatus.failed]);
+ expect(stopwatch.elapsed, greaterThanOrEqualTo(ProxySocket.clearnetConnectDeadline));
+ expect(
+ stopwatch.elapsed,
+ lessThan(ProxySocket.clearnetConnectDeadline + const Duration(seconds: 3)),
+ );
+ await silent.close();
+ },
+ timeout: const Timeout(Duration(seconds: 40)),
+ );
+
+ test(
+ "Tor never answering CONNECT fails at the Tor deadline and closes the proxy socket",
+ () async {
+ final closed = <Future<void>>[];
+ final tor = await _fakeTor(closed: closed);
+ CakeTor.instance = CakeTorSocks(tor.port);
+ final log = <ConnectionStatus>[];
+ final client = _client(log);
+ final stopwatch = Stopwatch()..start();
+
+ await client.connectToUri(Uri.parse("tcp://example.onion:50001"), useSSL: false);
+
+ expect(log, [ConnectionStatus.connecting, ConnectionStatus.failed]);
+ expect(stopwatch.elapsed, greaterThanOrEqualTo(ProxySocket.torConnectDeadline));
+ expect(
+ stopwatch.elapsed,
+ lessThan(ProxySocket.torConnectDeadline + const Duration(seconds: 3)),
+ );
+ await closed.single.timeout(const Duration(seconds: 3));
+ await tor.close();
+ },
+ timeout: const Timeout(Duration(seconds: 90)),
+ );
+
+ test("Tor refusing CONNECT is reported as failed and the Tor session is closed", () async {
+ final closed = <Future<void>>[];
+ final tor = await _fakeTor(connectReply: 0x04, closed: closed);
+ CakeTor.instance = CakeTorSocks(tor.port);
+ final log = <ConnectionStatus>[];
+ final client = _client(log);
+
+ await client.connectToUri(Uri.parse("tcp://example.onion:50001"), useSSL: false);
+
+ expect(log, [ConnectionStatus.connecting, ConnectionStatus.failed]);
+ await closed.single.timeout(const Duration(seconds: 3));
+ await tor.close();
+ });
+
+ test(
+ "after the server drops the connection, the keep-alive does not report connected",
+ () async {
+ final server = await _FakeServer.start();
+ final log = <ConnectionStatus>[];
+ final client = _client(log);
+ await client.connectToUri(server.uri, useSSL: false);
+ await Future.delayed(const Duration(seconds: 6));
+ expect(log.last, ConnectionStatus.connected);
+
+ for (final c in server.clients) {
+ c.destroy();
+ }
+ await server.server.close();
+ await Future.delayed(const Duration(seconds: 11)); // two keep-alive ticks
+
+ expect(log, [
+ ConnectionStatus.connecting,
+ ConnectionStatus.connected,
+ ConnectionStatus.disconnected,
+ ]);
+ expect(client.isConnected, isFalse);
+ await client.close();
+ },
+ timeout: const Timeout(Duration(seconds: 40)),
+ );
+
+ test(
+ "reconnecting: the old socket closing late does not tear down the new one",
+ () async {
+ final a = await _FakeServer.start(closeDelay: const Duration(milliseconds: 500));
+ final b = await _FakeServer.start();
+ final log = <ConnectionStatus>[];
+ final client = _client(log);
+ await client.connectToUri(a.uri, useSSL: false);
+ await Future.delayed(const Duration(seconds: 6));
+
+ // The wallet's 5 s retry reconnects like this, without close().
+ await client.connectToUri(b.uri, useSSL: false);
+ await Future.delayed(const Duration(seconds: 6)); // A closes after 500 ms; B gets pinged
+
+ expect(client.isConnected, isTrue);
+ expect(log.skip(2), [ConnectionStatus.connecting, ConnectionStatus.connected]);
+ await client.close();
+ await a.server.close();
+ await b.server.close();
+ },
+ timeout: const Timeout(Duration(seconds: 40)),
+ );
+
+ test(
+ "a connect superseded by a newer one does not install its late socket",
+ () async {
+ final target = await _FakeServer.start();
+ final slowClosed = <Future<void>>[];
+ final slowTor = await _fakeTor(
+ connectReply: 0x00,
+ pipeToPort: target.server.port,
+ replyDelay: const Duration(seconds: 2),
+ closed: slowClosed,
+ );
+ final fastTor = await _fakeTor(connectReply: 0x00, pipeToPort: target.server.port);
+ final log = <ConnectionStatus>[];
+ final client = _client(log);
+
+ CakeTor.instance = CakeTorSocks(slowTor.port);
+ unawaited(client.connectToUri(Uri.parse("tcp://old-node.onion:50001"), useSSL: false));
+ await Future.delayed(const Duration(milliseconds: 300));
+ CakeTor.instance = CakeTorSocks(fastTor.port);
+ await client.connectToUri(Uri.parse("tcp://new-node.onion:50001"), useSSL: false);
+ final current = client.socket;
+ await Future.delayed(const Duration(seconds: 7)); // the old attempt completes at ~2 s
+
+ expect(identical(client.socket, current), isTrue);
+ expect(client.isConnected, isTrue);
+ expect(log, [
+ ConnectionStatus.connecting,
+ ConnectionStatus.connecting,
+ ConnectionStatus.connected,
+ ]);
+ await slowClosed.single.timeout(const Duration(seconds: 3)); // the late socket was destroyed
+ await client.close();
+ await slowTor.close();
+ await fastTor.close();
+ await target.server.close();
+ },
+ timeout: const Timeout(Duration(seconds: 40)),
+ );
+
+ test(
+ "close() during a connect: the late socket is not installed",
+ () async {
+ final target = await _FakeServer.start();
+ final tor = await _fakeTor(
+ connectReply: 0x00,
+ pipeToPort: target.server.port,
+ replyDelay: const Duration(seconds: 2),
+ );
+ CakeTor.instance = CakeTorSocks(tor.port);
+ final client = _client([]);
+
+ unawaited(client.connectToUri(Uri.parse("tcp://node.onion:50001"), useSSL: false));
+ await Future.delayed(const Duration(milliseconds: 300));
+ await client.close();
+ await Future.delayed(const Duration(seconds: 4)); // the connect completes at ~2 s
+
+ expect(client.socket, isNull);
+ await tor.close();
+ await target.server.close();
+ },
+ timeout: const Timeout(Duration(seconds: 30)),
+ );
+}
### cw_bitcoin/test/electrum_wallet_connection_test.dart
@@ -0,0 +1,420 @@
+import "dart:async";
+import "dart:convert";
+import "dart:io";
+import "dart:typed_data";
+
+import "package:bitcoin_base/bitcoin_base.dart";
+import "package:blockchain_utils/blockchain_utils.dart";
+import "package:cw_bitcoin/bitcoin_address_record.dart";
+import "package:cw_bitcoin/bitcoin_wallet_addresses.dart";
+import "package:cw_bitcoin/electrum_wallet.dart";
+import "package:cw_bitcoin/payjoin/manager.dart";
+import "package:cw_bitcoin/utils.dart";
+import "package:cw_core/crypto_currency.dart";
+import "package:cw_core/db/sqlite.dart";
+import "package:cw_core/encryption_file_utils.dart";
+import "package:cw_core/node.dart";
+import "package:cw_core/sync_status.dart";
+import "package:cw_core/unspent_coins_info.dart";
+import "package:cw_core/utils/proxy_wrapper.dart";
+import "package:cw_core/utils/tor/disabled.dart";
+import "package:cw_core/utils/tor/socks.dart";
+import "package:cw_core/wallet_info.dart";
+import "package:cw_core/wallet_type.dart";
+import "package:flutter_test/flutter_test.dart";
+import "package:hive/hive.dart";
+import "package:mobx/mobx.dart";
+import "package:shared_preferences/shared_preferences.dart";
+import "package:sqflite_common_ffi/sqflite_ffi.dart";
+
+final _master = Bip32Slip10Secp256k1.fromSeed(List<int>.generate(64, (i) => i));
+final _receiveHd = _master.derivePath("m/84'/0'/0'/0") as Bip32Slip10Secp256k1;
+final _changeHd = _master.derivePath("m/84'/0'/0'/1") as Bip32Slip10Secp256k1;
+const _addressCount = 3;
+
+class _NoPayjoin implements PayjoinManager {
+ @override
+ dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError();
+}
+
+class _NoUnspentsBox implements Box<UnspentCoinsInfo> {
+ @override
+ dynamic noSuchMethod(Invocation invocation) => throw UnimplementedError();
+}
+
+class _Addresses extends BitcoinWalletAddresses {
+ _Addresses(super.walletInfo)
+ : super(
+ mainHdByTypeAndAccount: {
+ 0: {SegwitAddresType.p2wpkh: _receiveHd},
+ },
+ sideHdByTypeAndAccount: {
+ 0: {SegwitAddresType.p2wpkh: _changeHd},
+ },
+ accountIndexes: [0],
+ currentAccountIndex: 0,
+ legacyMainHd: _receiveHd,
+ legacySideHd: _changeHd,
+ network: BitcoinNetwork.mainnet,
+ isHardwareWallet: false,
+ payjoinManager: _NoPayjoin(),
+ masterHd: _master,
+ initialAddresses: [
+ for (var i = 0; i < _addressCount; i++)
+ BitcoinAddressRecord(
+ generateP2WPKHAddress(hd: _receiveHd, network: BitcoinNetwork.mainnet, index: i),
+ index: i,
+ type: SegwitAddresType.p2wpkh,
+ network: BitcoinNetwork.mainnet,
+ ),
+ ],
+ );
+
+ @override
+ Future<void> saveAddressesInBox() async {}
+}
+
+/// Electrum server stand-in: answers requests with a null result (a block height for
+/// blockchain.headers.subscribe, so a sync gets past its first step), leaves batch requests
+/// unanswered, and counts address subscriptions.
+class _FakeNode {
+ _FakeNode._(this._server);
+
+ final ServerSocket _server;
+ int subscribes = 0;
+
+ static Future<_FakeNode> start({int port = 0}) async {
+ final node = _FakeNode._(await ServerSocket.bind(InternetAddress.loopbackIPv4, port));
+ node._server.listen((c) {
+ c.cast<List<int>>().transform(utf8.decoder).transform(const LineSplitter()).listen(
+ (line) {
+ final request = json.decode(line);
+ if (request is! Map) {
+ return;
+ }
+ if (request["method"] == "blockchain.scripthash.subscribe") {
+ node.subscribes++;
+ }
+ final result =
+ request["method"] == "blockchain.headers.subscribe" ? '{"height":800000}' : "null";
+ c.write('{"jsonrpc":"2.0","result":$result,"id":${json.encode(request['id'])}}\n');
+ },
+ onDone: () => c.destroy(),
+ onError: (_) {},
+ );
+ });
+ return node;
+ }
+
+ int get port => _server.port;
+
+ Future<void> close() => _server.close();
+}
+
+/// Accepts connections and never answers, so a TLS handshake to it never finishes.
+Future<ServerSocket> _silentServer(List<Socket> accepted) async {
+ final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ server.listen((c) {
+ accepted.add(c);
+ c.listen((_) {}, onError: (_) {});
+ });
+ return server;
+}
+
+Future<int> _refusedPort() async {
+ final s = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ final port = s.port;
+ await s.close();
+ return port;
+}
+
+/// SOCKS5 stand-in for Tor that sends every CONNECT to 127.0.0.1:[targetPort].
+Future<ServerSocket> _fakeTor(int targetPort, {required void Function() onConnect}) async {
+ final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ server.listen((c) {
+ var stage = 0;
+ Socket? upstream;
+ c.listen(
+ (data) async {
+ if (stage == 0) {
+ stage = 1;
+ c.add([0x05, 0x00]);
+ } else if (stage == 1) {
+ stage = 2;
+ onConnect();
+ c.add([0x05, 0x00, 0x00, 0x01, 0, 0, 0, 0, 0, 0]);
+ upstream = await Socket.connect(InternetAddress.loopbackIPv4, targetPort);
+ upstream!.listen(c.add, onDone: () => c.destroy(), onError: (_) {});
+ } else {
+ upstream?.add(data);
+ }
+ },
+ onError: (_) {},
+ onDone: () => upstream?.destroy(),
+ );
+ });
+ return server;
+}
+
+Node _node(int port, {bool useSSL = false}) =>
+ Node(uri: "127.0.0.1:$port", type: WalletType.bitcoin, useSSL: useSSL);
+
+ElectrumWallet _wallet() {
+ final walletInfo = WalletInfo.external(
+ id: "connection_test",
+ name: "connection_test",
+ type: WalletType.bitcoin,
+ isRecovery: false,
+ restoreHeight: 0,
+ date: DateTime(2026),
+ dirPath: "",
+ path: "",
+ address: "",
+ );
+ return ElectrumWallet(
+ password: "",
+ walletInfo: walletInfo,
+ derivationInfo: DerivationInfo(
+ derivationType: DerivationType.bip39,
+ derivationPath: "m/84'/0'/0'",
+ ),
+ unspentCoinsInfo: _NoUnspentsBox(),
+ network: BitcoinNetwork.mainnet,
+ encryptionFileUtils: encryptionFileUtilsFor(false),
+ seedBytes: Uint8List.fromList(List<int>.generate(64, (i) => i)),
+ currency: CryptoCurrency.btc,
+ )..walletAddresses = _Addresses(walletInfo);
+}
+
+Future<void> _waitFor(bool Function() done, Duration max) async {
+ final end = DateTime.now().add(max);
+ while (!done() && DateTime.now().isBefore(end)) {
+ await Future.delayed(const Duration(milliseconds: 100));
+ }
+}
+
+bool _connectedTo(ElectrumWallet wallet, int port) =>
+ wallet.syncStatus is ConnectedSyncStatus &&
+ wallet.electrumClient.isConnected &&
+ wallet.electrumClient.uri?.port == port;
+
+void main() {
+ setUpAll(() async {
+ sqfliteFfiInit();
+ db = await databaseFactoryFfi.openDatabase(inMemoryDatabasePath);
+ await db!.execute(
+ "CREATE TABLE walletInfoAddress "
+ "(walletInfoAddressId INTEGER PRIMARY KEY, walletInfoId INTEGER, type INTEGER, "
+ "address TEXT)",
+ );
+ });
+
+ setUp(() {
+ SharedPreferences.setMockInitialValues({});
+ CakeTor.instance = CakeTorDisabled();
+ });
+
+ test("a node that refuses the connection ends in Lost connection, not Connecting", () async {
+ final wallet = _wallet();
+
+ await wallet.connectToNode(node: _node(await _refusedPort()));
+
+ expect(wallet.syncStatus, isA<LostConnectionSyncStatus>());
+ await wallet.close();
+ });
+
+ test(
+ "after a failed connect, the wallet retries and connects once the node is back",
+ () async {
+ final port = await _refusedPort();
+ final wallet = _wallet();
+ await wallet.connectToNode(node: _node(port));
+
+ final node = await _FakeNode.start(port: port);
+ await _waitFor(() => _connectedTo(wallet, port), const Duration(seconds: 15));
+
+ expect(_connectedTo(wallet, port), isTrue);
+ await wallet.close();
+ await node.close();
+ },
+ timeout: const Timeout(Duration(seconds: 30)),
+ );
+
+ test(
+ "selecting another node while a connect hangs connects to it right away",
+ () async {
+ final accepted = <Socket>[];
+ final stalled = await _silentServer(accepted);
+ final good = await _FakeNode.start();
+ final wallet = _wallet();
+
+ unawaited(wallet.connectToNode(node: _node(stalled.port, useSSL: true)));
+ await _waitFor(() => accepted.isNotEmpty, const Duration(seconds: 3));
+ expect(wallet.syncStatus, isA<ConnectingSyncStatus>());
+
+ await wallet.connectToNode(node: _node(good.port));
+ await _waitFor(() => _connectedTo(wallet, good.port), const Duration(seconds: 8));
+
+ expect(_connectedTo(wallet, good.port), isTrue);
+ await wallet.close();
+ await good.close();
+ await stalled.close();
+ },
+ timeout: const Timeout(Duration(seconds: 30)),
+ );
+
+ test(
+ "selecting the same node again while connecting does not start a second connect",
+ () async {
+ final accepted = <Socket>[];
+ final stalled = await _silentServer(accepted);
+ final wallet = _wallet();
+ final node = _node(stalled.port, useSSL: true);
+
+ unawaited(wallet.connectToNode(node: node));
+ await _waitFor(() => accepted.isNotEmpty, const Duration(seconds: 3));
+ unawaited(wallet.connectToNode(node: node));
+ await Future.delayed(const Duration(seconds: 1));
+
+ expect(accepted, hasLength(1));
+ await wallet.close();
+ await stalled.close();
+ },
+ timeout: const Timeout(Duration(seconds: 30)),
+ );
+
+ test(
+ "turning Tor on while connecting reconnects through Tor",
+ () async {
+ final accepted = <Socket>[];
+ final silent = await _silentServer(accepted);
+ final good = await _FakeNode.start();
+ var torConnects = 0;
+ final tor = await _fakeTor(good.port, onConnect: () => torConnects++);
+ final wallet = _wallet();
+ final node = _node(silent.port);
+
+ // Plain TCP to a server that never answers: the wallet stays on Connecting.
+ await wallet.connectToNode(node: node);
+ expect(wallet.syncStatus, isA<ConnectingSyncStatus>());
+
+ CakeTor.instance = CakeTorSocks(tor.port);
+ await wallet.connectToNode(node: node);
+
+ expect(torConnects, 1);
+ await _waitFor(() => wallet.syncStatus is ConnectedSyncStatus, const Duration(seconds: 8));
+ expect(wallet.syncStatus, isA<ConnectedSyncStatus>());
+ await wallet.close();
+ await tor.close();
+ await good.close();
+ await silent.close();
+ },
+ timeout: const Timeout(Duration(seconds: 30)),
+ );
+
+ test("app resume with an unreachable node does not start a sync", () async {
+ final wallet = _wallet();
+ await wallet.connectToNode(node: _node(await _refusedPort()));
+ final statuses = <SyncStatus>[];
+ final dispose = reaction((_) => wallet.syncStatus, statuses.add);
+
+ await wallet.checkSocketHealth();
+
+ dispose();
+ expect(statuses.whereType<SyncronizingSyncStatus>(), isEmpty);
+ expect(wallet.syncStatus, isA<LostConnectionSyncStatus>());
+ await wallet.close();
+ });
+
+ test(
+ "app resume on an unresponsive session re-subscribes the addresses",
+ () async {
+ final node = await _FakeNode.start();
+ final wallet = _wallet();
+ await wallet.connectToNode(node: _node(node.port));
+ await _waitFor(() => _connectedTo(wallet, node.port), const Duration(seconds: 8));
+ await wallet.subscribeForUpdates();
+ await Future.delayed(const Duration(milliseconds: 300));
+ final firstSession = node.subscribes;
+ expect(firstSession, greaterThanOrEqualTo(_addressCount));
+
+ // The fake answers server.version with null, which the health check treats as a dead
+ // session: it reconnects and starts a sync.
+ unawaited(wallet.checkSocketHealth());
+ await _waitFor(() => node.subscribes == 2 * firstSession, const Duration(seconds: 8));
+
+ expect(node.subscribes, 2 * firstSession);
+ await wallet.close();
+ await node.close();
+ },
+ timeout: const Timeout(Duration(seconds: 30)),
+ );
+
+ test(
+ "a closed wallet does not reconnect on its own",
+ () async {
+ final port = await _refusedPort();
+ final wallet = _wallet();
+ await wallet.connectToNode(node: _node(port)); // fails, so a retry is scheduled
+ await wallet.close();
+
+ final node = await _FakeNode.start(port: port);
+ await Future.delayed(const Duration(seconds: 7)); // past the 5 s retry
+
+ expect(wallet.electrumClient.isConnected, isFalse);
+ await node.close();
+ },
+ timeout: const Timeout(Duration(seconds: 30)),
+ );
+
+ test(
+ "closing a wallet while it syncs does not reconnect it",
+ () async {
+ final node = await _FakeNode.start();
+ final wallet = _wallet();
+ await wallet.connectToNode(node: _node(node.port));
+ await _waitFor(() => _connectedTo(wallet, node.port), const Duration(seconds: 8));
+
+ unawaited(wallet.startSync());
+ await Future.delayed(const Duration(milliseconds: 200));
+ await wallet.close();
+ // The sync still running against the closed client fails on its own.
+ await _waitFor(
+ () => wallet.syncStatus is NotConnectedSyncStatus,
+ const Duration(seconds: 20),
+ );
+ expect(wallet.syncStatus, isA<NotConnectedSyncStatus>());
+ await Future.delayed(const Duration(seconds: 7)); // past the 5 s retry
+
+ expect(wallet.electrumClient.isConnected, isFalse);
+ await node.close();
+ },
+ timeout: const Timeout(Duration(seconds: 60)),
+ );
+
+ test(
+ "switching between two working nodes subscribes the addresses on the new node",
+ () async {
+ final a = await _FakeNode.start();
+ final b = await _FakeNode.start();
+ final wallet = _wallet();
+
+ await wallet.connectToNode(node: _node(a.port));
+ await _waitFor(() => _connectedTo(wallet, a.port), const Duration(seconds: 8));
+ await wallet.subscribeForUpdates(); // what startSync does once connected
+ await Future.delayed(const Duration(milliseconds: 300));
+ expect(a.subscribes, greaterThanOrEqualTo(_addressCount));
+
+ await wallet.connectToNode(node: _node(b.port));
+ await _waitFor(() => _connectedTo(wallet, b.port), const Duration(seconds: 8));
+ await wallet.subscribeForUpdates();
+ await Future.delayed(const Duration(milliseconds: 300));
+
+ expect(b.subscribes, a.subscribes);
+ await wallet.close();
+ await a.close();
+ await b.close();
+ },
+ timeout: const Timeout(Duration(seconds: 30)),
+ );
+}
### cw_core/lib/utils/proxy_socket/abstract.dart
@@ -16,28 +16,68 @@ class ProxyAddress {
}
abstract class ProxySocket {
+ // [connectionTimeout] only covers DNS + TCP; these bound the whole connect, including the SOCKS
+ // and TLS handshakes, which otherwise can wait forever. Tor needs time to build a circuit.
+ static const clearnetConnectDeadline = Duration(seconds: 20);
+ static const torConnectDeadline = Duration(seconds: 60);
+
static Future<ProxySocket> connect(bool sslEnabled, ProxyAddress address,
- {Duration? connectionTimeout}) async {
+ {Duration? connectionTimeout}) {
if (CakeTor.instance!.started) {
- var socksSocket = await SOCKSSocket.create(
- proxyHost: InternetAddress.loopbackIPv4.address,
- proxyPort: CakeTor.instance!.port,
- sslEnabled: sslEnabled,
+ SOCKSSocket? socksSocket;
+ Future<ProxySocket> open() async {
+ final socket = socksSocket = await SOCKSSocket.create(
+ proxyHost: InternetAddress.loopbackIPv4.address,
+ proxyPort: CakeTor.instance!.port,
+ sslEnabled: sslEnabled,
+ );
+ try {
+ await socket.connect();
+ await socket.connectTo(address.host, address.port);
+ } catch (_) {
+ // On a failure reply the library leaves its connection to Tor open.
+ unawaited(socket.close().catchError((_) {}));
+ rethrow;
+ }
+ return ProxySocketSocks(socket);
+ }
+
+ // Closing the SOCKS socket also fails a handshake that is still waiting on Tor.
+ return _withDeadline(
+ open(),
+ torConnectDeadline,
+ onTimeout: () => unawaited(socksSocket?.close().catchError((_) {})),
);
- await socksSocket.connect();
- await socksSocket.connectTo(address.host, address.port);
- return ProxySocketSocks(socksSocket);
}
if (sslEnabled == false) {
- return ProxySocketInsecure(
- await Socket.connect(address.host, address.port, timeout: connectionTimeout));
+ return _withDeadline(
+ Socket.connect(address.host, address.port, timeout: connectionTimeout)
+ .then(ProxySocketInsecure.new),
+ clearnetConnectDeadline,
+ );
} else {
- return ProxySocketSecure(await SecureSocket.connect(
- address.host,
- address.port,
- timeout: connectionTimeout,
- onBadCertificate: (_) => true,
- ));
+ return _withDeadline(
+ SecureSocket.connect(
+ address.host,
+ address.port,
+ timeout: connectionTimeout,
+ onBadCertificate: (_) => true,
+ ).then(ProxySocketSecure.new),
+ clearnetConnectDeadline,
+ );
+ }
+ }
+
+ /// Fails with a [TimeoutException] once [deadline] passes; a socket that still connects after
+ /// that is destroyed instead of leaking.
+ static Future<ProxySocket> _withDeadline(Future<ProxySocket> pending, Duration deadline,
+ {void Function()? onTimeout}) async {
+ try {
+ return await pending.timeout(deadline);
+ } on TimeoutException {
+ onTimeout?.call();
+ unawaited(pending.then((socket) => socket.destroy(), onError: (_) {}));
+ rethrow;
}
}
Why this scored 50/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.