Merge branch 'staging' into repro-dnix-packages
What changed, and why it matters
This is a large merge commit that rewrites how the wallet connects to Electrum servers. The main security-relevant changes are: each wallet now owns its own Electrum connection instead of sharing one global client; the app learns to remember a specific TLS certificate for each node and will only trust that certificate for that exact host/port/SSL combination; and there are fixes for connection leaks during cancelled wallet restores. The commit also adds many tests for failover, certificate pinning, and Tor routing. It looks like a defensive hardening patch rather than a fix for a single known exploit.
Review the new certificate pinning logic for correct parsing and comparison, ensure the DrainingElectrumClient drain cannot be abused to keep a revoked connection alive indefinitely, and run the new test suite. Consider whether the old shared ClientManager removal fully eliminates any remaining references elsewhere in the codebase.
Security signals we found
Per-wallet Electrum connection ownership replaces shared singleton, reducing cross-wallet state contamination
Trusted TLS certificate pinning per node (host/port/SSL) added
Certificate approval UI with SHA-256 fingerprint display and forget action
Connection draining for in-flight requests before close
Failover logic now validates endpoint and certificate match before reusing a connection
Cancelled/failed wallet restores now close their Electrum adapter to prevent connection leaks
NotificationsService reuses wallet client instead of creating a parallel connection
Extensive new test suite for TLS, failover, Tor, and request deadlines
Evidence from the diff
The commit removes the shared ClientManager singleton and gives each ElectrumXClient its own ManagedElectrumClient/ManagedFiroElectrumClient connection with a DrainingElectrumClient mixin that lets in-flight requests finish before closing. It adds per-method request timeouts (ElectrumRequestTimeouts), per-node trusted certificate pinning (trustedCertificatePem), and certificate approval UI flows. NodeModel and Hive serialization are extended with trustedCertificatePem. NodeService gets saveEdit/saveTrustedCertificate/forgetTrustedCertificate helpers that bind approvals to endpoint identity. NotificationsService now reuses the wallet’s own ElectrumXClient instead of opening a separate one. Restore flows close the temporary Electrum client if the restore is cancelled or fails. There are extensive new tests covering TLS pinning, failover, Tor gating, and request deadlines.
Changed components
lib/electrumx_rpc/electrumx_client.dartlib/electrumx_rpc/draining_electrum_client.dartlib/electrumx_rpc/electrum_request_timeouts.dartlib/models/node_model.dartlib/models/node_form_data.dartlib/services/node_service.dartlib/services/notifications_service.dartlib/services/wallets.dartlib/utilities/connection_check/electrum_connection_check.dartlib/utilities/tls_certificate.dartlib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dartlib/pages/add_wallet_views/restore_wallet_view/restore_view_only_wallet_view.dartlib/pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dartlib/pages/settings_views/global_settings_view/manage_nodes_views/node_details_view.dartInspect captured patch +7700 / −1645
### lib/electrumx_rpc/client_manager.dart
@@ -1,142 +0,0 @@
-import 'dart:async';
-
-import 'package:electrum_adapter/electrum_adapter.dart';
-
-import '../utilities/logger.dart';
-import '../utilities/prefs.dart';
-import '../utilities/tor_plain_net_option_enum.dart';
-import '../wallets/crypto_currency/crypto_currency.dart';
-
-class ClientManager {
- ClientManager._();
- static final ClientManager sharedInstance = ClientManager._();
-
- final Map<String, ElectrumClient> _map = {};
- final Map<String, TorPlainNetworkOption> _mapNet = {};
- final Map<String, int> _heights = {};
- final Map<String, StreamSubscription<BlockHeader>> _subscriptions = {};
- final Map<String, Completer<int>> _heightCompleters = {};
-
- String _keyHelper(CryptoCurrency cryptoCurrency) {
- return "${cryptoCurrency.runtimeType}_${cryptoCurrency.network.name}";
- }
-
- final Finalizer<ClientManager> _finalizer = Finalizer((manager) async {
- await manager._kill();
- });
-
- ElectrumClient? getClient({
- required CryptoCurrency cryptoCurrency,
- required TorPlainNetworkOption netType,
- }) {
- final _key = _keyHelper(cryptoCurrency);
-
- if (netType == _mapNet[_key]) {
- return _map[_key];
- } else {
- return null;
- }
- }
-
- Future<void> addClient(
- ElectrumClient client, {
- required CryptoCurrency cryptoCurrency,
- required TorPlainNetworkOption netType,
- }) async {
- final key = _keyHelper(cryptoCurrency);
- if (_map[key] != null) {
- if (_mapNet[key] == netType) {
- throw Exception(
- "ElectrumX Client for $key and $netType already exists.",
- );
- }
-
- await remove(cryptoCurrency: cryptoCurrency);
-
- _map[key] = client;
- _mapNet[key] = netType;
- } else {
- _map[key] = client;
- _mapNet[key] = netType;
- }
-
- _heightCompleters[key] = Completer<int>();
- _subscriptions[key] = client.subscribeHeaders().listen(
- (event) {
- _heights[key] = event.height;
-
- if (!_heightCompleters[key]!.isCompleted) {
- _heightCompleters[key]!.complete(event.height);
- }
- },
- onError: (Object err, StackTrace s) => Logging.instance.e(
- "ClientManager listen",
- error: err,
- stackTrace: s,
- ),
- );
- }
-
- Future<int> getChainHeightFor(CryptoCurrency cryptoCurrency) async {
- final key = _keyHelper(cryptoCurrency);
-
- if (_map[key] == null) {
- throw Exception(
- "No managed ElectrumClient for $key found.",
- );
- }
- if (_heightCompleters[key] == null) {
- throw Exception(
- "No managed _heightCompleters for $key found.",
- );
- }
-
- if (Prefs.instance.useTor) {
- if (_mapNet[key]! == TorPlainNetworkOption.clear) {
- throw Exception(
- "Non-TOR only client for $key found.",
- );
- }
- } else {
- if (_mapNet[key]! == TorPlainNetworkOption.tor) {
- throw Exception(
- "TOR only client for $key found.",
- );
- }
- }
-
- return _heights[key] ?? await _heightCompleters[key]!.future;
- }
-
- Future<(ElectrumClient?, TorPlainNetworkOption?)> remove({
- required CryptoCurrency cryptoCurrency,
- }) async {
- final key = _keyHelper(cryptoCurrency);
- await _subscriptions[key]?.cancel();
- _subscriptions.remove(key);
- _heights.remove(key);
- _heightCompleters.remove(key);
-
- return (_map.remove(key), _mapNet.remove(key));
- }
-
- Future<void> closeAll() async {
- await _kill();
- _finalizer.detach(this);
- }
-
- Future<void> _kill() async {
- for (final sub in _subscriptions.values) {
- await sub.cancel();
- }
- for (final client in _map.values) {
- await client.close();
- }
-
- _heightCompleters.clear();
- _heights.clear();
- _subscriptions.clear();
- _mapNet.clear();
- _map.clear();
- }
-}
### lib/electrumx_rpc/draining_electrum_client.dart
@@ -0,0 +1,71 @@
+import 'dart:async';
+
+import 'package:electrum_adapter/electrum_adapter.dart';
+
+/// A superseded connection finishes its outstanding RPCs before closing.
+/// Every adapter helper, including subscription setup, uses this request hook.
+/// Explicit close still cancels immediately for revocation and shutdown.
+mixin DrainingElectrumClient on ElectrumClient {
+ int _requests = 0;
+ bool _retiring = false;
+
+ Future<void> retire() async {
+ _retiring = true;
+ if (_requests == 0) await close();
+ }
+
+ @override
+ Future<dynamic> requestWithTimeout(
+ String method, {
+ dynamic parameters,
+ Duration? timeout,
+ }) {
+ _requests++;
+ try {
+ final pending = super.requestWithTimeout(
+ method,
+ parameters: parameters,
+ timeout: timeout,
+ );
+ // Keep the original future: subscription setup relies on the adapter's
+ // synchronous completion ordering relative to following notifications.
+ unawaited(
+ pending.then<void>(
+ (_) => _requestFinished(),
+ onError: (Object _) => _requestFinished(),
+ ),
+ );
+ return pending;
+ } catch (_) {
+ _requestFinished();
+ rethrow;
+ }
+ }
+
+ void _requestFinished() {
+ if (--_requests == 0 && _retiring) close().ignore();
+ }
+}
+
+class ManagedElectrumClient extends ElectrumClient with DrainingElectrumClient {
+ ManagedElectrumClient(
+ super.channel,
+ super.host,
+ super.port,
+ super.useSSL,
+ super.proxyInfo, {
+ required super.requestTimeout,
+ });
+}
+
+class ManagedFiroElectrumClient extends FiroElectrumClient
+ with DrainingElectrumClient {
+ ManagedFiroElectrumClient(
+ super.channel,
+ super.host,
+ super.port,
+ super.useSSL,
+ super.proxyInfo, {
+ required super.requestTimeout,
+ });
+}
### lib/electrumx_rpc/electrum_request_timeouts.dart
@@ -0,0 +1,34 @@
+/// Response limits shared by individual and batched Electrum requests.
+class ElectrumRequestTimeouts {
+ const ElectrumRequestTimeouts({
+ this.standard = const Duration(seconds: 60),
+ this.history = const Duration(minutes: 5),
+ this.transactionBatch = const Duration(minutes: 5),
+ this.firoSet = const Duration(hours: 3),
+ this.broadcast = const Duration(minutes: 5),
+ });
+
+ final Duration standard;
+ final Duration history;
+
+ /// Deadline for the combined response to a verbose transaction batch.
+ final Duration transactionBatch;
+
+ /// Deadline for a Firo set download. The full Spark used-tag set alone is
+ /// tens of megabytes and arrives as one response, so this is long enough
+ /// for very slow connections to finish it.
+ final Duration firoSet;
+ final Duration broadcast;
+
+ Duration forMethod(String method) => switch (method) {
+ 'blockchain.scripthash.get_history' => history,
+ 'blockchain.transaction.broadcast' => broadcast,
+ 'lelantus.getanonymityset' ||
+ 'lelantus.getusedcoinserials' ||
+ 'spark.getusedcoinstags' ||
+ 'spark.getusedcoinstagstxhashes' ||
+ 'spark.getsparkanonymityset' ||
+ 'spark.getsparkanonymitysetsector' => firoSet,
+ _ => standard,
+ };
+}
### lib/electrumx_rpc/electrumx_client.dart
@@ -13,12 +13,14 @@ import 'dart:io';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:decimal/decimal.dart';
+import 'package:electrum_adapter/client/subscribing_client.dart'
+ show registerSubscribable;
import 'package:electrum_adapter/electrum_adapter.dart' as electrum_adapter;
import 'package:electrum_adapter/electrum_adapter.dart';
import 'package:electrum_adapter/methods/specific/firo.dart';
import 'package:event_bus/event_bus.dart';
+import 'package:meta/meta.dart' show protected;
import 'package:mutex/mutex.dart';
-import 'package:stream_channel/stream_channel.dart';
import '../app_config.dart';
import '../exceptions/electrumx/no_such_transaction.dart';
@@ -31,10 +33,12 @@ import '../utilities/amount/amount.dart';
import '../utilities/extensions/impl/string.dart';
import '../utilities/logger.dart';
import '../utilities/prefs.dart';
+import '../utilities/tls_certificate.dart';
import '../utilities/tor_plain_net_option_enum.dart';
import '../wallets/crypto_currency/crypto_currency.dart';
import '../wallets/crypto_currency/interfaces/electrumx_currency_interface.dart';
-import 'client_manager.dart';
+import 'draining_electrum_client.dart';
+import 'electrum_request_timeouts.dart';
class WifiOnlyException implements Exception {}
@@ -51,6 +55,7 @@ class ElectrumXNode {
required this.useSSL,
required this.torEnabled,
required this.clearnetEnabled,
+ this.trustedCertificatePem,
});
final String address;
final int port;
@@ -59,6 +64,7 @@ class ElectrumXNode {
final bool useSSL;
final bool torEnabled;
final bool clearnetEnabled;
+ final String? trustedCertificatePem;
factory ElectrumXNode.from(ElectrumXNode node) {
return ElectrumXNode(
@@ -69,6 +75,7 @@ class ElectrumXNode {
useSSL: node.useSSL,
torEnabled: node.torEnabled,
clearnetEnabled: node.clearnetEnabled,
+ trustedCertificatePem: node.trustedCertificatePem,
);
}
@@ -79,6 +86,8 @@ class ElectrumXNode {
}
class ElectrumXClient {
+ final ElectrumRequestTimeouts requestTimeouts;
+
final CryptoCurrency cryptoCurrency;
final TorPlainNetworkOption netType;
@@ -90,12 +99,23 @@ class ElectrumXClient {
bool get useSSL => _useSSL;
late bool _useSSL;
+ final String? trustedCertificatePem;
+
+ bool _closed = false;
+ int _connectionGeneration = 0;
+
+ /// This client's own connection. No other [ElectrumXClient] uses it.
+ ElectrumClient? _adapter;
- // StreamChannel<dynamic>? get electrumAdapterChannel => _electrumAdapterChannel;
- StreamChannel<dynamic>? _electrumAdapterChannel;
+ /// The certificate [_adapter] was opened with; null for platform roots.
+ String? _adapterCertificate;
+ ElectrumClient? _pendingClient;
- ElectrumClient? getElectrumAdapter() => ClientManager.sharedInstance
- .getClient(cryptoCurrency: cryptoCurrency, netType: netType);
+ /// This client's superseded connections that are still finishing requests
+ /// it sent before a failover.
+ final _retiring = <ElectrumClient>{};
+
+ ElectrumClient? getElectrumAdapter() => _closed ? null : _adapter;
late Prefs _prefs;
late TorService _torService;
@@ -105,17 +125,10 @@ class ElectrumXClient {
final Duration connectionTimeoutForSpecialCaseJsonRPCClients;
- // add finalizer to cancel stream subscription when all references to an
- // instance of ElectrumX becomes inaccessible
- static final Finalizer<ElectrumXClient> _finalizer = Finalizer((p0) {
- p0._torPreferenceListener?.cancel();
- p0._torStatusListener?.cancel();
- });
StreamSubscription<TorPreferenceChangedEvent>? _torPreferenceListener;
StreamSubscription<TorConnectionStatusChangedEvent>? _torStatusListener;
- final Mutex _torConnectingLock = Mutex();
- bool _requireMutex = false;
+ Completer<void>? _torConnectionGate;
final _adapterMutex = Mutex();
@@ -132,7 +145,20 @@ class ElectrumXClient {
),
TorService? torService,
EventBus? globalEventBusForTesting,
+ this.trustedCertificatePem,
+ this.requestTimeouts = const ElectrumRequestTimeouts(),
}) {
+ for (final limit in [
+ requestTimeouts.standard,
+ requestTimeouts.history,
+ requestTimeouts.transactionBatch,
+ requestTimeouts.firoSet,
+ requestTimeouts.broadcast,
+ ]) {
+ if (limit <= Duration.zero) {
+ throw ArgumentError.value(limit, 'requestTimeouts', 'Must be positive');
+ }
+ }
_prefs = prefs;
_torService = torService ?? TorService.sharedInstance;
_host = host;
@@ -145,19 +171,16 @@ class ElectrumXClient {
// Listen for tor status changes.
_torStatusListener = bus.on<TorConnectionStatusChangedEvent>().listen((
event,
- ) async {
+ ) {
+ if (_closed) return;
switch (event.newStatus) {
case TorConnectionStatus.connecting:
- await _torConnectingLock.acquire();
- _requireMutex = true;
+ _torConnectionGate ??= Completer<void>();
break;
case TorConnectionStatus.connected:
case TorConnectionStatus.disconnected:
- if (_torConnectingLock.isLocked) {
- _torConnectingLock.release();
- }
- _requireMutex = false;
+ _releaseTorWaiters();
break;
}
});
@@ -166,21 +189,7 @@ class ElectrumXClient {
_torPreferenceListener = bus.on<TorPreferenceChangedEvent>().listen((
event,
) async {
- // not sure if we need to do anything specific here
- // switch (event.status) {
- // case TorStatus.enabled:
- // case TorStatus.disabled:
- // }
-
- // setting to null should force the creation of a new json rpc client
- // on the next request sent through this electrumx instance
- _electrumAdapterChannel = null;
- await (await ClientManager.sharedInstance.remove(
- cryptoCurrency: cryptoCurrency,
- )).$1?.close();
-
- // Also close any chain height services that are currently open.
- // await ChainHeightServiceManager.dispose();
+ if (!_closed) await _resetAdapter();
});
}
@@ -191,11 +200,14 @@ class ElectrumXClient {
required CryptoCurrency cryptoCurrency,
TorService? torService,
EventBus? globalEventBusForTesting,
+ ElectrumRequestTimeouts requestTimeouts = const ElectrumRequestTimeouts(),
}) {
return ElectrumXClient(
host: node.address,
port: node.port,
useSSL: node.useSSL,
+ trustedCertificatePem: node.trustedCertificatePem,
+ requestTimeouts: requestTimeouts,
prefs: prefs,
torService: torService,
failovers: failovers,
@@ -217,144 +229,246 @@ class ElectrumXClient {
return true;
}
+ /// Lets the current connection finish this client's requests, then close.
+ /// Unlike [closeAdapter], the client stays usable: the next request opens
+ /// a new connection.
+ Future<void> disconnect() => _adapterMutex.protect(() async {
+ final current = _adapter;
+ _adapter = null;
+ _adapterCertificate = null;
+ if (current != null) await _retire(current);
+ });
+
Future<void> closeAdapter() async {
- await getElectrumAdapter()?.close();
+ _closed = true;
+ _releaseTorWaiters();
+ await _torPreferenceListener?.cancel();
+ await _torStatusListener?.cancel();
+ await _resetAdapter();
}
- Future<void> checkElectrumAdapter() async {
- 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 {
- // 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 the current ElectrumAdapterClient is closed, create a new one.
- if (getElectrumAdapter() != null && getElectrumAdapter()!.peer.isClosed) {
- _electrumAdapterChannel = null;
- await ClientManager.sharedInstance.remove(
- cryptoCurrency: cryptoCurrency,
- );
- }
+ void _releaseTorWaiters() {
+ final gate = _torConnectionGate;
+ _torConnectionGate = null;
+ gate?.complete();
+ }
- final String useHost;
- final int usePort;
- final bool useUseSSL;
+ Future<void> _waitForTor() async {
+ // Tor readiness is a signal, not a lock held by an individual request.
+ // Adapter setup remains serialized by _adapterMutex.
+ while (_torConnectionGate != null) {
+ await _torConnectionGate!.future;
+ }
+ }
- 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;
- }
+ /// Requests this client already sent on a superseded connection still
+ /// finish; the connection closes after the last one. Their own deadlines
+ /// bound the drain.
+ Future<void> _retire(ElectrumClient client) async {
+ if (client is! DrainingElectrumClient) return client.close();
+ _retiring.add(client);
+ unawaited(
+ client.done.then<void>(
+ (_) => _retiring.remove(client),
+ onError: (Object _) {
+ _retiring.remove(client);
+ },
+ ),
+ );
+ await client.retire();
+ }
- _electrumAdapterChannel ??= await electrum_adapter.connect(
- useHost,
- port: usePort,
- connectionTimeout: connectionTimeoutForSpecialCaseJsonRPCClients,
- aliveTimerDuration: connectionTimeoutForSpecialCaseJsonRPCClients,
- acceptUnverified: false,
- useSSL: useUseSSL,
- proxyInfo: proxyInfo,
- );
+ /// Closes the current, pending and draining connections at once, for
+ /// closing the owner and for Tor preference changes.
+ Future<void> _resetAdapter() async {
+ _connectionGeneration++;
+ final clients = <ElectrumClient>{
+ if (_pendingClient != null) _pendingClient!,
+ if (_adapter != null) _adapter!,
+ ..._retiring,
+ };
+ _pendingClient = _adapter = null;
+ _adapterCertificate = null;
+ _retiring.clear();
+ await Future.wait(clients.map((client) => client.close()));
+ }
- 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,
+ /// Opens one connection for [checkElectrumAdapter]. Tests override this to
+ /// supply an in-memory transport; the setup and failover logic is shared.
+ @protected
+ Future<ElectrumClient> openConnection({
+ required String host,
+ required int port,
+ required bool useSSL,
+ required ({InternetAddress host, int port})? proxy,
+ required bool Function(X509Certificate)? onBadCertificate,
+ }) async {
+ final channel = await electrum_adapter.connect(
+ host,
+ port: port,
+ useSSL: useSSL,
+ proxyInfo: proxy,
+ connectionTimeout: connectionTimeoutForSpecialCaseJsonRPCClients,
+ connectionDeadline: connectionTimeoutForSpecialCaseJsonRPCClients,
+ acceptUnverified: false,
+ onBadCertificate: onBadCertificate,
+ );
+ return cryptoCurrency is Firo
+ ? ManagedFiroElectrumClient(
+ channel,
+ host,
+ port,
+ useSSL,
+ proxy,
+ requestTimeout: requestTimeouts.standard,
+ )
+ : ManagedElectrumClient(
+ channel,
+ host,
+ port,
+ useSSL,
+ proxy,
+ requestTimeout: requestTimeouts.standard,
);
- }
+ }
+
+ Future<void> checkElectrumAdapter() => _adapterMutex.protect(() async {
+ final generation = _connectionGeneration;
+ void ensureCurrent() {
+ if (_closed || generation != _connectionGeneration) {
+ throw StateError('Electrum client changed');
+ }
+ }
- await newClient.request('server.version');
+ ensureCurrent();
+ ({InternetAddress host, int port})? proxy;
+ if (AppConfig.hasFeature(AppFeature.tor) && _prefs.useTor) {
+ if (_torService.status == TorConnectionStatus.connected) {
+ proxy = _torService.getProxyInfo();
+ } else if (_prefs.torKillSwitch) {
+ throw StateError('Tor is not connected');
+ }
+ }
+ // Only this client's own nodes are ever connected, and they cannot change
+ // for its lifetime. A connection therefore needs to be checked against
+ // the selected endpoint and approval, and against the current Tor route.
+ bool sameRoute(ElectrumClient client) =>
+ client.proxyInfo?.host.address == proxy?.host.address &&
+ client.proxyInfo?.port == proxy?.port;
+ // Draining connections still obey Tor route changes.
+ final offRoute = _retiring.where((client) => !sameRoute(client)).toList();
+ _retiring.removeAll(offRoute);
+ await Future.wait(offRoute.map((client) => client.close()));
+ ensureCurrent();
+ // Setup fails before the caller RPC is sent. Try each remaining configured
+ // node once, including for callers that use the adapter directly.
+ for (var index = currentFailoverIndex; index < _failovers.length; index++) {
+ ensureCurrent();
+ currentFailoverIndex = index;
+ final failover = index == -1 ? null : _failovers[index];
+ final useHost = failover?.address ?? host;
+ final usePort = failover?.port ?? port;
+ final ssl = failover?.useSSL ?? useSSL;
+ final pem = ssl
+ ? (failover == null
+ ? trustedCertificatePem
+ : failover.trustedCertificatePem)
+ : null;
+ final existing = _adapter;
+ // At the primary index any open connection of this client is kept: a
+ // successful failover request resets the index, and later requests stay
+ // on the working failover. A failover index selects that endpoint and
+ // its own approval.
+ if (existing != null &&
+ !existing.peer.isClosed &&
+ sameRoute(existing) &&
+ (failover == null ||
+ (existing.host == useHost &&
+ existing.port == usePort &&
+ existing.useSSL == ssl &&
+ _adapterCertificate == pem))) {
+ return;
+ }
- await ClientManager.sharedInstance.addClient(
- newClient,
- cryptoCurrency: cryptoCurrency,
- netType: netType,
+ // Invalid saved approvals are a local configuration error. They must not
+ // be mistaken for a failed network attempt or bypassed by failover.
+ // Check before retiring the current connection: an attempt that cannot
+ // connect must not take this client's working connection down with it.
+ final bool Function(X509Certificate)? certificateCheck;
+ try {
+ certificateCheck = trustedCertificateCheck(pem);
+ } on FormatException {
+ // Fail this attempt, but let the next one retry a recovered primary.
+ currentFailoverIndex = -1;
+ rethrow;
+ }
+ if (existing != null) {
+ _adapter = null;
+ _adapterCertificate = null;
+ // Requests already sent on it finish, unless the Tor route changed.
+ await (sameRoute(existing) ? _retire(existing) : existing.close());
+ ensureCurrent();
+ }
+ ElectrumClient? candidate;
+ try {
+ candidate = await openConnection(
+ host: useHost,
+ port: usePort,
+ useSSL: ssl,
+ proxy: proxy,
+ onBadCertificate: certificateCheck,
+ );
+ _pendingClient = candidate;
+ ensureCurrent();
+ await candidate.requestWithTimeout(
+ 'server.version',
+ timeout: connectionTimeoutForSpecialCaseJsonRPCClients,
);
+ ensureCurrent();
+ _adapter = candidate;
+ _adapterCertificate = pem;
+ } catch (error) {
+ // Closing the owner or changing its network settings cancels the whole
+ // operation. Programming errors are not node faults; StateError can
+ // instead mean the negotiating peer has closed.
+ ensureCurrent();
+ if (error is Error && error is! StateError) rethrow;
+ if (index == _failovers.length - 1) {
+ currentFailoverIndex = -1;
+ rethrow;
+ }
+ } finally {
+ if (identical(_pendingClient, candidate)) _pendingClient = null;
+ if (candidate != null && !identical(_adapter, candidate)) {
+ await candidate.close();
+ }
}
- });
- }
+ ensureCurrent();
+ if (_adapter != null) return;
+ }
+ });
/// Send raw rpc command
Future<dynamic> request({
required String command,
List<dynamic> args = const [],
String? requestID,
int retries = 2,
- Duration requestTimeout = const Duration(seconds: 60),
+ Duration? requestTimeout,
}) async {
if (!(await _allow())) {
throw WifiOnlyException();
}
- if (_requireMutex) {
- await _torConnectingLock.protect(
- () async => await checkElectrumAdapter(),
- );
- } else {
- await checkElectrumAdapter();
- }
+ await _waitForTor();
+ await checkElectrumAdapter();
try {
- final response = await getElectrumAdapter()!.request(command, args);
+ final response = await _adapter!.requestWithTimeout(
+ command,
+ parameters: args,
+ timeout: requestTimeout ?? requestTimeouts.forMethod(command),
+ );
if (response is Map &&
response.keys.contains("error") &&
@@ -431,26 +545,28 @@ class ElectrumXClient {
Future<List<dynamic>> batchRequest({
required String command,
required List<dynamic> args,
- Duration requestTimeout = const Duration(seconds: 60),
+ Duration? requestTimeout,
int retries = 2,
}) async {
+ if (args.isEmpty) return [];
if (!(await _allow())) {
throw WifiOnlyException();
}
- if (_requireMutex) {
- await _torConnectingLock.protect(
- () async => await checkElectrumAdapter(),
- );
- } else {
- await checkElectrumAdapter();
- }
+ await _waitForTor();
+ await checkElectrumAdapter();
try {
final futures = <Future<dynamic>>[];
- getElectrumAdapter()!.peer.withBatch(() {
+ _adapter!.peer.withBatch(() {
for (final arg in args) {
- futures.add(getElectrumAdapter()!.request(command, arg));
+ futures.add(
+ _adapter!.requestWithTimeout(
+ command,
+ parameters: arg,
+ timeout: requestTimeout ?? requestTimeouts.forMethod(command),
+ ),
+ );
}
});
final response = await Future.wait(futures);
@@ -567,6 +683,10 @@ class ElectrumXClient {
/// "hex": "00000020890208a0ae3a3892aa047c5468725846577cfcd9b512b50000000000000000005dc2b02f2d297a9064ee103036c14d678f9afc7e3d9409cf53fd58b82e938e8ecbeca05a2d2103188ce804c4"
/// }
Future<Map<String, dynamic>> getBlockHeadTip({String? requestID}) async {
+ // This request subscribes the connection to new headers. Registering the
+ // method lets the adapter accept those notifications instead of reporting
+ // each one as an unknown method.
+ registerSubscribable('blockchain.headers', 0);
try {
final response = await request(
requestID: requestID,
@@ -614,16 +734,12 @@ class ElectrumXClient {
required String rawTx,
String? requestID,
}) async {
- try {
- final response = await request(
- requestID: requestID,
- command: 'blockchain.transaction.broadcast',
- args: [rawTx],
- );
- return response as String;
- } catch (e) {
- rethrow;
- }
+ final response = await request(
+ requestID: requestID,
+ command: 'blockchain.transaction.broadcast',
+ args: [rawTx],
+ );
+ return response as String;
}
/// Return the confirmed and unconfirmed balances for the scripthash of a given scripthash
@@ -677,7 +793,6 @@ class ElectrumXClient {
final response = await request(
requestID: requestID,
command: 'blockchain.scripthash.get_history',
- requestTimeout: const Duration(minutes: 5),
args: [scripthash],
);
result = response;
@@ -829,9 +944,10 @@ class ElectrumXClient {
}) async {
Logging.instance.d("attempting to fetch blockchain.transaction.get...");
await checkElectrumAdapter();
- final dynamic response = await getElectrumAdapter()!.request(
+ final dynamic response = await _adapter!.requestWithTimeout(
'blockchain.transaction.get',
- [txHash, verbose],
+ parameters: [txHash, verbose],
+ timeout: requestTimeouts.forMethod('blockchain.transaction.get'),
);
Logging.instance.d("Fetching blockchain.transaction.get finished");
@@ -853,6 +969,7 @@ class ElectrumXClient {
final response = await batchRequest(
command: 'blockchain.transaction.get',
args: txHashes.map((e) => [e, true]).toList(),
+ requestTimeout: requestTimeouts.transactionBatch,
);
final List<Map<String, dynamic>> result = [];
for (int i = 0; i < response.length; i++) {
@@ -885,9 +1002,12 @@ class ElectrumXClient {
}) async {
Logging.instance.d("attempting to fetch lelantus.getanonymityset...");
await checkElectrumAdapter();
- final Map<String, dynamic> response =
- await (getElectrumAdapter() as FiroElectrumClient)
- .getLelantusAnonymitySet(groupId: groupId, blockHash: blockhash);
+ final Map<String, dynamic> response = await (_adapter as FiroElectrumClient)
+ .getLelantusAnonymitySet(
+ groupId: groupId,
+ blockHash: blockhash,
+ timeout: requestTimeouts.firoSet,
+ );
Logging.instance.d("Fetching lelantus.getanonymityset finished");
return response;
}
@@ -902,8 +1022,11 @@ class ElectrumXClient {
}) async {
Logging.instance.d("attempting to fetch lelantus.getmintmetadata...");
await checkElectrumAdapter();
- final dynamic response = await (getElectrumAdapter() as FiroElectrumClient)
- .getLelantusMintData(mints: mints);
+ final dynamic response = await _adapter!.requestWithTimeout(
+ 'lelantus.getmintmetadata',
+ parameters: [mints],
+ timeout: requestTimeouts.forMethod('lelantus.getmintmetadata'),
+ );
Logging.instance.d("Fetching lelantus.getmintmetadata finished");
return response;
}
@@ -921,9 +1044,11 @@ class ElectrumXClient {
dynamic response;
while (retryCount > 0 && response is! List) {
- response = await (getElectrumAdapter() as FiroElectrumClient)
- .getLelantusUsedCoinSerials(startNumber: startNumber);
- // TODO add 2 minute timeout.
+ response = await (_adapter as FiroElectrumClient)
+ .getLelantusUsedCoinSerials(
+ startNumber: startNumber,
+ timeout: requestTimeouts.firoSet,
+ );
Logging.instance.d("Fetching lelantus.getusedcoinserials finished");
retryCount--;
@@ -938,8 +1063,10 @@ class ElectrumXClient {
Future<int> getLelantusLatestCoinId({String? requestID}) async {
Logging.instance.d("attempting to fetch lelantus.getlatestcoinid...");
await checkElectrumAdapter();
- final int response = await (getElectrumAdapter() as FiroElectrumClient)
- .getLatestCoinId();
+ final int response = await _adapter!.requestWithTimeout(
+ 'lelantus.getlatestcoinid',
+ timeout: requestTimeouts.forMethod('lelantus.getlatestcoinid'),
+ ) as int;
Logging.instance.d("Fetching lelantus.getlatestcoinid finished");
return response;
}
@@ -968,11 +1095,11 @@ class ElectrumXClient {
final start = DateTime.now();
await checkElectrumAdapter();
final Map<String, dynamic> response =
- await (getElectrumAdapter() as FiroElectrumClient)
- .getSparkAnonymitySet(
- coinGroupId: coinGroupId,
- startBlockHash: startBlockHash,
- );
+ await (_adapter as FiroElectrumClient).getSparkAnonymitySet(
+ coinGroupId: coinGroupId,
+ startBlockHash: startBlockHash,
+ timeout: requestTimeouts.firoSet,
+ );
Logging.instance.d(
"Finished ElectrumXClient.getSparkAnonymitySet(coinGroupId"
"=$coinGroupId, startBlockHash=$startBlockHash). "
@@ -996,7 +1123,7 @@ class ElectrumXClient {
// final start = DateTime.now();
// await _checkElectrumAdapter();
// final Map<String, dynamic> response =
- // await (getElectrumAdapter() as FiroElectrumClient)
+ // await (_adapter as FiroElectrumClient)
// .getUsedCoinsTags(startNumber: startNumber);
// // TODO: Add 2 minute timeout.
// // Why 2 minutes?
@@ -1043,7 +1170,7 @@ class ElectrumXClient {
// );
// await checkElectrumAdapter();
// final List<dynamic> response =
- // await (getElectrumAdapter() as FiroElectrumClient)
+ // await (_adapter as FiroElectrumClient)
// .getSparkMintMetaData(sparkCoinHashes: sparkCoinHashes);
// Logging.instance.log(
// "Fetching spark.getsparkmintmetadata finished",
@@ -1063,8 +1190,10 @@ class ElectrumXClient {
try {
Logging.instance.d("attempting to fetch spark.getsparklatestcoinid...");
await checkElectrumAdapter();
- final int response = await (getElectrumAdapter() as FiroElectrumClient)
- .getSparkLatestCoinId();
+ final int response = await _adapter!.requestWithTimeout(
+ 'spark.getsparklatestcoinid',
+ timeout: requestTimeouts.forMethod('spark.getsparklatestcoinid'),
+ ) as int;
Logging.instance.d("Fetching spark.getsparklatestcoinid finished");
return response;
} catch (e, s) {
@@ -1364,7 +1493,10 @@ class ElectrumXClient {
/// }
Future<Map<String, dynamic>> getFeeRate({String? requestID}) async {
await checkElectrumAdapter();
- return await getElectrumAdapter()!.getFeeRate();
+ return await _adapter!.requestWithTimeout(
+ 'blockchain.getfeerate',
+ timeout: requestTimeouts.forMethod('blockchain.getfeerate'),
+ ) as Map<String, dynamic>;
}
/// Return the estimated transaction fee per kilobyte for a transaction to be
### lib/models/node_form_data.dart
@@ -0,0 +1,81 @@
+import '../utilities/tor_plain_net_option_enum.dart';
+import 'node_model.dart';
+
+class NodeFormData {
+ NodeFormData();
+
+ // The certificate is assigned last so it is bound to the node's endpoint.
+ factory NodeFormData.fromNode(NodeModel node) => NodeFormData()
+ ..name = node.name
+ ..host = node.host
+ ..port = node.port
+ ..useSSL = node.useSSL
+ ..login = node.loginName
+ ..trusted = node.trusted
+ ..isFailover = node.isFailover
+ ..netOption = TorPlainNetworkOption.fromNodeData(
+ node.torEnabled,
+ node.clearnetEnabled,
+ )
+ ..forceNoTor = node.forceNoTor
+ ..isPrimary = node.isPrimary
+ ..apiSecret = node.nodeApiSecret
+ ..trustedCertificatePem = node.trustedCertificatePem
+ ..source = node;
+
+ String? name, host, login, password, apiSecret;
+ int? port;
+ bool? useSSL, isFailover, trusted, forceNoTor, isPrimary;
+ TorPlainNetworkOption? netOption;
+ NodeModel? source;
+ Future<void>? passwordLoad;
+ int certificateRevision = 0;
+
+ // A certificate approval belongs to the endpoint it was reviewed for. It
+ // stays with that endpoint: editing the host and restoring it keeps the
+ // approval, while any other host, port or SSL setting reads as unapproved.
+ String? _approvedPem;
+ String? _approvedHost;
+ int? _approvedPort;
+ bool? _approvedUseSSL;
+ bool _forgotten = false;
+
+ bool get certificateForgotten =>
+ _forgotten &&
+ host == _approvedHost &&
+ port == _approvedPort &&
+ useSSL == _approvedUseSSL;
+
+ void forgetCertificate() {
+ trustedCertificatePem = null;
+ _forgotten = true;
+ }
+
+ String? get trustedCertificatePem =>
+ _approvedPem != null &&
+ host == _approvedHost &&
+ port == _approvedPort &&
+ useSSL == _approvedUseSSL
+ ? _approvedPem
+ : null;
+
+ set trustedCertificatePem(String? value) {
+ certificateRevision++;
+ _forgotten = false;
+ _approvedPem = value;
+ _approvedHost = host;
+ _approvedPort = port;
+ _approvedUseSSL = useSSL;
+ }
+
+ /// Whether the form currently names [node]'s endpoint, the identity a
+ /// trusted certificate is bound to.
+ bool matchesEndpointOf(NodeModel node) =>
+ host == node.host && port == node.port && useSSL == node.useSSL;
+
+ @override
+ String toString() {
+ return "{ name: $name, host: $host, port: $port, useSSL: $useSSL, "
+ "trusted: $trusted, netOption: $netOption, isPrimary: $isPrimary }";
+ }
+}
### lib/models/node_model.dart
@@ -12,6 +12,7 @@ import 'package:hive_ce/hive.dart';
import '../utilities/default_nodes.dart';
import '../utilities/flutter_secure_storage_interface.dart';
+import '../utilities/tls_certificate.dart';
part 'type_adaptors/node_model.g.dart';
@@ -49,6 +50,8 @@ class NodeModel {
final bool isPrimary;
// @HiveField(15)
final String? nodeApiSecret;
+ // @HiveField(16)
+ final String? trustedCertificatePem;
NodeModel({
required this.host,
@@ -67,6 +70,7 @@ class NodeModel {
this.loginName,
this.trusted,
this.nodeApiSecret,
+ this.trustedCertificatePem,
});
factory NodeModel.fromStackBackup(
@@ -97,9 +101,25 @@ class NodeModel {
fallback: legacyPrimaryNodeIds?.contains(id) ?? false,
),
nodeApiSecret: map['nodeApiSecret'] as String?,
+ trustedCertificatePem: _backupCertificatePem(
+ map['trustedCertificatePem'],
+ ),
);
}
+ /// A PEM that cannot be parsed would make every connection to this node
+ /// throw, so a damaged backup value is dropped. The node then uses the
+ /// platform roots until its certificate is reviewed again.
+ static String? _backupCertificatePem(Object? value) {
+ if (value is! String) return null;
+ try {
+ certificateDer(value);
+ return value;
+ } catch (_) {
+ return null;
+ }
+ }
+
static bool _backupBool(Object? value, {required bool fallback}) =>
_nullableBackupBool(value) ?? fallback;
@@ -117,6 +137,14 @@ class NodeModel {
return null;
}
+ /// Whether [host], [port] and [useSSL] name this node's endpoint, the
+ /// identity a trusted certificate is bound to.
+ bool sameEndpoint({
+ required String host,
+ required int port,
+ required bool useSSL,
+ }) => this.host == host && this.port == port && this.useSSL == useSSL;
+
NodeModel copyWith({
String? host,
int? port,
@@ -133,7 +161,14 @@ class NodeModel {
bool? clearnetEnabled,
bool? isPrimary,
String? nodeApiSecret,
+ String? trustedCertificatePem,
+ bool clearTrustedCertificate = false,
}) {
+ final endpointChanged = !sameEndpoint(
+ host: host ?? this.host,
+ port: port ?? this.port,
+ useSSL: useSSL ?? this.useSSL,
+ );
return NodeModel(
host: host ?? this.host,
port: port ?? this.port,
@@ -151,6 +186,10 @@ class NodeModel {
forceNoTor: forceNoTor ?? this.forceNoTor,
isPrimary: isPrimary ?? this.isPrimary,
nodeApiSecret: nodeApiSecret ?? this.nodeApiSecret,
+ trustedCertificatePem: clearTrustedCertificate
+ ? null
+ : trustedCertificatePem ??
+ (endpointChanged ? null : this.trustedCertificatePem),
);
}
@@ -177,6 +216,7 @@ class NodeModel {
map['forceNoTor'] = forceNoTor;
map['isPrimary'] = isPrimary;
map['nodeApiSecret'] = nodeApiSecret;
+ map['trustedCertificatePem'] = trustedCertificatePem;
return map;
}
### lib/models/type_adaptors/node_model.g.dart
@@ -1,4 +1,4 @@
-// GENERATED CODE - DO NOT MODIFY BY HAND
+// Manually maintained Hive adapter. Append fields for backwards compatibility.
part of '../node_model.dart';
@@ -33,13 +33,14 @@ class NodeModelAdapter extends TypeAdapter<NodeModel> {
forceNoTor: fields[13] as bool? ?? false,
isPrimary: fields[14] as bool? ?? false,
nodeApiSecret: fields[15] as String?,
+ trustedCertificatePem: fields[16] as String?,
);
}
@override
void write(BinaryWriter writer, NodeModel obj) {
writer
- ..writeByte(16)
+ ..writeByte(17)
..writeByte(0)
..write(obj.id)
..writeByte(1)
@@ -71,7 +72,9 @@ class NodeModelAdapter extends TypeAdapter<NodeModel> {
..writeByte(14)
..write(obj.isPrimary)
..writeByte(15)
- ..write(obj.nodeApiSecret);
+ ..write(obj.nodeApiSecret)
+ ..writeByte(16)
+ ..write(obj.trustedCertificatePem);
}
@override
### lib/pages/add_wallet_views/restore_wallet_view/restore_view_only_wallet_view.dart
@@ -29,6 +29,7 @@ import '../../../wallets/wallet/impl/mimblewimblecoin_wallet.dart';
import '../../../wallets/wallet/impl/xelis_wallet.dart';
import '../../../wallets/wallet/intermediate/cryptonote_wallet.dart';
import '../../../wallets/wallet/wallet.dart';
+import '../../../wallets/wallet/wallet_mixin_interfaces/electrumx_interface.dart';
import '../../../wallets/wallet/wallet_mixin_interfaces/extended_keys_interface.dart';
import '../../../widgets/custom_buttons/app_bar_icon_button.dart';
import '../../../widgets/desktop/desktop_app_bar.dart';
@@ -120,6 +121,8 @@ class _RestoreViewOnlyWalletViewState
if (!Platform.isLinux && !Util.isDesktop) await WakelockPlus.enable();
+ Wallet? restored;
+ bool added = false;
try {
final info = WalletInfo.createNew(
coin: widget.coin,
@@ -146,6 +149,12 @@ class _RestoreViewOnlyWalletViewState
await ref
.read(pWallets)
.deleteWallet(info, ref.read(secureStoreProvider));
+
+ // Stop the cancelled restore's network work now.
+ final cancelled = restored;
+ if (cancelled is ElectrumXInterface) {
+ await cancelled.electrumXClient.closeAdapter();
+ }
},
);
},
@@ -212,14 +221,15 @@ class _RestoreViewOnlyWalletViewState
}
try {
- final wallet = await Wallet.create(
+ final wallet = restored = await Wallet.create(
walletInfo: info,
mainDB: ref.read(mainDBProvider),
secureStorageInterface: ref.read(secureStoreProvider),
nodeService: ref.read(nodeServiceChangeNotifierProvider),
prefs: ref.read(prefsChangeNotifierProvider),
viewOnlyData: viewOnlyData,
);
+ if (!mounted || !isRestoring) return;
// TODO: extract interface with isRestore param
switch (wallet) {
@@ -246,7 +256,7 @@ class _RestoreViewOnlyWalletViewState
await wallet.recover(isRescan: false);
// check if state is still active before continuing
- if (mounted) {
+ if (mounted && isRestoring) {
// don't remove this setMnemonicVerified thing
await wallet.info.setMnemonicVerified(
isar: ref.read(mainDBProvider).isar,
@@ -259,13 +269,14 @@ class _RestoreViewOnlyWalletViewState
);
}
+ if (!mounted || !isRestoring) return;
ref.read(pWallets).addWallet(wallet);
+ added = true;
if (mounted) {
if (Util.isDesktop) {
- Navigator.of(
- context,
- ).popUntil(ModalRoute.withName(DesktopHomeView.routeName));
+ Navigator.of(context)
+ .popUntil(ModalRoute.withName(DesktopHomeView.routeName));
} else {
unawaited(
Navigator.of(
@@ -307,6 +318,12 @@ class _RestoreViewOnlyWalletViewState
}
}
} finally {
+ // A cancelled or failed restore never adds the wallet, so nothing else
+ // will close its Electrum connection.
+ final unused = restored;
+ if (!added && unused is ElectrumXInterface) {
+ await unused.electrumXClient.closeAdapter();
+ }
if (!Platform.isLinux && !Util.isDesktop) await WakelockPlus.disable();
}
}
@@ -406,12 +423,12 @@ class _RestoreViewOnlyWalletViewState
if (widget.coin is Firo)
isDesktop ? "Spark View Key" : "View Key",
],
- onColor: Theme.of(
- context,
- ).extension<StackColors>()!.popupBG,
- offColor: Theme.of(
- context,
- ).extension<StackColors>()!.textFieldDefaultBG,
+ onColor: Theme.of(context)
+ .extension<StackColors>()!
+ .popupBG,
+ offColor: Theme.of(context)
+ .extension<StackColors>()!
+ .textFieldDefaultBG,
selectedIndex: _walletType.index - 1,
onValueChanged: (value) {
setState(() {
### lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart
@@ -28,6 +28,7 @@ import '../../../pages_desktop_specific/my_stack_view/exit_to_my_stack_button.da
import '../../../providers/global/secure_store_provider.dart';
import '../../../providers/providers.dart';
import '../../../services/transaction_notification_tracker.dart';
+import '../../../services/wallets.dart';
import '../../../themes/stack_colors.dart';
import '../../../utilities/address_utils.dart';
import '../../../utilities/assets.dart';
@@ -51,6 +52,7 @@ import '../../../wallets/wallet/intermediate/external_wallet.dart';
import '../../../wallets/wallet/supporting/epiccash_wallet_info_extension.dart';
import '../../../wallets/wallet/supporting/mimblewimblecoin_wallet_info_extension.dart';
import '../../../wallets/wallet/wallet.dart';
+import '../../../wallets/wallet/wallet_mixin_interfaces/electrumx_interface.dart';
import '../../../widgets/custom_buttons/app_bar_icon_button.dart';
import '../../../widgets/desktop/desktop_app_bar.dart';
import '../../../widgets/desktop/desktop_scaffold.dart';
@@ -292,6 +294,7 @@ class _RestoreWalletViewState extends ConsumerState<RestoreWalletView> {
);
bool isRestoring = true;
+ Wallet? restored;
// show restoring in progress
if (mounted) {
@@ -310,6 +313,13 @@ class _RestoreWalletViewState extends ConsumerState<RestoreWalletView> {
await ref
.read(pWallets)
.deleteWallet(info, ref.read(secureStoreProvider));
+
+ // Stop the cancelled restore's network work now: its
+ // recover() fails and the wallet is never added.
+ final cancelled = restored;
+ if (cancelled is ElectrumXInterface) {
+ await cancelled.electrumXClient.closeAdapter();
+ }
},
);
},
@@ -333,7 +343,7 @@ class _RestoreWalletViewState extends ConsumerState<RestoreWalletView> {
);
try {
- final wallet = await Wallet.create(
+ final wallet = restored = await Wallet.create(
walletInfo: info,
mainDB: ref.read(mainDBProvider),
secureStorageInterface: ref.read(secureStoreProvider),
@@ -481,6 +491,14 @@ class _RestoreWalletViewState extends ConsumerState<RestoreWalletView> {
if (mounted) setState(() => _hideSeedWords = false);
}
+ } finally {
+ // A cancelled or failed restore never adds the wallet, so nothing
+ // else will close its Electrum connection.
+ final unused = restored;
+ if (unused is ElectrumXInterface &&
+ !Wallets.sharedInstance.wallets.contains(unused)) {
+ await unused.electrumXClient.closeAdapter();
+ }
}
if (!Platform.isLinux && !isDesktop) {
### lib/pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart
@@ -16,24 +16,26 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:uuid/uuid.dart';
+import '../../../../models/node_form_data.dart';
import '../../../../models/node_model.dart';
import '../../../../notifications/show_flush_bar.dart';
-import '../../../../providers/global/active_wallet_provider.dart';
import '../../../../providers/global/secure_store_provider.dart';
import '../../../../providers/providers.dart';
import '../../../../themes/stack_colors.dart';
import '../../../../utilities/assets.dart';
import '../../../../utilities/barcode_scanner_interface.dart';
import '../../../../utilities/constants.dart';
-import '../../../../utilities/enums/sync_type_enum.dart';
import '../../../../utilities/flutter_secure_storage_interface.dart';
import '../../../../utilities/logger.dart';
+import '../../../../utilities/node_change_notifier.dart';
import '../../../../utilities/node_uri_util.dart';
import '../../../../utilities/test_node_connection.dart';
import '../../../../utilities/text_styles.dart';
+import '../../../../utilities/tls_certificate.dart';
import '../../../../utilities/tor_plain_net_option_enum.dart';
import '../../../../utilities/util.dart';
import '../../../../wallets/crypto_currency/crypto_currency.dart';
+import '../../../../wallets/crypto_currency/interfaces/electrumx_currency_interface.dart';
import '../../../../wallets/crypto_currency/intermediate/cryptonote_currency.dart';
import '../../../../widgets/background.dart';
import '../../../../widgets/conditional_parent.dart';
@@ -48,7 +50,7 @@ import '../../../../widgets/stack_dialog.dart';
import '../../../../widgets/stack_text_field.dart';
import '../../../../widgets/textfield_icon_button.dart';
-// import 'package:web3dart/web3dart.dart';
+export '../../../../models/node_form_data.dart';
enum AddEditNodeViewType { add, edit }
@@ -83,28 +85,50 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
late bool saveEnabled;
late bool testConnectionEnabled;
+ late final NodeFormData _form;
+ bool _busy = false;
+
void _onTestSuccess(NodeFormData data) {
- if (coin is Epiccash) {
- ref.read(nodeFormDataProvider).host = data.host;
- ref.read(nodeFormDataProvider).port = data.port;
- ref.read(nodeFormDataProvider).useSSL = data.useSSL;
- } else if (coin is Mimblewimblecoin) {
- ref.read(nodeFormDataProvider).host = data.host;
- ref.read(nodeFormDataProvider).port = data.port;
- ref.read(nodeFormDataProvider).useSSL = data.useSSL;
- } else if (coin is CryptonoteCurrency) {
- ref.read(nodeFormDataProvider).host = data.host;
+ if (mounted && identical(data, _form)) setState(() {});
+ }
+
+ VoidCallback? _whileIdle(Future<void> Function() action) =>
+ _busy ? null : () => _runBusy(action);
+
+ Future<void> _runBusy(Future<void> Function() action) async {
+ if (_busy) return;
+ setState(() => _busy = true);
+ try {
+ await WidgetsBinding.instance.endOfFrame;
+ await _form.passwordLoad;
+ if (mounted) await action();
+ } catch (error, stack) {
+ Logging.instance.w('$error', error: error, stackTrace: stack);
+ if (mounted) {
+ unawaited(
+ showFloatingFlushBar(
+ type: FlushBarType.warning,
+ message: 'Node operation failed',
+ context: context,
+ ),
+ );
+ }
+ } finally {
+ if (mounted) setState(() => _busy = false);
}
}
Future<void> attemptSave() async {
+ final service = ref.read(nodeServiceChangeNotifierProvider);
+ final notify = nodeChangeNotifier(ref, coin);
final canConnect = await ref.read(testNodeConnectionProvider)(
context: context,
onSuccess: _onTestSuccess,
cryptoCurrency: coin,
- nodeFormData: ref.read(nodeFormDataProvider),
+ nodeFormData: _form,
);
+ if (!mounted || ModalRoute.of(context)?.isCurrent == false) return;
bool? shouldSave;
if (!canConnect && mounted) {
@@ -217,12 +241,12 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
});
}
- if (!canConnect && !shouldSave!) {
+ if (!mounted || (!canConnect && shouldSave != true)) {
// return without saving
return;
}
- final formData = ref.read(nodeFormDataProvider);
+ final formData = _form;
// strip unused path
String address = formData.host!;
@@ -255,6 +279,7 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
coinName: coin.identifier,
isFailover: formData.isFailover!,
trusted: formData.trusted!,
+ trustedCertificatePem: formData.trustedCertificatePem,
isDown: false,
torEnabled: torEnabled,
clearnetEnabled: plainEnabled,
@@ -263,10 +288,8 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
nodeApiSecret: formData.apiSecret,
);
- await ref
- .read(nodeServiceChangeNotifierProvider)
- .save(node, formData.password, true);
- await _notifyWalletsOfUpdatedNode();
+ await service.save(node, formData.password, true);
+ await notify();
if (mounted) {
Navigator.of(context)
.popUntil(ModalRoute.withName(widget.routeOnSuccessOrDelete));
@@ -284,6 +307,7 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
coinName: coin.identifier,
isFailover: formData.isFailover!,
trusted: formData.trusted!,
+ trustedCertificatePem: formData.trustedCertificatePem,
isDown: false,
torEnabled: torEnabled,
clearnetEnabled: plainEnabled,
@@ -292,10 +316,16 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
nodeApiSecret: formData.apiSecret,
);
- await ref
- .read(nodeServiceChangeNotifierProvider)
- .save(node, formData.password, true);
- await _notifyWalletsOfUpdatedNode();
+ if (!await service.saveEdit(
+ node,
+ formData.password,
+ true,
+ opened: formData.source!,
+ forgetCertificate: formData.certificateForgotten,
+ )) {
+ return;
+ }
+ await notify();
if (mounted) {
Navigator.of(context)
.popUntil(ModalRoute.withName(widget.routeOnSuccessOrDelete));
@@ -304,41 +334,6 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
}
}
- Future<void> _notifyWalletsOfUpdatedNode() async {
- final wallets = ref
- .read(pWallets)
- .wallets
- .where((e) => e.info.coin == widget.coin);
- final prefs = ref.read(prefsChangeNotifierProvider);
-
- switch (prefs.syncType) {
- case SyncingType.currentWalletOnly:
- for (final wallet in wallets) {
- if (ref.read(currentWalletIdProvider) == wallet.walletId) {
- unawaited(wallet.updateNode().then((value) => wallet.refresh()));
- } else {
- unawaited(wallet.updateNode());
- }
- }
- break;
- case SyncingType.selectedWalletsAtStartup:
- final List<String> walletIdsToSync = prefs.walletIdsSyncOnStartup;
- for (final wallet in wallets) {
- if (walletIdsToSync.contains(wallet.walletId)) {
- unawaited(wallet.updateNode().then((value) => wallet.refresh()));
- } else {
- unawaited(wallet.updateNode());
- }
- }
- break;
- case SyncingType.allWalletsOnStartup:
- for (final wallet in wallets) {
- unawaited(wallet.updateNode().then((value) => wallet.refresh()));
- }
- break;
- }
- }
-
bool _scanLock = false;
void _scanQr() async {
@@ -433,7 +428,7 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
@override
void initState() {
isDesktop = Util.isDesktop;
- ref.refresh(nodeFormDataProvider);
+ _form = ref.refresh(nodeFormDataProvider);
viewType = widget.viewType;
coin = widget.coin;
@@ -517,7 +512,7 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
.extension<StackColors>()!
.accentColorDark,
),
- onPressed: _scanQr,
+ onPressed: _busy ? null : _scanQr,
),
),
),
@@ -553,16 +548,23 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
width: 20,
height: 20,
),
- onPressed: () async {
- Navigator.popUntil(
- context,
- ModalRoute.withName(widget.routeOnSuccessOrDelete),
- );
-
- await ref
- .read(nodeServiceChangeNotifierProvider)
- .delete(nodeId!, true);
- },
+ onPressed: _busy
+ ? null
+ : () async {
+ final service = ref.read(
+ nodeServiceChangeNotifierProvider,
+ );
+ final notify = nodeChangeNotifier(ref, coin);
+ Navigator.popUntil(
+ context,
+ ModalRoute.withName(
+ widget.routeOnSuccessOrDelete,
+ ),
+ );
+
+ await service.delete(nodeId!, true);
+ await notify();
+ },
),
),
),
@@ -601,7 +603,7 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
maxWidth: 580,
maxHeight: double.infinity,
child: Column(
- mainAxisSize: MainAxisSize.min,
+ mainAxisSize: .min,
children: [
const SizedBox(height: 8),
Row(
@@ -630,7 +632,7 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
.extension<StackColors>()!
.background,
icon: const QrCodeIcon(width: 21, height: 21),
- onPressed: _scanQr,
+ onPressed: _busy ? null : _scanQr,
),
),
],
@@ -648,14 +650,16 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
),
),
child: Column(
- crossAxisAlignment: CrossAxisAlignment.stretch,
+ crossAxisAlignment: .stretch,
children: [
NodeForm(
key: Key((node ?? _scannedResult?.$1)?.id ?? "none"),
node: node ?? _scannedResult?.$1,
scannedPw: _scannedResult?.$2,
secureStore: ref.read(secureStoreProvider),
readOnly: false,
+ busy: _busy,
+ data: _form,
coin: widget.coin,
onChanged: (canSave, canTest) {
if (canSave != saveEnabled &&
@@ -682,16 +686,16 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
Expanded(
child: SecondaryButton(
label: "Test connection",
- enabled: testConnectionEnabled,
+ enabled: testConnectionEnabled && !_busy,
buttonHeight: isDesktop ? ButtonHeight.l : null,
- onPressed: testConnectionEnabled
- ? () async {
+ onPressed: testConnectionEnabled && !_busy
+ ? _whileIdle(() async {
final testPassed =
await ref.read(testNodeConnectionProvider)(
context: context,
onSuccess: _onTestSuccess,
cryptoCurrency: coin,
- nodeFormData: ref.read(nodeFormDataProvider),
+ nodeFormData: _form,
);
if (context.mounted) {
if (testPassed) {
@@ -712,7 +716,7 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
);
}
}
- }
+ })
: null,
),
),
@@ -721,9 +725,11 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
Expanded(
child: PrimaryButton(
label: "Save",
- enabled: saveEnabled,
+ enabled: saveEnabled && !_busy,
buttonHeight: ButtonHeight.l,
- onPressed: saveEnabled ? attemptSave : null,
+ onPressed: saveEnabled && !_busy
+ ? _whileIdle(attemptSave)
+ : null,
),
),
],
@@ -738,7 +744,9 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
: Theme.of(context)
.extension<StackColors>()!
.getPrimaryDisabledButtonStyle(context),
- onPressed: saveEnabled ? attemptSave : null,
+ onPressed: saveEnabled && !_busy
+ ? _whileIdle(attemptSave)
+ : null,
child: Text("Save", style: STextStyles.button(context)),
),
],
@@ -748,24 +756,14 @@ class _AddEditNodeViewState extends ConsumerState<AddEditNodeView> {
}
}
-class NodeFormData {
- String? name, host, login, password, apiSecret;
- int? port;
- bool? useSSL, isFailover, trusted, forceNoTor, isPrimary;
- TorPlainNetworkOption? netOption;
-
- @override
- String toString() {
- return "{ name: $name, host: $host, port: $port, useSSL: $useSSL, trusted: $trusted, netOption: $netOption, isPrimary: $isPrimary }";
- }
-}
-
final nodeFormDataProvider = Provider<NodeFormData>((_) => NodeFormData());
class NodeForm extends ConsumerStatefulWidget {
const NodeForm({
super.key,
this.node,
+ this.data,
+ this.busy = false,
this.scannedPw,
required this.secureStore,
required this.readOnly,
@@ -774,6 +772,8 @@ class NodeForm extends ConsumerStatefulWidget {
});
final NodeModel? node;
+ final NodeFormData? data;
+ final bool busy;
final String? scannedPw;
final SecureStorageInterface secureStore;
final bool readOnly;
@@ -785,6 +785,36 @@ class NodeForm extends ConsumerStatefulWidget {
}
class _NodeFormState extends ConsumerState<NodeForm> {
+ late final NodeFormData _data;
+ bool _changing = false;
+ bool _passwordEdited = false;
+ bool get _inputsReadOnly => widget.readOnly || widget.busy || _changing;
+ String? get _certificate => widget.readOnly
+ ? widget.node?.trustedCertificatePem
+ : _data.trustedCertificatePem;
+
+ Future<void> _changeNode(Future<bool> Function() action) async {
+ if (widget.busy || _changing) return;
+ final notify = nodeChangeNotifier(ref, widget.coin);
+ setState(() => _changing = true);
+ try {
+ if (await action()) await notify();
+ } catch (error, stack) {
+ Logging.instance.w('$error', error: error, stackTrace: stack);
+ if (mounted) {
+ unawaited(
+ showFloatingFlushBar(
+ type: FlushBarType.warning,
+ message: 'Node operation failed',
+ context: context,
+ ),
+ );
+ }
+ } finally {
+ if (mounted) setState(() => _changing = false);
+ }
+ }
+
late final TextEditingController _nameController;
late final TextEditingController _hostController;
late final TextEditingController _portController;
@@ -834,41 +864,49 @@ class _NodeFormState extends ConsumerState<NodeForm> {
bool enableField(TextEditingController controller) {
bool enable = true;
- if (widget.readOnly) {
+ if (_inputsReadOnly) {
enable = controller.text.isNotEmpty;
}
return enable;
}
bool get shouldBeReadOnly =>
- widget.readOnly || widget.node?.isDefault == true;
+ _inputsReadOnly || widget.node?.isDefault == true;
void _updateState() {
+ if (widget.busy || _changing) return;
+ _copyToFormData();
+ }
+
+ void _copyToFormData() {
port = int.tryParse(_portController.text);
onChanged?.call(canSave, canTestConnection);
- ref.read(nodeFormDataProvider).name = _nameController.text;
- ref.read(nodeFormDataProvider).host = _hostController.text;
- ref.read(nodeFormDataProvider).login = _usernameController.text.isEmpty
+ _data.name = _nameController.text;
+ _data.host = _hostController.text;
+ _data.login = _usernameController.text.isEmpty
? null
: _usernameController.text;
- ref.read(nodeFormDataProvider).password = _passwordController.text.isEmpty
+ _data.password = _passwordController.text.isEmpty
? null
: _passwordController.text;
- ref.read(nodeFormDataProvider).apiSecret = _apiSecretController.text.isEmpty
+ _data.apiSecret = _apiSecretController.text.isEmpty
? null
: _apiSecretController.text;
- ref.read(nodeFormDataProvider).port = port;
- ref.read(nodeFormDataProvider).useSSL = _useSSL;
- ref.read(nodeFormDataProvider).isFailover = _isFailover;
- ref.read(nodeFormDataProvider).trusted = _trusted;
- ref.read(nodeFormDataProvider).netOption = netOption;
- ref.read(nodeFormDataProvider).forceNoTor = _forceNoTor;
- ref.read(nodeFormDataProvider).host;
- ref.read(nodeFormDataProvider).isPrimary = _isPrimary;
+ _data.port = port;
+ _data.useSSL = _useSSL;
+ _data.isFailover = _isFailover;
+ _data.trusted = _trusted;
+ _data.netOption = netOption;
+ _data.forceNoTor = _forceNoTor;
+ _data.host;
+ _data.isPrimary = _isPrimary;
}
@override
void initState() {
+ _data = widget.data ?? ref.read(nodeFormDataProvider);
+ _data.source = widget.node;
+ _data.trustedCertificatePem = null;
onChanged = widget.onChanged;
_nameController = TextEditingController();
_hostController = TextEditingController();
@@ -883,11 +921,16 @@ class _NodeFormState extends ConsumerState<NodeForm> {
final node = widget.node!;
if (enableAuthFields) {
if (widget.scannedPw == null) {
- node.getPassword(widget.secureStore).then((value) {
- if (value is String) {
- _passwordController.text = value;
- }
- });
+ // Save and Test await this; a failed read must not block them.
+ _data.passwordLoad = node.getPassword(widget.secureStore).then((
+ value,
+ ) {
+ if (!mounted || value is! String || _passwordEdited) return;
+ _passwordController.text = value;
+ _data.password = value;
+ // Tests and saves may run before any field is edited.
+ _updateState();
+ }, onError: (Object _) {});
} else {
_passwordController.text = widget.scannedPw!;
}
@@ -921,8 +964,12 @@ class _NodeFormState extends ConsumerState<NodeForm> {
}
WidgetsBinding.instance.addPostFrameCallback((_) {
- // update provider state object so test connection works without having to modify a field in the ui first
- _updateState();
+ if (!mounted) return;
+ // A replacement node must hydrate even while a previous test is busy.
+ // Copy its endpoint before binding its certificate to the form.
+ _copyToFormData();
+ _data.trustedCertificatePem = node.trustedCertificatePem;
+ if (mounted) setState(() {});
});
} else {
enableSSLCheckbox = true;
@@ -1234,6 +1281,8 @@ class _NodeFormState extends ConsumerState<NodeForm> {
TextFieldIconButton(
child: const XIcon(),
onTap: () async {
+ if (widget.busy || _changing) return;
+ _passwordEdited = true;
_passwordController.text = "";
_updateState();
},
@@ -1245,6 +1294,8 @@ class _NodeFormState extends ConsumerState<NodeForm> {
: null,
),
onChanged: (newValue) {
+ if (widget.busy || _changing) return;
+ _passwordEdited = true;
_updateState();
setState(() {});
},
@@ -1350,11 +1401,57 @@ class _NodeFormState extends ConsumerState<NodeForm> {
),
],
),
+ if ((widget.coin is ElectrumXCurrencyInterface ||
+ widget.coin is BitcoinFrost) &&
+ _useSSL &&
+ _certificate != null)
+ Column(
+ crossAxisAlignment: .start,
+ children: [
+ const SizedBox(height: 8),
+ Row(
+ children: [
+ Expanded(
+ child: SelectableText(
+ 'Trusted TLS certificate\n'
+ 'SHA-256:\n'
+ '${certificatePemFingerprint(_certificate!) ?? 'Unavailable'}',
+ style: STextStyles.itemSubtitle12(context),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 8),
+ Row(
+ children: [
+ const Spacer(),
+ SecondaryButton(
+ label: 'Forget certificate',
+ buttonHeight: .s,
+ padding: const .symmetric(horizontal: 10),
+ onPressed: widget.busy || _changing
+ ? null
+ : () async {
+ if (!widget.readOnly) {
+ setState(_data.forgetCertificate);
+ return;
+ }
+ await _changeNode(
+ () => ref
+ .read(nodeServiceChangeNotifierProvider)
+ .forgetTrustedCertificate(widget.node!),
+ );
+ },
+ ),
+ ],
+ ),
+ ],
+ ),
if (widget.coin is CryptonoteCurrency)
Row(
children: [
GestureDetector(
- onTap: !widget.readOnly /*&& trustedCheckbox*/
+ onTap: !_inputsReadOnly
? () {
setState(() {
_trusted = !_trusted;
@@ -1370,7 +1467,7 @@ class _NodeFormState extends ConsumerState<NodeForm> {
width: 20,
height: 20,
child: Checkbox(
- fillColor: !widget.readOnly
+ fillColor: !_inputsReadOnly
? null
: MaterialStateProperty.all(
Theme.of(context)
@@ -1380,7 +1477,7 @@ class _NodeFormState extends ConsumerState<NodeForm> {
materialTapTargetSize:
MaterialTapTargetSize.shrinkWrap,
value: _trusted,
- onChanged: !widget.readOnly
+ onChanged: !_inputsReadOnly
? (newValue) {
setState(() {
_trusted = newValue!;
@@ -1411,26 +1508,24 @@ class _NodeFormState extends ConsumerState<NodeForm> {
Row(
children: [
GestureDetector(
- onTap: () {
- setState(() {
- _isFailover = !_isFailover;
- });
- if (widget.readOnly) {
- ref
- .read(nodeServiceChangeNotifierProvider)
- .save(
- widget.node!.copyWith(
- isFailover: _isFailover,
- loginName: widget.node!.loginName,
- trusted: widget.node!.trusted,
- ),
- null,
- true,
- );
- } else {
- _updateState();
- }
- },
+ onTap: widget.busy || _changing
+ ? null
+ : () {
+ setState(() {
+ _isFailover = !_isFailover;
+ });
+ if (widget.readOnly) {
+ unawaited(
+ _changeNode(
+ () => ref
+ .read(nodeServiceChangeNotifierProvider)
+ .setFailover(widget.node!.id, _isFailover),
+ ),
+ );
+ } else {
+ _updateState();
+ }
+ },
child: Container(
color: Colors.transparent,
child: Row(
@@ -1442,26 +1537,29 @@ class _NodeFormState extends ConsumerState<NodeForm> {
materialTapTargetSize:
MaterialTapTargetSize.shrinkWrap,
value: _isFailover,
- onChanged: (newValue) {
- setState(() {
- _isFailover = newValue!;
- });
- if (widget.readOnly) {
- ref
- .read(nodeServiceChangeNotifierProvider)
- .save(
- widget.node!.copyWith(
- isFailover: _isFailover,
- loginName: widget.node!.loginName,
- trusted: widget.node!.trusted,
- ),
- null,
- true,
- );
- } else {
- _updateState();
- }
- },
+ onChanged: widget.busy || _changing
+ ? null
+ : (newValue) {
+ setState(() {
+ _isFailover = newValue!;
+ });
+ if (widget.readOnly) {
+ unawaited(
+ _changeNode(
+ () => ref
+ .read(
+ nodeServiceChangeNotifierProvider,
+ )
+ .setFailover(
+ widget.node!.id,
+ _isFailover,
+ ),
+ ),
+ );
+ } else {
+ _updateState();
+ }
+ },
),
),
const SizedBox(width: 12),
@@ -1480,11 +1578,11 @@ class _NodeFormState extends ConsumerState<NodeForm> {
children: [
RadioTextButton(
label: "Only TOR traffic",
- enabled: !widget.readOnly,
+ enabled: !_inputsReadOnly,
value: TorPlainNetworkOption.tor,
groupValue: netOption,
onChanged: (value) {
- if (!widget.readOnly) {
+ if (!_inputsReadOnly) {
setState(() => netOption = TorPlainNetworkOption.tor);
_updateState();
}
@@ -1497,11 +1595,11 @@ class _NodeFormState extends ConsumerState<NodeForm> {
children: [
RadioTextButton(
label: "Only non-TOR traffic",
- enabled: !widget.readOnly,
+ enabled: !_inputsReadOnly,
value: TorPlainNetworkOption.clear,
groupValue: netOption,
onChanged: (value) {
- if (!widget.readOnly) {
+ if (!_inputsReadOnly) {
setState(() => netOption = TorPlainNetworkOption.clear);
_updateState();
}
@@ -1514,11 +1612,11 @@ class _NodeFormState extends ConsumerState<NodeForm> {
children: [
RadioTextButton(
label: "Allow both",
- enabled: !widget.readOnly,
+ enabled: !_inputsReadOnly,
value: TorPlainNetworkOption.both,
groupValue: netOption,
onChanged: (value) {
- if (!widget.readOnly) {
+ if (!_inputsReadOnly) {
setState(() => netOption = TorPlainNetworkOption.both);
_updateState();
}
@@ -1535,7 +1633,7 @@ class _NodeFormState extends ConsumerState<NodeForm> {
width: 20,
height: 20,
child: Checkbox(
- fillColor: !widget.readOnly
+ fillColor: !_inputsReadOnly
? null
: MaterialStateProperty.all(
Theme.of(context)
@@ -1544,7 +1642,7 @@ class _NodeFormState extends ConsumerState<NodeForm> {
),
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
value: _forceNoTor,
- onChanged: !widget.readOnly
+ onChanged: !_inputsReadOnly
? (newValue) {
setState(() {
_forceNoTor = newValue!;
@@ -1599,8 +1697,8 @@ class RadioTextButton<T> extends StatelessWidget {
child: Container(
color: Colors.transparent,
child: Row(
- mainAxisSize: MainAxisSize.min,
- crossAxisAlignment: CrossAxisAlignment.start,
+ mainAxisSize: .min,
+ crossAxisAlignment: .start,
children: [
SizedBox(
width: 20,
### lib/pages/settings_views/global_settings_view/manage_nodes_views/node_details_view.dart
@@ -16,14 +16,14 @@ import 'package:flutter_svg/svg.dart';
import 'package:tuple/tuple.dart';
import '../../../../notifications/show_flush_bar.dart';
-import '../../../../providers/global/active_wallet_provider.dart';
import '../../../../providers/global/secure_store_provider.dart';
import '../../../../providers/providers.dart';
import '../../../../themes/stack_colors.dart';
import '../../../../utilities/assets.dart';
-import '../../../../utilities/enums/sync_type_enum.dart';
import '../../../../utilities/flutter_secure_storage_interface.dart';
import '../../../../utilities/test_node_connection.dart';
+import '../../../../utilities/logger.dart';
+import '../../../../utilities/node_change_notifier.dart';
import '../../../../utilities/text_styles.dart';
import '../../../../utilities/tor_plain_net_option_enum.dart';
import '../../../../utilities/util.dart';
@@ -62,44 +62,38 @@ class _NodeDetailsViewState extends ConsumerState<NodeDetailsView> {
late final String popRouteName;
bool _desktopReadOnly = true;
+ bool _busy = false;
+ late final NodeFormData _form;
- Future<void> _notifyWalletsOfUpdatedNode() async {
- final wallets = ref
- .read(pWallets)
- .wallets
- .where((e) => e.info.coin == widget.coin);
- final prefs = ref.read(prefsChangeNotifierProvider);
+ VoidCallback? _whileIdle(Future<void> Function() action) =>
+ _busy ? null : () => _runBusy(action);
- switch (prefs.syncType) {
- case SyncingType.currentWalletOnly:
- for (final wallet in wallets) {
- if (ref.read(currentWalletIdProvider) == wallet.walletId) {
- unawaited(wallet.updateNode().then((value) => wallet.refresh()));
- } else {
- unawaited(wallet.updateNode());
- }
- }
- break;
- case SyncingType.selectedWalletsAtStartup:
- final List<String> walletIdsToSync = prefs.walletIdsSyncOnStartup;
- for (final wallet in wallets) {
- if (walletIdsToSync.contains(wallet.walletId)) {
- unawaited(wallet.updateNode().then((value) => wallet.refresh()));
- } else {
- unawaited(wallet.updateNode());
- }
- }
- break;
- case SyncingType.allWalletsOnStartup:
- for (final wallet in wallets) {
- unawaited(wallet.updateNode().then((value) => wallet.refresh()));
- }
- break;
+ Future<void> _runBusy(Future<void> Function() action) async {
+ if (_busy) return;
+ setState(() => _busy = true);
+ try {
+ await WidgetsBinding.instance.endOfFrame;
+ await _form.passwordLoad;
+ if (mounted) await action();
+ } catch (error, stack) {
+ Logging.instance.w('$error', error: error, stackTrace: stack);
+ if (mounted) {
+ unawaited(
+ showFloatingFlushBar(
+ type: FlushBarType.warning,
+ message: 'Node operation failed',
+ context: context,
+ ),
+ );
+ }
+ } finally {
+ if (mounted) setState(() => _busy = false);
}
}
@override
initState() {
+ _form = ref.refresh(nodeFormDataProvider);
secureStore = ref.read(secureStoreProvider);
coin = widget.coin;
nodeId = widget.nodeId;
@@ -129,9 +123,9 @@ class _NodeDetailsViewState extends ConsumerState<NodeDetailsView> {
condition: !isDesktop,
builder: (child) => Background(
child: Scaffold(
- backgroundColor: Theme.of(
- context,
- ).extension<StackColors>()!.background,
+ backgroundColor: Theme.of(context)
+ .extension<StackColors>()!
+ .background,
appBar: AppBar(
leading: AppBarBackButton(
onPressed: () async {
@@ -158,28 +152,30 @@ class _NodeDetailsViewState extends ConsumerState<NodeDetailsView> {
key: const Key("nodeDetailsEditNodeAppBarButtonKey"),
size: 36,
shadows: const [],
- color: Theme.of(
- context,
- ).extension<StackColors>()!.background,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .background,
icon: SvgPicture.asset(
Assets.svg.pencil,
- color: Theme.of(
- context,
- ).extension<StackColors>()!.accentColorDark,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .accentColorDark,
width: 20,
height: 20,
),
- onPressed: () {
- Navigator.of(context).pushNamed(
- AddEditNodeView.routeName,
- arguments: Tuple4(
- AddEditNodeViewType.edit,
- coin,
- nodeId,
- popRouteName,
- ),
- );
- },
+ onPressed: _busy
+ ? null
+ : () {
+ Navigator.of(context).pushNamed(
+ AddEditNodeView.routeName,
+ arguments: Tuple4(
+ AddEditNodeViewType.edit,
+ coin,
+ nodeId,
+ popRouteName,
+ ),
+ );
+ },
),
),
),
@@ -238,6 +234,10 @@ class _NodeDetailsViewState extends ConsumerState<NodeDetailsView> {
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
NodeForm(
+ // Reload the form only when the stored node changes.
+ key: ValueKey(node),
+ data: _form,
+ busy: _busy,
node: node,
secureStore: secureStore,
readOnly: isDesktop ? _desktopReadOnly : true,
@@ -256,13 +256,21 @@ class _NodeDetailsViewState extends ConsumerState<NodeDetailsView> {
child: DeleteButton(
label: "Delete node",
desktopMed: true,
- onPressed: () async {
- Navigator.of(context).pop();
+ onPressed: _busy
+ ? null
+ : () async {
+ final service = ref.read(
+ nodeServiceChangeNotifierProvider,
+ );
+ final notify = nodeChangeNotifier(
+ ref,
+ coin,
+ );
+ Navigator.of(context).pop();
- await ref
- .read(nodeServiceChangeNotifierProvider)
- .delete(node!.id, true);
- },
+ await service.delete(node!.id, true);
+ await notify();
+ },
),
),
const SizedBox(width: 16),
@@ -277,36 +285,27 @@ class _NodeDetailsViewState extends ConsumerState<NodeDetailsView> {
Expanded(
child: SecondaryButton(
label: "Test connection",
+ enabled: !_busy,
buttonHeight: isDesktop ? ButtonHeight.l : null,
- onPressed: () async {
+ onPressed: _whileIdle(() async {
+ final service = ref.read(
+ nodeServiceChangeNotifierProvider,
+ );
+ final notify = nodeChangeNotifier(ref, coin);
final node = ref
.read(nodeServiceChangeNotifierProvider)
.getNodeById(id: nodeId)!;
- final TorPlainNetworkOption netOption;
- if (ref.read(nodeFormDataProvider).netOption != null) {
- netOption = ref.read(nodeFormDataProvider).netOption!;
- } else {
- netOption = TorPlainNetworkOption.fromNodeData(
- node.torEnabled,
- node.clearnetEnabled,
+ final editing = isDesktop && !_desktopReadOnly;
+ final nodeFormData = editing
+ ? _form
+ : NodeFormData.fromNode(node);
+ if (!editing) {
+ nodeFormData.password = await node.getPassword(
+ ref.read(secureStoreProvider),
);
}
- final nodeFormData = NodeFormData()
- ..useSSL = node.useSSL
- ..trusted = node.trusted
- ..name = node.name
- ..host = node.host
- ..login = node.loginName
- ..port = node.port
- ..isFailover = node.isFailover
- ..netOption = netOption
- ..forceNoTor = node.forceNoTor;
- nodeFormData.password = await node.getPassword(
- ref.read(secureStoreProvider),
- );
-
if (context.mounted) {
final testPassed =
await ref.read(testNodeConnectionProvider)(
@@ -316,6 +315,14 @@ class _NodeDetailsViewState extends ConsumerState<NodeDetailsView> {
);
if (testPassed) {
+ if (!editing) {
+ final saved = await service.saveTrustedCertificate(
+ node,
+ nodeFormData,
+ );
+ if (saved) await notify();
+ }
+ if (mounted) setState(() {});
if (context.mounted) {
unawaited(
showFloatingFlushBar(
@@ -337,62 +344,58 @@ class _NodeDetailsViewState extends ConsumerState<NodeDetailsView> {
}
}
}
- },
+ }),
),
),
if (isDesktop) const SizedBox(width: 16),
if (isDesktop)
Expanded(
- child:
- // !nodeId.startsWith(DefaultNodes.defaultNodeIdPrefix)
- // ?
- PrimaryButton(
- label: _desktopReadOnly ? "Edit" : "Save",
- buttonHeight: ButtonHeight.l,
- onPressed: () async {
- final shouldSave = _desktopReadOnly == false;
- setState(() {
- _desktopReadOnly = !_desktopReadOnly;
- });
-
- if (shouldSave) {
- final editedNode = node!.copyWith(
- host: ref.read(nodeFormDataProvider).host,
- port: ref.read(nodeFormDataProvider).port,
- name: ref.read(nodeFormDataProvider).name,
- useSSL: ref.read(nodeFormDataProvider).useSSL,
- trusted: ref.read(nodeFormDataProvider).trusted,
- loginName: ref.read(nodeFormDataProvider).login,
- isFailover: ref
- .read(nodeFormDataProvider)
- .isFailover,
- torEnabled:
- ref.read(nodeFormDataProvider).netOption ==
- TorPlainNetworkOption.tor ||
- ref.read(nodeFormDataProvider).netOption ==
- TorPlainNetworkOption.both,
- clearnetEnabled:
- ref.read(nodeFormDataProvider).netOption ==
- TorPlainNetworkOption.clear ||
- ref.read(nodeFormDataProvider).netOption ==
- TorPlainNetworkOption.both,
- forceNoTor: ref
- .read(nodeFormDataProvider)
- .forceNoTor,
- );
+ child: PrimaryButton(
+ label: _desktopReadOnly ? "Edit" : "Save",
+ enabled: !_busy,
+ buttonHeight: ButtonHeight.l,
+ onPressed: _whileIdle(() async {
+ if (_desktopReadOnly) {
+ setState(() => _desktopReadOnly = false);
+ return;
+ }
+ final service = ref.read(
+ nodeServiceChangeNotifierProvider,
+ );
+ final notify = nodeChangeNotifier(ref, coin);
+ final editedNode = node!.copyWith(
+ host: _form.host,
+ port: _form.port,
+ name: _form.name,
+ useSSL: _form.useSSL,
+ trusted: _form.trusted,
+ trustedCertificatePem: _form.trustedCertificatePem,
+ clearTrustedCertificate:
+ _form.trustedCertificatePem == null,
+ loginName: _form.login,
+ isFailover: _form.isFailover,
+ torEnabled:
+ _form.netOption == TorPlainNetworkOption.tor ||
+ _form.netOption == TorPlainNetworkOption.both,
+ clearnetEnabled:
+ _form.netOption == TorPlainNetworkOption.clear ||
+ _form.netOption == TorPlainNetworkOption.both,
+ forceNoTor: _form.forceNoTor,
+ );
- await ref
- .read(nodeServiceChangeNotifierProvider)
- .save(
- editedNode,
- ref.read(nodeFormDataProvider).password,
- true,
- );
- await _notifyWalletsOfUpdatedNode();
- }
- },
- ),
- // : Container()
+ if (!await service.saveEdit(
+ editedNode,
+ _form.password,
+ true,
+ opened: _form.source!,
+ forgetCertificate: _form.certificateForgotten,
+ )) {
+ return;
+ }
+ await notify();
+ if (mounted) setState(() => _desktopReadOnly = true);
+ }),
+ ),
),
],
),
### lib/services/node_service.dart
@@ -16,6 +16,7 @@ import 'package:http/http.dart';
import '../app_config.dart';
import '../db/hive/db.dart';
import '../models/epicbox_server_model.dart';
+import '../models/node_form_data.dart';
import '../models/node_model.dart';
import '../utilities/default_epicboxes.dart';
import '../utilities/default_nodes.dart';
@@ -67,50 +68,41 @@ class NodeService extends ChangeNotifier {
isPrimary: false,
);
- await DB.instance.put<NodeModel>(
- boxName: DB.boxNameNodeModels,
- key: _id,
- value: node,
- );
+ await _writeNode(_id, (current) => current == null ? node : null);
}
}
}
for (final defaultNode in AppConfig.coins.map(
(e) => e.defaultNode(isPrimary: true),
)) {
- final savedNode = DB.instance.get<NodeModel>(
- boxName: DB.boxNameNodeModels,
- key: defaultNode.id,
- );
- if (savedNode == null) {
- // save the default node to hive only if no other nodes for the specific coin exist
- if (getNodesFor(
- AppConfig.getCryptoCurrencyByPrettyName(defaultNode.coinName),
- ).isEmpty) {
- await DB.instance.put<NodeModel>(
- boxName: DB.boxNameNodeModels,
- key: defaultNode.id,
- value: defaultNode,
- );
+ await _writeNode(defaultNode.id, (savedNode) {
+ if (savedNode == null) {
+ return getNodesFor(
+ AppConfig.getCryptoCurrencyByPrettyName(defaultNode.coinName),
+ ).isEmpty
+ ? defaultNode
+ : null;
}
- } else {
- // update all fields but copy over previously set enabled and trusted states
- await DB.instance.put<NodeModel>(
- boxName: DB.boxNameNodeModels,
- key: savedNode.id,
- value: defaultNode.copyWith(
- enabled: savedNode.enabled,
- isFailover: savedNode.isFailover,
- trusted: savedNode.trusted,
- torEnabled: savedNode.torEnabled,
- clearnetEnabled: savedNode.clearnetEnabled,
- loginName: savedNode.loginName,
- isPrimary: savedNode.isPrimary,
- forceNoTor: savedNode.forceNoTor,
- ),
+ return defaultNode.copyWith(
+ enabled: savedNode.enabled,
+ isFailover: savedNode.isFailover,
+ trusted: savedNode.trusted,
+ torEnabled: savedNode.torEnabled,
+ clearnetEnabled: savedNode.clearnetEnabled,
+ loginName: savedNode.loginName,
+ isPrimary: savedNode.isPrimary,
+ forceNoTor: savedNode.forceNoTor,
+ trustedCertificatePem:
+ savedNode.sameEndpoint(
+ host: defaultNode.host,
+ port: defaultNode.port,
+ useSSL: defaultNode.useSSL,
+ )
+ ? savedNode.trustedCertificatePem
+ : null,
);
- }
+ });
}
}
@@ -119,40 +111,48 @@ class NodeService extends ChangeNotifier {
required NodeModel node,
bool shouldNotifyListeners = false,
}) async {
- // current
- final currentPrimaries = primaryNodes.where(
- (e) => e.coinName == coin.identifier && e.id != node.id,
- );
- final List<NodeModel> toStore = [];
- for (final node in currentPrimaries) {
- final updated = node.copyWith(
- loginName: node.loginName,
- trusted: node.trusted,
- isPrimary: false,
+ await DB.instance.mutex.protect(() async {
+ await _promote(getNodeById(id: node.id) ?? node);
+ });
+ if (shouldNotifyListeners) notifyListeners();
+ }
+
+ // The caller holds DB's write lock; only primary flags change.
+ Future<void> _promote(NodeModel node) async {
+ final box = DB.instance.hive.box<NodeModel>(DB.boxNameNodeModels);
+ for (final other in primaryNodes.where(
+ (other) => other.coinName == node.coinName && other.id != node.id,
+ )) {
+ await box.put(
+ other.id,
+ other.copyWith(
+ loginName: other.loginName,
+ trusted: other.trusted,
+ isPrimary: false,
+ ),
);
- toStore.add(updated);
}
- toStore.add(
+ await box.put(
+ node.id,
node.copyWith(
loginName: node.loginName,
trusted: node.trusted,
isPrimary: true,
),
);
-
- for (final node in toStore) {
- await DB.instance.put<NodeModel>(
- boxName: DB.boxNameNodeModels,
- key: node.id,
- value: node,
- );
- }
-
- if (shouldNotifyListeners) {
- notifyListeners();
- }
}
+ // Normal Hive boxes cache immutable NodeModels. Identity detects any write,
+ // including Forget of an empty approval, without another persisted revision.
+ Future<bool> _writeNode(String id, NodeModel? Function(NodeModel?) next) =>
+ DB.instance.mutex.protect(() async {
+ final box = DB.instance.hive.box<NodeModel>(DB.boxNameNodeModels);
+ final node = next(box.get(id));
+ if (node == null) return false;
+ await box.put(id, node);
+ return true;
+ });
+
NodeModel? getPrimaryNodeFor({required CryptoCurrency currency}) {
return primaryNodes
.where((e) => e.coinName == currency.identifier)
@@ -198,9 +198,9 @@ class NodeService extends ChangeNotifier {
}
List<NodeModel> failoverNodesFor({required CryptoCurrency currency}) {
- return getNodesFor(
- currency,
- ).where((e) => e.isFailover && !e.isDown).toList();
+ return getNodesFor(currency)
+ .where((e) => e.isFailover && !e.isDown)
+ .toList();
}
/// Adds a new node to the database.
@@ -218,20 +218,145 @@ class NodeService extends ChangeNotifier {
value: node,
);
- // Save password to secure storage.
- if (password != null) {
- await secureStorageInterface.write(
- key: "${node.id}_nodePW",
- value: password,
- );
- } else {
- await secureStorageInterface.delete(key: "${node.id}_nodePW");
- }
+ await _savePassword(node.id, password);
if (shouldNotifyListeners) {
notifyListeners();
}
}
+ Future<void> _savePassword(String id, String? password) async {
+ if (password == null) {
+ await secureStorageInterface.delete(key: "${id}_nodePW");
+ } else {
+ await secureStorageInterface.write(key: "${id}_nodePW", value: password);
+ }
+ }
+
+ Future<bool> saveEdit(
+ NodeModel node,
+ String? password,
+ bool notify, {
+ required NodeModel opened,
+ bool forgetCertificate = false,
+ }) async {
+ if (getNodeById(id: node.id) == null) return false;
+ await _savePassword(node.id, password);
+ final saved = await _writeNode(node.id, (current) {
+ if (current == null) return null;
+ final pem = identical(current, opened) || forgetCertificate
+ ? node.trustedCertificatePem
+ : node.sameEndpoint(
+ host: current.host,
+ port: current.port,
+ useSSL: current.useSSL,
+ )
+ ? current.trustedCertificatePem
+ : null;
+ return node.copyWith(
+ loginName: node.loginName,
+ trusted: node.trusted,
+ isPrimary: current.isPrimary,
+ trustedCertificatePem: pem,
+ clearTrustedCertificate: pem == null,
+ );
+ });
+ if (saved && notify) notifyListeners();
+ return saved;
+ }
+
+ bool prepareCertificateTest(NodeFormData data) {
+ final source = data.source;
+ if (source == null) return true;
+ final current = getNodeById(id: source.id);
+ if (current == null) return false;
+ if (!identical(source, current)) {
+ if (!data.certificateForgotten) {
+ data.trustedCertificatePem = data.matchesEndpointOf(current)
+ ? current.trustedCertificatePem
+ : null;
+ }
+ data.source = current;
+ }
+ return true;
+ }
+
+ Future<bool> saveTrustedCertificate(NodeModel node, NodeFormData data) async {
+ final pem = data.trustedCertificatePem;
+ final saved = await _writeNode(
+ node.id,
+ (current) =>
+ identical(current, node) &&
+ pem != null &&
+ data.matchesEndpointOf(current!) &&
+ current.trustedCertificatePem != pem
+ ? current.copyWith(
+ loginName: current.loginName,
+ trusted: current.trusted,
+ trustedCertificatePem: pem,
+ )
+ : null,
+ );
+ if (saved) notifyListeners();
+ return saved;
+ }
+
+ Future<bool> forgetTrustedCertificate(NodeModel shown) async {
+ final saved = await _writeNode(
+ shown.id,
+ (current) =>
+ current != null &&
+ shown.sameEndpoint(
+ host: current.host,
+ port: current.port,
+ useSSL: current.useSSL,
+ )
+ ? current.copyWith(
+ loginName: current.loginName,
+ trusted: current.trusted,
+ clearTrustedCertificate: true,
+ )
+ : null,
+ );
+ if (saved) notifyListeners();
+ return saved;
+ }
+
+ Future<bool> commitConnectionTest({
+ required NodeModel node,
+ required NodeFormData formData,
+ }) async {
+ final saved = await DB.instance.mutex.protect(() async {
+ if (!identical(getNodeById(id: node.id), node)) return false;
+ final pem = formData.matchesEndpointOf(node)
+ ? formData.trustedCertificatePem
+ : node.trustedCertificatePem;
+ await _promote(
+ node.copyWith(
+ loginName: node.loginName,
+ trusted: node.trusted,
+ trustedCertificatePem: pem,
+ clearTrustedCertificate: pem == null,
+ ),
+ );
+ return true;
+ });
+ if (saved) notifyListeners();
+ return saved;
+ }
+
+ Future<bool> setFailover(String id, bool value) async {
+ final saved = await _writeNode(
+ id,
+ (node) => node?.copyWith(
+ loginName: node.loginName,
+ trusted: node.trusted,
+ isFailover: value,
+ ),
+ );
+ if (saved) notifyListeners();
+ return saved;
+ }
+
Future<void> delete(String id, bool shouldNotifyListeners) async {
final nodeToDelete = getNodeById(id: id);
@@ -271,14 +396,9 @@ class NodeService extends ChangeNotifier {
bool enabled,
bool shouldNotifyListeners,
) async {
- final model = DB.instance.get<NodeModel>(
- boxName: DB.boxNameNodeModels,
- key: id,
- )!;
- await DB.instance.put<NodeModel>(
- boxName: DB.boxNameNodeModels,
- key: model.id,
- value: model.copyWith(
+ await _writeNode(
+ id,
+ (model) => model?.copyWith(
enabled: enabled,
loginName: model.loginName,
trusted: model.trusted,
### lib/services/notifications_service.dart
@@ -14,7 +14,6 @@ import 'package:flutter/foundation.dart';
import '../app_config.dart';
import '../db/hive/db.dart';
-import '../electrumx_rpc/electrumx_client.dart';
import '../exceptions/electrumx/no_such_transaction.dart';
import '../models/exchange/response_objects/trade.dart';
import '../models/notification_model.dart';
@@ -150,37 +149,11 @@ class NotificationsService extends ChangeNotifier {
}
}
- final eNode = ElectrumXNode(
- address: node.host,
- port: node.port,
- name: node.name,
- id: node.id,
- useSSL: node.useSSL,
- torEnabled: node.torEnabled,
- clearnetEnabled: node.clearnetEnabled,
+ // The wallet's own client: no extra connection per check, and a
+ // node or approval change replaces it through updateNode().
+ final tx = await wallet.electrumXClient.getTransaction(
+ txHash: txid,
);
- final failovers = nodeService
- .failoverNodesFor(currency: coin)
- .map(
- (e) => ElectrumXNode(
- address: e.host,
- port: e.port,
- name: e.name,
- id: e.id,
- useSSL: e.useSSL,
- torEnabled: node.torEnabled,
- clearnetEnabled: node.clearnetEnabled,
- ),
- )
- .toList();
-
- final client = ElectrumXClient.from(
- node: eNode,
- failovers: failovers,
- prefs: prefs,
- cryptoCurrency: wallet.cryptoCurrency,
- );
- final tx = await client.getTransaction(txHash: txid);
int confirmations = tx["confirmations"] as int? ?? 0;
### lib/services/wallets.dart
@@ -33,6 +33,7 @@ import '../wallets/wallet/impl/mimblewimblecoin_wallet.dart';
import '../wallets/wallet/intermediate/cryptonote_wallet.dart';
import '../wallets/wallet/intermediate/lib_salvium_wallet.dart';
import '../wallets/wallet/wallet.dart';
+import '../wallets/wallet/wallet_mixin_interfaces/electrumx_interface.dart';
import 'event_bus/events/wallet_added_event.dart';
import 'event_bus/global_event_bus.dart';
import 'node_service.dart';
@@ -117,6 +118,21 @@ class Wallets {
final wallet = _wallets[walletId];
_wallets.remove(walletId);
await wallet?.exit();
+ // An Electrum wallet owns its connection; no other client will close it.
+ try {
+ if (wallet is ElectrumXInterface) {
+ await wallet.electrumXClient.closeAdapter();
+ } else if (wallet is BitcoinFrostWallet) {
+ await wallet.electrumXClient.closeAdapter();
+ }
+ } catch (e, s) {
+ // A wallet that never loaded has no client.
+ Logging.instance.w(
+ "Closing the Electrum client of $walletId",
+ error: e,
+ stackTrace: s,
+ );
+ }
if (info.coin is Xelis) {
// Remove unlocked native storage before forgetting its password.
### lib/utilities/connection_check/electrum_connection_check.dart
@@ -1,19 +1,83 @@
+import 'dart:async';
import 'dart:io';
import 'package:electrum_adapter/electrum_adapter.dart';
import '../../app_config.dart';
+import '../../models/node_form_data.dart';
import '../../services/event_bus/events/global/tor_connection_status_changed_event.dart';
import '../../services/tor_service.dart';
import '../logger.dart';
import '../prefs.dart';
+import '../tls_certificate.dart';
-Future<bool> checkElectrumServer({
+/// The outcome of one connection attempt. [certificate] is the server's TLS
+/// certificate when the attempt failed because that certificate was rejected.
+class ElectrumConnectionResult {
+ const ElectrumConnectionResult({
+ required this.success,
+ this.certificate,
+ this.error,
+ });
+
+ final bool success;
+ final X509Certificate? certificate;
+ final Object? error;
+}
+
+/// Connects, sends server.version and disconnects. A certificate the
+/// platform rejects is accepted only when it is the approved one; any other
+/// is returned for review without being accepted.
+Future<ElectrumConnectionResult> testElectrumConnection({
+ required String host,
+ required int port,
+ required bool useSSL,
+ required Duration timeout,
+ String? trustedCertificatePem,
+ ({InternetAddress host, int port})? proxyInfo,
+}) async {
+ ElectrumClient? client;
+ X509Certificate? rejected;
+ try {
+ final trusted = useSSL
+ ? trustedCertificateCheck(trustedCertificatePem)
+ : null;
+ client = await ElectrumClient.connect(
+ host: host,
+ port: port,
+ useSSL: useSSL,
+ proxyInfo: proxyInfo,
+ connectionTimeout: timeout,
+ connectionDeadline: timeout,
+ requestTimeout: timeout,
+ acceptUnverified: false,
+ onBadCertificate: (certificate) {
+ if (trusted != null && trusted(certificate)) return true;
+ rejected = certificate;
+ return false;
+ },
+ );
+ await client.request('server.version');
+ return const ElectrumConnectionResult(success: true);
+ } catch (error) {
+ return ElectrumConnectionResult(
+ success: false,
+ certificate: rejected,
+ error: error,
+ );
+ } finally {
+ await client?.close();
+ }
+}
+
+/// Applies the Tor preference, then runs [testElectrumConnection].
+Future<ElectrumConnectionResult> checkElectrumServer({
required String host,
required int port,
required bool useSSL,
Prefs? overridePrefs,
TorService? overrideTorService,
+ String? trustedCertificatePem,
}) async {
final _prefs = overridePrefs ?? Prefs.instance;
@@ -43,27 +107,75 @@ Future<bool> checkElectrumServer({
}
}
- final client =
- await ElectrumClient.connect(
- host: host,
- port: port,
- useSSL: useSSL && !host.endsWith('.onion'),
- proxyInfo: proxyInfo,
- acceptUnverified: false,
- ).timeout(
- Duration(seconds: (proxyInfo == null ? 5 : 30)),
- onTimeout: () => throw Exception(
- "The checkElectrumServer connect() call timed out.",
- ),
- );
-
- await client
- .request('server.version')
- .timeout(Duration(seconds: (proxyInfo == null ? 5 : 30)));
-
- return true;
+ return await testElectrumConnection(
+ host: host,
+ port: port,
+ useSSL: useSSL,
+ trustedCertificatePem: trustedCertificatePem,
+ proxyInfo: proxyInfo,
+ timeout: Duration(seconds: proxyInfo == null ? 5 : 30),
+ );
} catch (e, s) {
Logging.instance.e("$e\n$s", error: e, stackTrace: s);
- return false;
+ return ElectrumConnectionResult(success: false, error: e);
+ }
+}
+
+typedef ElectrumNodeTester = Future<ElectrumConnectionResult> Function({
+ required String host,
+ required int port,
+ required bool useSSL,
+ String? trustedCertificatePem,
+});
+
+/// Tests the node in [data]. A rejected certificate is offered for review
+/// through [requestTrust]; after approval the test is retried with it, and
+/// only a successful retry keeps the approval in the form. The UI supplies
+/// the approval dialog.
+Future<bool> testElectrumNodeConnection(
+ NodeFormData data, {
+ required ElectrumNodeTester testConnection,
+ required Future<bool> Function(X509Certificate, String, int) requestTrust,
+ required bool Function() isActive,
+ void Function(NodeFormData)? onSuccess,
+}) async {
+ final host = data.host!;
+ final port = data.port!;
+ final useSSL = data.useSSL!;
+ final netOption = data.netOption;
+ final certificatePem = data.trustedCertificatePem;
+ final decision = data.certificateRevision;
+ bool unchanged() =>
+ isActive() &&
+ data.host == host &&
+ data.port == port &&
+ data.useSSL == useSSL &&
+ data.netOption == netOption &&
+ data.certificateRevision == decision &&
+ data.trustedCertificatePem == certificatePem;
+
+ var response = await testConnection(
+ host: host,
+ port: port,
+ useSSL: useSSL,
+ trustedCertificatePem: certificatePem,
+ );
+ if (!unchanged()) return false;
+ final certificate = response.certificate;
+ if (certificate != null) {
+ final shouldTrust = await requestTrust(certificate, host, port);
+ if (!shouldTrust || !unchanged()) return false;
+ response = await testConnection(
+ host: host,
+ port: port,
+ useSSL: useSSL,
+ trustedCertificatePem: certificate.pem,
+ );
+ if (!unchanged()) return false;
+ if (response.success) {
+ data.trustedCertificatePem = certificate.pem;
+ }
}
+ if (response.success) onSuccess?.call(data);
+ return response.success;
}
### lib/utilities/node_change_notifier.dart
@@ -0,0 +1,42 @@
+import 'dart:async';
+
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+
+import '../providers/global/active_wallet_provider.dart';
+import '../providers/providers.dart';
+import '../wallets/crypto_currency/crypto_currency.dart';
+import 'enums/sync_type_enum.dart';
+
+/// Captures providers while the view is alive, then notifies the wallets
+/// still loaded when the returned callback runs.
+Future<void> Function() nodeChangeNotifier(WidgetRef ref, CryptoCurrency coin) {
+ final wallets = ref.read(pWallets);
+ final prefs = ref.read(prefsChangeNotifierProvider);
+ final activeWallet = ref.read(currentWalletIdProvider.notifier);
+
+ return () async {
+ // Every Electrum connection belongs to one client. updateNode() closes the
+ // wallet's previous client, with any connection it still drains, so a
+ // revoked approval or replaced node outlives no loaded wallet.
+ for (final wallet in wallets.wallets.where((e) => e.info.coin == coin)) {
+ final shouldRefresh = switch (prefs.syncType) {
+ SyncingType.currentWalletOnly => activeWallet.state == wallet.walletId,
+ SyncingType.selectedWalletsAtStartup =>
+ prefs.walletIdsSyncOnStartup.contains(wallet.walletId),
+ SyncingType.allWalletsOnStartup => true,
+ };
+ // A refresh already running fails with the replaced client, and
+ // refresh() hands back that same run. Sync again once it ends.
+ final wasRefreshing = wallet.refreshMutex.isLocked;
+ final update = wallet.updateNode();
+ unawaited(
+ shouldRefresh
+ ? update.then((_) async {
+ await wallet.refresh();
+ if (wasRefreshing) await wallet.refresh();
+ })
+ : update,
+ );
+ }
+ };
+}
### lib/utilities/test_monero_node_connection.dart
@@ -30,23 +30,15 @@ class MoneroNodeConnectionResponse {
final int? port;
final bool success;
- MoneroNodeConnectionResponse(
- this.cert,
- this.url,
- this.port,
- this.success,
- );
+ MoneroNodeConnectionResponse(this.cert, this.url, this.port, this.success);
}
Future<MoneroNodeConnectionResponse> testMoneroNodeConnection(
Uri uri,
String? username,
String? password,
bool allowBadX509Certificate, {
- required ({
- InternetAddress host,
- int port,
- })? proxyInfo,
+ required ({InternetAddress host, int port})? proxyInfo,
}) async {
if (uri.host.endsWith(".onion")) {
if (proxyInfo == null) {
@@ -80,8 +72,9 @@ Future<MoneroNodeConnectionResponse> testMoneroNodeConnection(
// node asking us for authentication, but we don't have any crendentials.
return MoneroNodeConnectionResponse(null, null, null, false);
}
- authenticateHeaderValue =
- line.replaceFirst('WWW-authenticate: ', '').trim();
+ authenticateHeaderValue = line
+ .replaceFirst('WWW-authenticate: ', '')
+ .trim();
}
}
// header to authenticate was present, we need to remake the request with digest
@@ -91,8 +84,12 @@ Future<MoneroNodeConnectionResponse> testMoneroNodeConnection(
// generate the Authorization header for the second request.
final authHeader = digestAuth.getAuthString('POST', uri.path);
- final rawRequestAuthenticated =
- DaemonRpc.rawRequestRpc(uri, 'get_info', {}, authHeader);
+ final rawRequestAuthenticated = DaemonRpc.rawRequestRpc(
+ uri,
+ 'get_info',
+ {},
+ authHeader,
+ );
// resend with an authenticated request
response = await socket.send(rawRequestAuthenticated);
}
@@ -103,7 +100,7 @@ Future<MoneroNodeConnectionResponse> testMoneroNodeConnection(
return MoneroNodeConnectionResponse(null, null, null, success);
} catch (e, s) {
- Logging.instance.w("$e\n$s", error: e, stackTrace: s,);
+ Logging.instance.w("$e\n$s", error: e, stackTrace: s);
return MoneroNodeConnectionResponse(null, null, null, false);
} finally {
await socket?.close();
@@ -114,10 +111,7 @@ Future<MoneroNodeConnectionResponse> testMoneroNodeConnection(
try {
if (proxyInfo != null) {
SocksTCPClient.assignToHttpClient(httpClient, [
- ProxySettings(
- proxyInfo.host,
- proxyInfo.port,
- ),
+ ProxySettings(proxyInfo.host, proxyInfo.port),
]);
}
@@ -127,8 +121,12 @@ Future<MoneroNodeConnectionResponse> testMoneroNodeConnection(
}
if (badCertResponse == null) {
- badCertResponse =
- MoneroNodeConnectionResponse(cert, url, port, false);
+ badCertResponse = MoneroNodeConnectionResponse(
+ cert,
+ url,
+ port,
+ false,
+ );
} else {
return false;
}
@@ -150,7 +148,7 @@ Future<MoneroNodeConnectionResponse> testMoneroNodeConnection(
if (badCertResponse != null) {
return badCertResponse!;
} else {
- Logging.instance.w("$e\n$s", error: e, stackTrace: s,);
+ Logging.instance.w("$e\n$s", error: e, stackTrace: s);
return MoneroNodeConnectionResponse(null, null, null, false);
}
} finally {
@@ -204,7 +202,7 @@ Future<bool> showBadX509CertificateDialog(
extension on SOCKSSocket {
/// write the raw request to the socket and return the response as String
Future<String> send(String rawRequest) async {
- write(rawRequest);
+ await write(rawRequest);
final buffer = StringBuffer();
await for (final response in inputStream) {
buffer.write(utf8.decode(response));
### lib/utilities/test_node_connection.dart
@@ -11,6 +11,7 @@ import '../app_config.dart';
import '../networking/http.dart';
import '../pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart';
import '../providers/global/prefs_provider.dart';
+import '../providers/global/node_service_provider.dart';
import '../services/tor_service.dart';
import '../wallets/api/cardano/blockfrost_http_provider.dart';
import '../wallets/api/tezos/tezos_rpc_api.dart';
@@ -20,6 +21,7 @@ import '../wallets/crypto_currency/intermediate/cryptonote_currency.dart';
import '../wallets/crypto_currency/intermediate/nano_currency.dart';
import '../wallets/wallet/impl/solana_wallet.dart';
import '../wl_gen/interfaces/lib_xelis_interface.dart';
+import '../widgets/tls_certificate_dialog.dart' as electrum_tls;
import 'connection_check/electrum_connection_check.dart';
import 'logger.dart';
import 'test_epic_box_connection.dart';
@@ -220,12 +222,40 @@ Future<bool> testNodeConnection({
case ElectrumXCurrencyInterface():
case BitcoinFrost():
try {
- testPassed = await checkElectrumServer(
- host: formData.host!,
- port: formData.port!,
- useSSL: formData.useSSL!,
- overridePrefs: read(prefsChangeNotifierProvider),
- overrideTorService: read(pTorService),
+ if (!read(nodeServiceChangeNotifierProvider)
+ .prepareCertificateTest(formData)) {
+ return false;
+ }
+ final prefs = read(prefsChangeNotifierProvider);
+ final torService = read(pTorService);
+ final useTor = prefs.useTor;
+ final torStatus = AppConfig.hasFeature(AppFeature.tor) && useTor
+ ? torService.status
+ : null;
+ testPassed = await testElectrumNodeConnection(
+ formData,
+ isActive: () =>
+ context.mounted &&
+ ModalRoute.of(context)?.isCurrent != false &&
+ prefs.useTor == useTor &&
+ (torStatus == null || torService.status == torStatus),
+ onSuccess: onSuccess,
+ requestTrust: (certificate, host, port) => electrum_tls
+ .showBadX509CertificateDialog(certificate, host, port, context),
+ testConnection:
+ ({
+ required host,
+ required port,
+ required useSSL,
+ trustedCertificatePem,
+ }) => checkElectrumServer(
+ host: host,
+ port: port,
+ useSSL: useSSL,
+ trustedCertificatePem: trustedCertificatePem,
+ overridePrefs: prefs,
+ overrideTorService: torService,
+ ),
);
} catch (_) {
testPassed = false;
### lib/utilities/tls_certificate.dart
@@ -0,0 +1,42 @@
+import 'dart:convert';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:crypto/crypto.dart';
+
+Uint8List certificateDer(String pem) {
+ final match = RegExp(
+ r'^\s*-----BEGIN CERTIFICATE-----\s*([A-Za-z0-9+/=\s]+)-----END CERTIFICATE-----\s*$',
+ ).firstMatch(pem);
+ if (match == null || match.end != pem.length) {
+ throw const FormatException('Expected one PEM certificate');
+ }
+ return base64Decode(match.group(1)!.replaceAll(RegExp(r'\s'), ''));
+}
+
+String certificateFingerprint(List<int> der) {
+ final hex = sha256.convert(der).toString().toUpperCase();
+ return [for (int i = 0; i < hex.length; i += 2) hex.substring(i, i + 2)]
+ .join(':');
+}
+
+String? certificatePemFingerprint(String pem) {
+ try {
+ return certificateFingerprint(certificateDer(pem));
+ } on FormatException {
+ return null;
+ }
+}
+
+/// The check a TLS connection runs when the platform rejects the server's
+/// certificate. It accepts exactly the certificate approved for the node,
+/// whatever its hostname or validity. A certificate the platform trusts
+/// never reaches it. Null when nothing is approved, so the platform's verdict
+/// stands. Throws a [FormatException] for a damaged PEM before connecting.
+bool Function(X509Certificate)? trustedCertificateCheck(
+ String? certificatePem,
+) {
+ if (certificatePem == null) return null;
+ final trusted = certificateFingerprint(certificateDer(certificatePem));
+ return (certificate) => certificateFingerprint(certificate.der) == trusted;
+}
### lib/wallets/wallet/impl/bitcoin_frost_wallet.dart
@@ -1292,6 +1292,7 @@ class BitcoinFrostWallet<T extends FrostCurrency> extends Wallet<T>
port: node.port,
name: node.name,
useSSL: node.useSSL,
+ trustedCertificatePem: node.trustedCertificatePem,
id: node.id,
torEnabled: node.torEnabled,
clearnetEnabled: node.clearnetEnabled,
@@ -1309,26 +1310,23 @@ class BitcoinFrostWallet<T extends FrostCurrency> extends Wallet<T>
name: e.name,
id: e.id,
useSSL: e.useSSL,
+ trustedCertificatePem: e.trustedCertificatePem,
torEnabled: e.torEnabled,
clearnetEnabled: e.clearnetEnabled,
),
)
.toList();
final newNode = await _getCurrentElectrumXNode();
+ ElectrumXClient? previous;
try {
- await electrumXClient.closeAdapter();
- } catch (e, s) {
- if (e.toString().contains("initialized")) {
- // Ignore. This should happen every first time the wallet is opened.
- } else {
- Logging.instance.e(
- "Error closing electrumXClient",
- error: e,
- stackTrace: s,
- );
- }
+ previous = electrumXClient;
+ } catch (e) {
+ // Not initialized: this happens every first time the wallet is opened.
+ if (!e.toString().contains("initialized")) rethrow;
}
+ // Replace before closing, so an overlapping update closes this client
+ // instead of overwriting it while it is still open.
electrumXClient = ElectrumXClient.from(
node: newNode,
prefs: prefs,
@@ -1339,6 +1337,34 @@ class BitcoinFrostWallet<T extends FrostCurrency> extends Wallet<T>
electrumXCachedClient = CachedElectrumXClient.from(
electrumXClient: electrumXClient,
);
+ try {
+ await previous?.closeAdapter();
+ } catch (e, s) {
+ Logging.instance.e(
+ "Error closing electrumXClient",
+ error: e,
+ stackTrace: s,
+ );
+ }
+ }
+
+ @override
+ Future<void> exit() async {
+ await super.exit();
+ // This wallet no longer syncs. Its connection closes once a refresh in
+ // progress ends; the client reconnects if the wallet is opened again.
+ unawaited(() async {
+ try {
+ await refreshMutex.protect(() async {});
+ if (!shouldAutoSync) await electrumXClient.disconnect();
+ } catch (e, s) {
+ Logging.instance.w(
+ "Releasing the Electrum connection of $walletId",
+ error: e,
+ stackTrace: s,
+ );
+ }
+ }());
}
bool _duplicateTxCheck(
### lib/wallets/wallet/wallet_mixin_interfaces/electrumx_interface.dart
@@ -9,7 +9,6 @@ import 'package:meta/meta.dart';
import '../../../db/drift/database.dart';
import '../../../electrumx_rpc/cached_electrumx_client.dart';
-import '../../../electrumx_rpc/client_manager.dart';
import '../../../electrumx_rpc/electrumx_client.dart';
import '../../../models/coinlib/exp2pkh_address.dart';
import '../../../models/input.dart';
@@ -25,6 +24,7 @@ import '../../../utilities/enums/fee_rate_type_enum.dart';
import '../../../utilities/extensions/extensions.dart';
import '../../../utilities/logger.dart';
import '../../../utilities/paynym_is_api.dart';
+import '../../../utilities/tor_plain_net_option_enum.dart';
import '../../crypto_currency/coins/firo.dart';
import '../../crypto_currency/interfaces/electrumx_currency_interface.dart';
import '../../isar/models/wallet_info.dart';
@@ -1033,9 +1033,21 @@ mixin ElectrumXInterface<T extends ElectrumXCurrencyInterface>
await _initializeServerVersionAndCheckGenesisHash();
}
- return await ClientManager.sharedInstance.getChainHeightFor(
- cryptoCurrency,
- );
+ // The network restriction the shared header subscription enforced.
+ if (prefs.useTor) {
+ if (electrumXClient.netType == TorPlainNetworkOption.clear) {
+ throw Exception(
+ "Non-TOR only client for ${cryptoCurrency.identifier} found.",
+ );
+ }
+ } else if (electrumXClient.netType == TorPlainNetworkOption.tor) {
+ throw Exception(
+ "TOR only client for ${cryptoCurrency.identifier} found.",
+ );
+ }
+
+ final tip = await electrumXClient.getBlockHeadTip();
+ return tip["height"] as int;
} catch (e, s) {
if (retries > 0) {
retries--;
@@ -1094,6 +1106,7 @@ mixin ElectrumXInterface<T extends ElectrumXCurrencyInterface>
port: node.port,
name: node.name,
useSSL: node.useSSL,
+ trustedCertificatePem: node.trustedCertificatePem,
id: node.id,
torEnabled: node.torEnabled,
clearnetEnabled: node.clearnetEnabled,
@@ -1110,26 +1123,23 @@ mixin ElectrumXInterface<T extends ElectrumXCurrencyInterface>
name: e.name,
id: e.id,
useSSL: e.useSSL,
+ trustedCertificatePem: e.trustedCertificatePem,
torEnabled: e.torEnabled,
clearnetEnabled: e.clearnetEnabled,
),
)
.toList();
final newNode = await _getCurrentElectrumXNode();
+ ElectrumXClient? previous;
try {
- await electrumXClient.closeAdapter();
- } catch (e, s) {
- if (e.toString().contains("initialized")) {
- // Ignore. This should happen every first time the wallet is opened.
- } else {
- Logging.instance.e(
- "Error closing electrumXClient",
- error: e,
- stackTrace: s,
- );
- }
+ previous = electrumXClient;
+ } catch (e) {
+ // Not initialized: this happens every first time the wallet is opened.
+ if (!e.toString().contains("initialized")) rethrow;
}
+ // Replace before closing, so an overlapping update closes this client
+ // instead of overwriting it while it is still open.
electrumXClient = ElectrumXClient.from(
node: newNode,
prefs: prefs,
@@ -1139,6 +1149,37 @@ mixin ElectrumXInterface<T extends ElectrumXCurrencyInterface>
electrumXCachedClient = CachedElectrumXClient.from(
electrumXClient: electrumXClient,
);
+ try {
+ await previous?.closeAdapter();
+ } catch (e, s) {
+ Logging.instance.e(
+ "Error closing electrumXClient",
+ error: e,
+ stackTrace: s,
+ );
+ }
+ }
+
+ @override
+ Future<void> exit() async {
+ await super.exit();
+ // This wallet no longer syncs. Its connection closes once a refresh in
+ // progress ends; the client reconnects if the wallet is opened again.
+ unawaited(releaseConnectionWhenIdle());
+ }
+
+ @visibleForTesting
+ Future<void> releaseConnectionWhenIdle() async {
+ try {
+ await refreshMutex.protect(() async {});
+ if (!shouldAutoSync) await electrumXClient.disconnect();
+ } catch (e, s) {
+ Logging.instance.w(
+ "Releasing the Electrum connection of $walletId",
+ error: e,
+ stackTrace: s,
+ );
+ }
}
//============================================================================
### lib/widgets/node_card.dart
@@ -15,20 +15,18 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';
import 'package:tuple/tuple.dart';
+import '../models/node_form_data.dart';
import '../notifications/show_flush_bar.dart';
-import '../pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart';
import '../pages/settings_views/global_settings_view/manage_nodes_views/node_details_view.dart';
-import '../providers/global/active_wallet_provider.dart';
import '../providers/global/secure_store_provider.dart';
import '../providers/providers.dart';
import '../themes/stack_colors.dart';
import '../utilities/assets.dart';
import '../utilities/constants.dart';
import '../utilities/default_nodes.dart';
-import '../utilities/enums/sync_type_enum.dart';
import '../utilities/test_node_connection.dart';
+import '../utilities/node_change_notifier.dart';
import '../utilities/text_styles.dart';
-import '../utilities/tor_plain_net_option_enum.dart';
import '../utilities/util.dart';
import '../wallets/crypto_currency/crypto_currency.dart';
import 'conditional_parent.dart';
@@ -57,41 +55,7 @@ class _NodeCardState extends ConsumerState<NodeCard> {
String _status = "Disconnected";
late final String nodeId;
bool _advancedIsExpanded = false;
-
- Future<void> _notifyWalletsOfUpdatedNode(WidgetRef ref) async {
- final wallets = ref
- .read(pWallets)
- .wallets
- .where((e) => e.info.coin == widget.coin);
- final prefs = ref.read(prefsChangeNotifierProvider);
-
- switch (prefs.syncType) {
- case SyncingType.currentWalletOnly:
- for (final wallet in wallets) {
- if (ref.read(currentWalletIdProvider) == wallet.walletId) {
- unawaited(wallet.updateNode().then((value) => wallet.refresh()));
- } else {
- unawaited(wallet.updateNode());
- }
- }
- break;
- case SyncingType.selectedWalletsAtStartup:
- final List<String> walletIdsToSync = prefs.walletIdsSyncOnStartup;
- for (final wallet in wallets) {
- if (walletIdsToSync.contains(wallet.walletId)) {
- unawaited(wallet.updateNode().then((value) => wallet.refresh()));
- } else {
- unawaited(wallet.updateNode());
- }
- }
- break;
- case SyncingType.allWalletsOnStartup:
- for (final wallet in wallets) {
- unawaited(wallet.updateNode().then((value) => wallet.refresh()));
- }
- break;
- }
- }
+ bool _connecting = false;
@override
void initState() {
@@ -167,59 +131,63 @@ class _NodeCardState extends ConsumerState<NodeCard> {
text: "Connect",
enabled: _status == "Disconnected",
onTap: () async {
- final TorPlainNetworkOption netOption;
- if (_node.torEnabled && !_node.clearnetEnabled) {
- netOption = TorPlainNetworkOption.tor;
- } else if (_node.clearnetEnabled && !_node.torEnabled) {
- netOption = TorPlainNetworkOption.clear;
- } else {
- netOption = TorPlainNetworkOption.both;
- }
+ // One test at a time, so taps cannot stack dialogs.
+ if (_connecting) return;
+ _connecting = true;
+ try {
+ // Carry the saved certificate so an approved node is
+ // not reviewed again, and keep a new approval below.
+ final service = ref.read(
+ nodeServiceChangeNotifierProvider,
+ );
+ final notify = nodeChangeNotifier(ref, widget.coin);
+ final nodeFormData = NodeFormData.fromNode(_node);
+ nodeFormData.password = await _node.getPassword(
+ ref.read(secureStoreProvider),
+ );
- final nodeFormData = NodeFormData()
- ..useSSL = _node.useSSL
- ..trusted = _node.trusted
- ..name = _node.name
- ..host = _node.host
- ..login = _node.loginName
- ..port = _node.port
- ..netOption = netOption
- ..isFailover = _node.isFailover;
- nodeFormData.password = await _node.getPassword(
- ref.read(secureStoreProvider),
- );
+ if (context.mounted) {
+ final canConnect =
+ await ref.read(testNodeConnectionProvider)(
+ context: context,
+ nodeFormData: nodeFormData,
+ cryptoCurrency: widget.coin,
+ );
- if (context.mounted) {
- final canConnect =
- await ref.read(testNodeConnectionProvider)(
- context: context,
- nodeFormData: nodeFormData,
- cryptoCurrency: widget.coin,
- );
+ if (!canConnect) {
+ if (context.mounted) {
+ unawaited(
+ showFloatingFlushBar(
+ type: FlushBarType.warning,
+ iconAsset: Assets.svg.circleAlert,
+ message: "Could not connect to node",
+ context: context,
+ ),
+ );
+ }
+ return;
+ }
- if (!canConnect) {
- if (context.mounted) {
+ if (await service.commitConnectionTest(
+ node: _node,
+ formData: nodeFormData,
+ )) {
+ await notify();
+ } else if (context.mounted) {
unawaited(
showFloatingFlushBar(
type: FlushBarType.warning,
iconAsset: Assets.svg.circleAlert,
- message: "Could not connect to node",
+ message:
+ "The node changed during the test. "
+ "Please try again.",
context: context,
),
);
}
- return;
}
-
- await ref
- .read(nodeServiceChangeNotifierProvider)
- .setPrimaryNodeFor(
- coin: widget.coin,
- node: _node,
- shouldNotifyListeners: true,
- );
-
- await _notifyWalletsOfUpdatedNode(ref);
+ } finally {
+ _connecting = false;
}
},
),
@@ -251,9 +219,9 @@ class _NodeCardState extends ConsumerState<NodeCard> {
height: isDesktop ? 40 : 24,
decoration: BoxDecoration(
color: _node.id.startsWith(DefaultNodes.defaultNodeIdPrefix)
- ? Theme.of(
- context,
- ).extension<StackColors>()!.buttonBackSecondary
+ ? Theme.of(context)
+ .extension<StackColors>()!
+ .buttonBackSecondary
: Theme.of(context)
.extension<StackColors>()!
.infoItemIcons
@@ -267,12 +235,12 @@ class _NodeCardState extends ConsumerState<NodeCard> {
width: isDesktop ? 20 : 14,
color:
_node.id.startsWith(DefaultNodes.defaultNodeIdPrefix)
- ? Theme.of(
- context,
- ).extension<StackColors>()!.accentColorDark
- : Theme.of(
- context,
- ).extension<StackColors>()!.infoItemIcons,
+ ? Theme.of(context)
+ .extension<StackColors>()!
+ .accentColorDark
+ : Theme.of(context)
+ .extension<StackColors>()!
+ .infoItemIcons,
),
),
),
@@ -290,12 +258,12 @@ class _NodeCardState extends ConsumerState<NodeCard> {
SvgPicture.asset(
Assets.svg.network,
color: _status == "Connected"
- ? Theme.of(
- context,
- ).extension<StackColors>()!.accentColorGreen
- : Theme.of(
- context,
- ).extension<StackColors>()!.buttonBackSecondary,
+ ? Theme.of(context)
+ .extension<StackColors>()!
+ .accentColorGreen
+ : Theme.of(context)
+ .extension<StackColors>()!
+ .buttonBackSecondary,
width: 20,
height: 20,
),
@@ -306,9 +274,9 @@ class _NodeCardState extends ConsumerState<NodeCard> {
: Assets.svg.chevronDown,
width: 12,
height: 6,
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textSubtitle1,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textSubtitle1,
),
],
),
### lib/widgets/node_options_sheet.dart
@@ -15,23 +15,22 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_svg/svg.dart';
import 'package:tuple/tuple.dart';
-import '../pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart';
+import '../models/node_form_data.dart';
+import '../notifications/show_flush_bar.dart';
import '../pages/settings_views/global_settings_view/manage_nodes_views/node_details_view.dart';
-import '../providers/global/active_wallet_provider.dart';
import '../providers/global/secure_store_provider.dart';
import '../providers/providers.dart';
import '../themes/stack_colors.dart';
import '../utilities/assets.dart';
import '../utilities/constants.dart';
import '../utilities/default_nodes.dart';
-import '../utilities/enums/sync_type_enum.dart';
import '../utilities/test_node_connection.dart';
+import '../utilities/node_change_notifier.dart';
import '../utilities/text_styles.dart';
-import '../utilities/tor_plain_net_option_enum.dart';
import '../wallets/crypto_currency/crypto_currency.dart';
import 'rounded_white_container.dart';
-class NodeOptionsSheet extends ConsumerWidget {
+class NodeOptionsSheet extends ConsumerStatefulWidget {
const NodeOptionsSheet({
super.key,
required this.nodeId,
@@ -43,43 +42,18 @@ class NodeOptionsSheet extends ConsumerWidget {
final CryptoCurrency coin;
final String popBackToRoute;
- Future<void> _notifyWalletsOfUpdatedNode(WidgetRef ref) async {
- final wallets = ref
- .read(pWallets)
- .wallets
- .where((e) => e.info.coin == coin);
- final prefs = ref.read(prefsChangeNotifierProvider);
+ @override
+ ConsumerState<NodeOptionsSheet> createState() => _NodeOptionsSheetState();
+}
- switch (prefs.syncType) {
- case SyncingType.currentWalletOnly:
- for (final wallet in wallets) {
- if (ref.read(currentWalletIdProvider) == wallet.walletId) {
- unawaited(wallet.updateNode().then((value) => wallet.refresh()));
- } else {
- unawaited(wallet.updateNode());
- }
- }
- break;
- case SyncingType.selectedWalletsAtStartup:
- final List<String> walletIdsToSync = prefs.walletIdsSyncOnStartup;
- for (final wallet in wallets) {
- if (walletIdsToSync.contains(wallet.walletId)) {
- unawaited(wallet.updateNode().then((value) => wallet.refresh()));
- } else {
- unawaited(wallet.updateNode());
- }
- }
- break;
- case SyncingType.allWalletsOnStartup:
- for (final wallet in wallets) {
- unawaited(wallet.updateNode().then((value) => wallet.refresh()));
- }
- break;
- }
- }
+class _NodeOptionsSheetState extends ConsumerState<NodeOptionsSheet> {
+ bool _connecting = false;
@override
- Widget build(BuildContext context, WidgetRef ref) {
+ Widget build(BuildContext context) {
+ final nodeId = widget.nodeId;
+ final coin = widget.coin;
+ final popBackToRoute = widget.popBackToRoute;
final maxHeight = MediaQuery.of(context).size.height * 0.60;
final node = ref.watch(
nodeServiceChangeNotifierProvider.select(
@@ -121,9 +95,9 @@ class NodeOptionsSheet extends ConsumerWidget {
Center(
child: Container(
decoration: BoxDecoration(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.textFieldDefaultBG,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .textFieldDefaultBG,
borderRadius: BorderRadius.circular(
Constants.size.circularBorderRadius,
),
@@ -150,9 +124,9 @@ class NodeOptionsSheet extends ConsumerWidget {
node.id.startsWith(
DefaultNodes.defaultNodeIdPrefix,
)
- ? Theme.of(
- context,
- ).extension<StackColors>()!.textSubtitle4
+ ? Theme.of(context)
+ .extension<StackColors>()!
+ .textSubtitle4
: Theme.of(context)
.extension<StackColors>()!
.infoItemIcons
@@ -168,12 +142,12 @@ class NodeOptionsSheet extends ConsumerWidget {
node.id.startsWith(
DefaultNodes.defaultNodeIdPrefix,
)
- ? Theme.of(
- context,
- ).extension<StackColors>()!.accentColorDark
- : Theme.of(
- context,
- ).extension<StackColors>()!.infoItemIcons,
+ ? Theme.of(context)
+ .extension<StackColors>()!
+ .accentColorDark
+ : Theme.of(context)
+ .extension<StackColors>()!
+ .infoItemIcons,
),
),
),
@@ -193,12 +167,12 @@ class NodeOptionsSheet extends ConsumerWidget {
SvgPicture.asset(
Assets.svg.network,
color: status == "Connected"
- ? Theme.of(
- context,
- ).extension<StackColors>()!.accentColorGreen
- : Theme.of(
- context,
- ).extension<StackColors>()!.buttonBackSecondary,
+ ? Theme.of(context)
+ .extension<StackColors>()!
+ .accentColorGreen
+ : Theme.of(context)
+ .extension<StackColors>()!
+ .buttonBackSecondary,
width: 18,
),
],
@@ -222,9 +196,9 @@ class NodeOptionsSheet extends ConsumerWidget {
child: Text(
"Details",
style: STextStyles.button(context).copyWith(
- color: Theme.of(
- context,
- ).extension<StackColors>()!.accentColorDark,
+ color: Theme.of(context)
+ .extension<StackColors>()!
+ .accentColorDark,
),
),
),
@@ -243,50 +217,57 @@ class NodeOptionsSheet extends ConsumerWidget {
onPressed: status == "Connected"
? null
: () async {
- final pw = await node.getPassword(
- ref.read(secureStoreProvider),
- );
- if (context.mounted) {
- final TorPlainNetworkOption netOption;
- if (node.torEnabled &&
- !node.clearnetEnabled) {
- netOption = TorPlainNetworkOption.tor;
- } else if (node.clearnetEnabled &&
- !node.torEnabled) {
- netOption = TorPlainNetworkOption.clear;
- } else {
- netOption = TorPlainNetworkOption.both;
- }
- final canConnect =
- await ref.read(
- testNodeConnectionProvider,
- )(
- context: context,
- nodeFormData: NodeFormData()
- ..name = node.name
- ..host = node.host
- ..login = node.loginName
- ..password = pw
- ..port = node.port
- ..useSSL = node.useSSL
- ..isFailover = node.isFailover
- ..netOption = netOption
- ..trusted = node.trusted,
- cryptoCurrency: coin,
+ // One test at a time, so taps cannot stack
+ // dialogs.
+ if (_connecting) return;
+ _connecting = true;
+ try {
+ // Carry the saved certificate so an approved
+ // node is not reviewed again, and keep a new
+ // approval below.
+ final service = ref.read(
+ nodeServiceChangeNotifierProvider,
+ );
+ final notify = nodeChangeNotifier(ref, coin);
+ final nodeFormData = NodeFormData.fromNode(
+ node,
+ );
+ nodeFormData.password = await node
+ .getPassword(
+ ref.read(secureStoreProvider),
);
- if (!canConnect) {
- return;
- }
+ if (context.mounted) {
+ final canConnect =
+ await ref.read(
+ testNodeConnectionProvider,
+ )(
+ context: context,
+ nodeFormData: nodeFormData,
+ cryptoCurrency: coin,
+ );
+ if (!canConnect) {
+ return;
+ }
- await ref
- .read(nodeServiceChangeNotifierProvider)
- .setPrimaryNodeFor(
- coin: coin,
- node: node,
- shouldNotifyListeners: true,
+ if (await service.commitConnectionTest(
+ node: node,
+ formData: nodeFormData,
+ )) {
+ await notify();
+ } else if (context.mounted) {
+ unawaited(
+ showFloatingFlushBar(
+ type: FlushBarType.warning,
+ message:
+ "The node changed during the "
+ "test. Please try again.",
+ context: context,
+ ),
);
-
- await _notifyWalletsOfUpdatedNode(ref);
+ }
+ }
+ } finally {
+ _connecting = false;
}
},
child: Text(
### lib/widgets/tls_certificate_dialog.dart
@@ -0,0 +1,40 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+
+import '../utilities/tls_certificate.dart';
+import 'desktop/primary_button.dart';
+import 'desktop/secondary_button.dart';
+import 'stack_dialog.dart';
+
+Future<bool> showBadX509CertificateDialog(
+ X509Certificate cert,
+ String host,
+ int port,
+ BuildContext context,
+) async {
+ final result = await showDialog<bool>(
+ context: context,
+ barrierDismissible: false,
+ builder: (context) => StackDialog(
+ title: 'Untrusted TLS certificate',
+ width: 520,
+ message:
+ 'Server: $host:$port\n\n'
+ 'Subject: ${cert.subject}\n'
+ 'Issuer: ${cert.issuer}\n\n'
+ 'Valid from: ${cert.startValidity.toUtc()}\n'
+ 'Valid until: ${cert.endValidity.toUtc()}\n\n'
+ 'SHA-256:\n${certificateFingerprint(cert.der)}',
+ leftButton: SecondaryButton(
+ label: 'Cancel',
+ onPressed: () => Navigator.of(context).pop(false),
+ ),
+ rightButton: PrimaryButton(
+ label: 'Trust',
+ onPressed: () => Navigator.of(context).pop(true),
+ ),
+ ),
+ );
+ return result ?? false;
+}
### pubspec.lock
@@ -921,11 +921,11 @@ packages:
dependency: "direct main"
description:
path: "."
- ref: "76ffad6ecc1e31de47d9187fd39c831db0aa987f"
- resolved-ref: "76ffad6ecc1e31de47d9187fd39c831db0aa987f"
+ ref: b0d8a16c8a4d6976bd0f1f98723e222706cc567c
+ resolved-ref: b0d8a16c8a4d6976bd0f1f98723e222706cc567c
url: "https://github.com/cypherstack/electrum_adapter.git"
source: git
- version: "4.0.1"
+ version: "5.0.0"
emojis:
dependency: "direct main"
description:
@@ -2183,10 +2183,10 @@ packages:
dependency: "direct main"
description:
name: socks_socket
- sha256: "09149ed1278584554aeacc60c7aeec5bd80154e6ce1136f00d97485d09d5a338"
+ sha256: "536e0876f94d878c09d0673d69d20f61894becce4476f0abd45a50a2ff387cf9"
url: "https://pub.dev"
source: hosted
- version: "2.0.0"
+ version: "2.1.0"
solana:
dependency: "direct main"
description:
### scripts/app_config/templates/pubspec.template.yaml
@@ -231,7 +231,7 @@ dependencies:
electrum_adapter:
git:
url: https://github.com/cypherstack/electrum_adapter.git
- ref: 76ffad6ecc1e31de47d9187fd39c831db0aa987f
+ ref: b0d8a16c8a4d6976bd0f1f98723e222706cc567c # v5.0.0
stream_channel: ^2.1.0
solana:
git: # TODO [prio=low]: Revert to official package once Tor support is merged upstream.
### test/electrumx_deadline_test.dart
@@ -0,0 +1,205 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:event_bus/event_bus.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:logger/logger.dart' show Level;
+import 'package:mockito/mockito.dart';
+import 'package:stackwallet/electrumx_rpc/electrumx_client.dart';
+import 'package:stackwallet/services/event_bus/events/global/tor_connection_status_changed_event.dart';
+import 'package:stackwallet/services/tor_service.dart';
+import 'package:stackwallet/utilities/logger.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/utilities/tor_plain_net_option_enum.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+
+import 'utilities/tls_test_server.dart';
+
+class _Prefs extends Mock implements Prefs {
+ _Prefs({this.useTor = false});
+ @override
+ final bool useTor;
+ @override
+ bool get wifiOnly => false;
+ @override
+ bool get torKillSwitch => true;
+}
+
+class _Tor extends Mock implements TorService {
+ _Tor(this.proxy);
+ final ({InternetAddress host, int port})? proxy;
+ @override
+ TorConnectionStatus get status => TorConnectionStatus.connected;
+ @override
+ ({InternetAddress host, int port}) getProxyInfo() => proxy!;
+}
+
+Future<void> _until(bool Function() ready) async {
+ final watch = Stopwatch()..start();
+ while (!ready()) {
+ if (watch.elapsed > const Duration(seconds: 2)) {
+ throw TimeoutException('Waiting for test server');
+ }
+ await Future<void>.delayed(const Duration(milliseconds: 5));
+ }
+}
+
+void main() {
+ late Directory logDirectory;
+ late EventBus bus;
+ setUpAll(() async {
+ logDirectory = await Directory.systemTemp.createTemp('electrum_deadlines');
+ await Logging.instance.initialize(logDirectory.path, level: Level.off);
+ });
+ tearDownAll(() => logDirectory.delete(recursive: true));
+ setUp(() => bus = EventBus());
+ // Each client closes itself through addTearDown in clientFor.
+ tearDown(() => bus.destroy());
+
+ Future<TlsElectrumServer> start({
+ bool stallHandshake = false,
+ Set<String> ignoredMethods = const {},
+ }) async {
+ final server = await TlsElectrumServer.start(
+ stallHandshake: stallHandshake,
+ ignoredMethods: ignoredMethods,
+ );
+ addTearDown(server.close);
+ return server;
+ }
+
+ ElectrumXClient clientFor(
+ TlsElectrumServer server, {
+ CryptoCurrency? coin,
+ ({InternetAddress host, int port})? proxy,
+ Duration connectionTimeout = const Duration(seconds: 2),
+ }) {
+ final client = ElectrumXClient(
+ host: proxy == null ? '127.0.0.1' : 'deadline.test.onion',
+ port: server.port,
+ useSSL: true,
+ trustedCertificatePem: TlsElectrumServer.certificate('node_a'),
+ cryptoCurrency: coin ?? Bitcoin(CryptoCurrencyNetwork.main),
+ prefs: _Prefs(useTor: proxy != null),
+ torService: _Tor(proxy),
+ netType: TorPlainNetworkOption.both,
+ globalEventBusForTesting: bus,
+ connectionTimeoutForSpecialCaseJsonRPCClients: connectionTimeout,
+ failovers: [],
+ );
+ addTearDown(client.closeAdapter);
+ return client;
+ }
+
+ for (final proxied in [false, true]) {
+ final route = proxied ? 'SOCKS TLS' : 'direct TLS';
+ for (final stallHandshake in [true, false]) {
+ final phase = stallHandshake ? 'TLS handshake' : 'server.version';
+ test('$route releases a stalled $phase', () async {
+ final server = await start(
+ stallHandshake: stallHandshake,
+ ignoredMethods: {'server.version'},
+ );
+ final proxy = proxied ? await TlsTestProxy.start(server.port) : null;
+ if (proxy != null) addTearDown(proxy.close);
+ final client = clientFor(
+ server,
+ proxy: proxy?.info,
+ connectionTimeout: const Duration(milliseconds: 200),
+ );
+
+ await expectLater(
+ client.checkElectrumAdapter().timeout(const Duration(seconds: 3)),
+ throwsA(isA<TimeoutException>()),
+ );
+ expect(client.getElectrumAdapter(), isNull);
+ await _until(() => server.disconnections == 1);
+ expect(server.accepted, 1);
+ });
+ }
+ }
+
+ for (final coin in [
+ Bitcoin(CryptoCurrencyNetwork.main),
+ Firo(CryptoCurrencyNetwork.main),
+ ]) {
+ test('${coin.runtimeType} RPC timeout closes and reconnects', () async {
+ final server = await start(ignoredMethods: {'probe.silent'});
+ final client = clientFor(server, coin: coin);
+ await client.request(command: 'probe.ready');
+ final original = client.getElectrumAdapter()!;
+
+ await expectLater(
+ client
+ .request(
+ command: 'probe.silent',
+ requestTimeout: const Duration(milliseconds: 150),
+ )
+ .timeout(const Duration(seconds: 3)),
+ throwsA(isA<TimeoutException>()),
+ );
+ expect(original.peer.isClosed, true);
+ await _until(() => server.disconnections == 1);
+ expect(await client.request(command: 'probe.ready'), isEmpty);
+ expect(client.getElectrumAdapter(), isNot(same(original)));
+ expect(server.accepted, 2);
+ expect(server.methods.where((m) => m == 'probe.silent').length, 1);
+ });
+ }
+
+ test(
+ 'batch members use the caller timeout and close a silent peer',
+ () async {
+ final server = await start(ignoredMethods: {'probe.silent'});
+ final client = clientFor(server);
+ await client.request(command: 'probe.ready');
+ final original = client.getElectrumAdapter()!;
+
+ await expectLater(
+ client
+ .batchRequest(
+ command: 'probe.silent',
+ args: [
+ [1],
+ [2],
+ ],
+ requestTimeout: const Duration(milliseconds: 150),
+ )
+ .timeout(const Duration(seconds: 3)),
+ throwsA(isA<TimeoutException>()),
+ );
+ expect(original.peer.isClosed, true);
+ await _until(() => server.disconnections == 1);
+ expect(server.methods.where((m) => m == 'probe.silent').length, 2);
+ expect(await client.request(command: 'probe.ready'), isEmpty);
+ },
+ );
+
+ test('batch replies preserve the request order and arguments', () async {
+ final server = await start();
+ final client = clientFor(server);
+ expect(
+ await client.batchRequest(
+ command: 'blockchain.transaction.get',
+ args: [
+ ['first', true],
+ ['second', true],
+ ],
+ ),
+ [
+ {'txid': 'first', 'confirmations': 3},
+ {'txid': 'second', 'confirmations': 3},
+ ],
+ );
+ });
+
+ test('an empty batch sends no requests and opens no connection', () async {
+ final server = await start();
+ final client = clientFor(server);
+ expect(
+ await client.batchRequest(command: 'probe.empty', args: []),
+ isEmpty,
+ );
+ expect(server.accepted, 0);
+ });
+}
### test/electrumx_duplicate_endpoint_test.dart
@@ -0,0 +1,119 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:event_bus/event_bus.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:logger/logger.dart' show Level;
+import 'package:mockito/mockito.dart';
+import 'package:stackwallet/electrumx_rpc/electrumx_client.dart';
+import 'package:stackwallet/services/tor_service.dart';
+import 'package:stackwallet/utilities/logger.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/utilities/tor_plain_net_option_enum.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+
+import 'utilities/tls_test_server.dart';
+
+class _Prefs extends Mock implements Prefs {
+ @override
+ bool get useTor => false;
+ @override
+ bool get wifiOnly => false;
+}
+
+class _Tor extends Mock implements TorService {}
+
+void main() {
+ test('repeated requests can keep an approved duplicate-endpoint failover', () async {
+ final logs = await Directory.systemTemp.createTemp('duplicate_endpoint');
+ await Logging.instance.initialize(logs.path, level: Level.off);
+ final listener = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ final sockets = <Socket>[];
+ int accepted = 0;
+ addTearDown(() async {
+ for (final s in sockets) {
+ s.destroy();
+ }
+ await listener.close();
+ await logs.delete(recursive: true);
+ });
+ listener.listen((raw) async {
+ final first = ++accepted == 1;
+ sockets.add(raw);
+ raw.done.ignore();
+ final name = first ? 'node_a' : 'node_b';
+ final context = SecurityContext()
+ ..useCertificateChainBytes(
+ utf8.encode(TlsElectrumServer.certificate(name)),
+ )
+ ..usePrivateKeyBytes(
+ File('test/fixtures/tls/$name.key.pem').readAsBytesSync(),
+ );
+ try {
+ final socket = await SecureSocket.secureServer(raw, context);
+ sockets.add(socket);
+ socket.done.ignore();
+ socket
+ .cast<List<int>>()
+ .transform(utf8.decoder)
+ .transform(const LineSplitter())
+ .listen((line) {
+ final request = jsonDecode(line) as Map<String, dynamic>;
+ final method = request['method'];
+ final Object? result = switch (method) {
+ 'server.version' => ['test', '1.4'],
+ 'blockchain.headers.subscribe' => {
+ 'height': 100,
+ 'hex': '00' * 80,
+ },
+ 'probe' =>
+ first ? {'error': 'retry at failover'} : {'via': 'B'},
+ _ => null,
+ };
+ socket.write(
+ '${jsonEncode({'jsonrpc': '2.0', 'id': request['id'], 'result': result})}\n',
+ );
+ }, onError: (Object _) {});
+ } catch (_) {
+ raw.destroy();
+ }
+ });
+ final bus = EventBus();
+ addTearDown(bus.destroy);
+ final connection = ElectrumXClient(
+ host: '127.0.0.1',
+ port: listener.port,
+ useSSL: true,
+ prefs: _Prefs(),
+ netType: TorPlainNetworkOption.both,
+ cryptoCurrency: Bitcoin(CryptoCurrencyNetwork.main),
+ torService: _Tor(),
+ globalEventBusForTesting: bus,
+ trustedCertificatePem: TlsElectrumServer.certificate('node_a'),
+ connectionTimeoutForSpecialCaseJsonRPCClients: const Duration(seconds: 2),
+ failovers: [
+ ElectrumXNode(
+ address: '127.0.0.1',
+ port: listener.port,
+ name: 'B',
+ id: 'B',
+ useSSL: true,
+ torEnabled: true,
+ clearnetEnabled: true,
+ trustedCertificatePem: TlsElectrumServer.certificate('node_b'),
+ ),
+ ],
+ );
+ addTearDown(connection.closeAdapter);
+ expect(await connection.request(command: 'probe'), {'via': 'B'});
+ expect(connection.currentFailoverIndex, -1);
+ final selected = connection.getElectrumAdapter();
+ final next = await connection.ping().then<Object?>(
+ (value) => value,
+ onError: (Object e) => e,
+ );
+ expect(next, true);
+ expect(connection.getElectrumAdapter(), same(selected));
+ });
+}
### test/electrumx_failover_test.dart
@@ -0,0 +1,575 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:event_bus/event_bus.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:logger/logger.dart' show Level;
+import 'package:mockito/mockito.dart';
+import 'package:stackwallet/electrumx_rpc/electrumx_client.dart';
+import 'package:stackwallet/services/tor_service.dart';
+import 'package:stackwallet/utilities/logger.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+
+import 'utilities/tls_test_server.dart';
+
+class _Prefs extends Mock implements Prefs {
+ @override
+ bool get useTor => false;
+ @override
+ bool get wifiOnly => false;
+ @override
+ bool get torKillSwitch => false;
+}
+
+class _Tor extends Mock implements TorService {}
+
+class _RpcServer {
+ _RpcServer(this.server);
+ final ServerSocket server;
+ final sockets = <Socket>[];
+ final ready = Completer<void>();
+ int pending = 0;
+ int requests = 0;
+ void Function()? fail;
+ int get port => server.port;
+
+ static Future<_RpcServer> start({
+ required bool batch,
+ bool holdRequests = true,
+ }) async {
+ final primary = _RpcServer(
+ await ServerSocket.bind(InternetAddress.loopbackIPv4, 0),
+ );
+ primary.server.listen((socket) {
+ primary.sockets.add(socket);
+ socket.done.ignore();
+ socket
+ .cast<List<int>>()
+ .transform(utf8.decoder)
+ .transform(const LineSplitter())
+ .listen((line) {
+ final decoded = jsonDecode(line);
+ for (final request in decoded is List ? decoded : [decoded]) {
+ primary.requests++;
+ if (holdRequests &&
+ (request['method'] == 'probe.a' ||
+ request['method'] == 'probe.b')) {
+ primary.pending++;
+ if (request['method'] == 'probe.a') {
+ primary.fail = () {
+ final reply = batch
+ ? {
+ 'jsonrpc': '2.0',
+ 'id': request['id'],
+ 'error': {
+ 'code': -32000,
+ 'message': 'temporary failure',
+ },
+ }
+ : {
+ 'jsonrpc': '2.0',
+ 'id': request['id'],
+ 'result': {'error': 'temporary failure'},
+ };
+ socket.write('${jsonEncode(batch ? [reply] : reply)}\n');
+ };
+ }
+ if (primary.pending == 2) primary.ready.complete();
+ } else {
+ final Object result = switch (request['method']) {
+ 'server.version' => ['test', '1.4'],
+ 'blockchain.headers.subscribe' => {
+ 'height': 100,
+ 'hex': '00' * 80,
+ },
+ _ => {},
+ };
+ final reply = {
+ 'jsonrpc': '2.0',
+ 'id': request['id'],
+ 'result': result,
+ };
+ socket.write(
+ '${jsonEncode(decoded is List ? [reply] : reply)}\n',
+ );
+ }
+ }
+ }, onError: (Object _) {});
+ });
+ return primary;
+ }
+
+ Future<void> close() async {
+ for (final socket in sockets) {
+ socket.destroy();
+ }
+ await server.close();
+ }
+}
+
+class _Rpc {
+ _Rpc(this.socket, this.message);
+ final Socket socket;
+ final Map<String, dynamic> message;
+ String get method => message['method'] as String;
+ void reply(Object? value) => socket.write(
+ '${jsonEncode({'jsonrpc': '2.0', 'id': message['id'], 'result': value})}\n',
+ );
+}
+
+/// A plain JSON-RPC server for the publication-selection regression. It
+/// answers header subscriptions, optionally auto-answers server.version, and
+/// hands every request to [onRequest] so a test can error or hold it.
+class _PubServer {
+ _PubServer(this.listener, this.autoVersion);
+ final ServerSocket listener;
+ final bool autoVersion;
+ final sockets = <Socket>[];
+ final requests = <_Rpc>[];
+ void Function(_Rpc)? onRequest;
+ int get port => listener.port;
+ List<_Rpc> get versions =>
+ requests.where((e) => e.method == 'server.version').toList();
+
+ static Future<_PubServer> start({bool autoVersion = false}) async {
+ final server = _PubServer(
+ await ServerSocket.bind(InternetAddress.loopbackIPv4, 0),
+ autoVersion,
+ );
+ server.listener.listen((socket) {
+ server.sockets.add(socket);
+ socket.done.ignore();
+ socket
+ .cast<List<int>>()
+ .transform(utf8.decoder)
+ .transform(const LineSplitter())
+ .listen((line) {
+ final decoded = jsonDecode(line);
+ for (final message in decoded is List ? decoded : [decoded]) {
+ final rpc = _Rpc(socket, message as Map<String, dynamic>);
+ server.requests.add(rpc);
+ if (rpc.method == 'blockchain.headers.subscribe') {
+ rpc.reply({'height': 100, 'hex': '00' * 80});
+ } else if (rpc.method == 'server.version' && autoVersion) {
+ rpc.reply(['test', '1.4']);
+ }
+ server.onRequest?.call(rpc);
+ }
+ }, onError: (Object _) {});
+ });
+ return server;
+ }
+
+ Future<void> close() async {
+ for (final socket in sockets) {
+ socket.destroy();
+ }
+ await listener.close();
+ }
+}
+
+Future<void> _until(bool Function() ready) async {
+ final deadline = DateTime.now().add(const Duration(seconds: 3));
+ while (!ready()) {
+ if (DateTime.now().isAfter(deadline)) {
+ throw TimeoutException('probe synchronization');
+ }
+ await Future<void>.delayed(const Duration(milliseconds: 5));
+ }
+}
+
+void main() {
+ late Directory logDirectory;
+ setUpAll(() async {
+ logDirectory = await Directory.systemTemp.createTemp('electrumx_failover');
+ await Logging.instance.initialize(logDirectory.path, level: Level.off);
+ });
+ tearDownAll(() => logDirectory.delete(recursive: true));
+ final coin = Bitcoin(CryptoCurrencyNetwork.main);
+ final servers = <TlsElectrumServer>[];
+ late EventBus bus;
+
+ final clients = <ElectrumXClient>[];
+ setUp(() => bus = EventBus());
+ tearDown(() async {
+ for (final client in clients) {
+ await client.closeAdapter();
+ }
+ clients.clear();
+ bus.destroy();
+ for (final server in servers) {
+ await server.close();
+ }
+ servers.clear();
+ });
+
+ Future<TlsElectrumServer> startPlain() async {
+ final server = await TlsElectrumServer.start(certificateName: null);
+ servers.add(server);
+ return server;
+ }
+
+ /// A port nothing listens on.
+ Future<int> deadPort() async {
+ final socket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ final port = socket.port;
+ await socket.close();
+ return port;
+ }
+
+ ElectrumXNode node(int port, String id) => ElectrumXNode(
+ address: '127.0.0.1',
+ port: port,
+ name: id,
+ id: id,
+ useSSL: false,
+ torEnabled: true,
+ clearnetEnabled: true,
+ );
+
+ ElectrumXClient client(
+ ElectrumXNode primary, {
+ List<ElectrumXNode> failovers = const [],
+ CryptoCurrency? currency,
+ }) {
+ final client = ElectrumXClient.from(
+ node: primary,
+ prefs: _Prefs(),
+ torService: _Tor(),
+ failovers: failovers,
+ cryptoCurrency: currency ?? coin,
+ globalEventBusForTesting: bus,
+ );
+ clients.add(client);
+ return client;
+ }
+
+ for (final currency in [coin, Firo(CryptoCurrencyNetwork.main)]) {
+ for (final timeout in [false, true]) {
+ test('${currency.runtimeType} failover preserves its own pending work '
+ '(timeout=$timeout)', () async {
+ final primary = await _PubServer.start(autoVersion: true);
+ final fallback = await _PubServer.start(autoVersion: true);
+ addTearDown(primary.close);
+ addTearDown(fallback.close);
+ primary.onRequest = (rpc) {
+ if (rpc.method == 'probe' && !timeout) {
+ rpc.reply({'error': 'try the fallback'});
+ }
+ };
+ fallback.onRequest = (rpc) {
+ if (rpc.method == 'probe') rpc.reply({'via': 'fallback'});
+ };
+ final actor = client(
+ node(primary.port, 'primary'),
+ currency: currency,
+ failovers: [node(fallback.port, 'fallback')],
+ );
+ await actor.checkElectrumAdapter();
+ final previous = actor.getElectrumAdapter()!;
+ final pending = actor
+ .getTransaction(txHash: 'a' * 64)
+ .then<Object?>((value) => value, onError: (Object e) => e);
+ await _until(
+ () => primary.requests.any(
+ (r) => r.method == 'blockchain.transaction.get',
+ ),
+ );
+
+ expect(
+ await actor.request(
+ command: 'probe',
+ requestTimeout: const Duration(milliseconds: 150),
+ ),
+ {'via': 'fallback'},
+ );
+ expect(actor.getElectrumAdapter()!.port, fallback.port);
+ expect(previous.peer.isClosed, false);
+ primary.requests
+ .singleWhere((r) => r.method == 'blockchain.transaction.get')
+ .reply({'confirmations': 7});
+ expect(await pending, {'confirmations': 7});
+ await _until(() => previous.peer.isClosed);
+ });
+ }
+ }
+
+ test(
+ 'requests after a successful failover request stay on the failover',
+ () async {
+ final failover = await startPlain();
+ final connection = client(
+ node(await deadPort(), 'primary'),
+ failovers: [node(failover.port, 'failover')],
+ );
+ connection.currentFailoverIndex = 0;
+ // A successful request resets the failover index to the primary.
+ expect(await connection.ping(), true);
+ expect(connection.currentFailoverIndex, -1);
+ final result = await connection.getTransaction(txHash: 'a' * 64);
+ expect(result['confirmations'], 3);
+ expect(connection.getElectrumAdapter()!.port, failover.port);
+ // server.version, ping, transaction.get: one session.
+ expect(failover.requests, 3);
+ expect(failover.disconnections, 0);
+ },
+ );
+
+ test('a draining connection closes when its last RPC times out', () async {
+ final primary = await _PubServer.start(autoVersion: true);
+ final fallback = await _PubServer.start(autoVersion: true);
+ addTearDown(primary.close);
+ addTearDown(fallback.close);
+ final connection = client(
+ node(primary.port, 'primary'),
+ failovers: [node(fallback.port, 'fallback')],
+ );
+ await connection.checkElectrumAdapter();
+ final previous = connection.getElectrumAdapter()!;
+ final pending = previous
+ .requestWithTimeout(
+ 'probe.held',
+ timeout: const Duration(milliseconds: 300),
+ )
+ .then<Object?>((value) => value, onError: (Object e) => e);
+ await _until(() => primary.requests.any((r) => r.method == 'probe.held'));
+ // Received traffic makes this an individual timeout: the adapter itself
+ // would leave the transport alive, so retirement must finish the cleanup.
+ await previous.request('server.version');
+ connection.currentFailoverIndex = 0;
+ await connection.checkElectrumAdapter();
+ expect(previous.peer.isClosed, false);
+ expect(await pending, isA<TimeoutException>());
+ await _until(() => previous.peer.isClosed);
+ expect(connection.getElectrumAdapter()!.port, fallback.port);
+ });
+
+ for (final primaryShadows in [false, true]) {
+ test(
+ 'duplicate endpoint approvals do not hide a successful ${primaryShadows ? 'primary' : 'failover'} fallback',
+ () async {
+ final server = await TlsElectrumServer.start(certificateName: 'node_b');
+ servers.add(server);
+ final a = TlsElectrumServer.certificate('node_a');
+ final b = TlsElectrumServer.certificate('node_b');
+ ElectrumXNode approved(String id, String pem) => ElectrumXNode(
+ address: '127.0.0.1',
+ port: server.port,
+ name: id,
+ id: id,
+ useSSL: true,
+ torEnabled: true,
+ clearnetEnabled: true,
+ trustedCertificatePem: pem,
+ );
+ final connection = client(
+ primaryShadows
+ ? approved('primary', a)
+ : node(await deadPort(), 'primary'),
+ failovers: [
+ if (!primaryShadows) approved('old approval', a),
+ approved('selected', b),
+ ],
+ );
+ addTearDown(connection.closeAdapter);
+ connection.currentFailoverIndex = primaryShadows ? 0 : 1;
+ expect(await connection.ping(), true);
+ final selected = connection.getElectrumAdapter();
+ expect(connection.currentFailoverIndex, -1);
+ expect(
+ (await connection.getTransaction(txHash: 'a' * 64))['confirmations'],
+ 3,
+ );
+ expect(connection.getElectrumAdapter(), same(selected));
+ expect(server.accepted, 1);
+ expect(server.disconnections, 0);
+ },
+ );
+ }
+
+ test("a failover to another owner's node opens its own connection", () async {
+ // A failover endpoint that answers setup and holds one request.
+ final listener = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ final sockets = <Socket>[];
+ var accepted = 0;
+ void Function()? release;
+ final held = Completer<void>();
+ listener.listen((socket) {
+ accepted++;
+ sockets.add(socket);
+ socket.done.ignore();
+ socket
+ .cast<List<int>>()
+ .transform(utf8.decoder)
+ .transform(const LineSplitter())
+ .listen((line) {
+ final request = jsonDecode(line) as Map<String, dynamic>;
+ void reply(Object? result) => socket.write(
+ '${jsonEncode({'jsonrpc': '2.0', 'id': request['id'], 'result': result})}\n',
+ );
+ switch (request['method']) {
+ case 'blockchain.transaction.get':
+ release = () => reply({'confirmations': 7});
+ if (!held.isCompleted) held.complete();
+ case 'blockchain.headers.subscribe':
+ reply({'height': 100, 'hex': '00' * 80});
+ default:
+ reply(['test', '1.4']);
+ }
+ }, onError: (Object _) {});
+ });
+ addTearDown(() async {
+ for (final socket in sockets) {
+ socket.destroy();
+ }
+ await listener.close();
+ });
+ final dead = await deadPort();
+ final failoverNode = node(listener.port, 'failover');
+ final w1 = client(node(dead, 'primary'), failovers: [failoverNode]);
+ final w2 = client(node(dead, 'primary'), failovers: [failoverNode]);
+
+ // W1 has already failed over to the shared node and is healthy on it.
+ w1.currentFailoverIndex = 0;
+ expect(await w1.ping(), true);
+ expect(w1.currentFailoverIndex, -1);
+ final shared = w1.getElectrumAdapter()!;
+
+ // W1 keeps a request in flight on its connection.
+ final inflight = w1.getTransaction(txHash: 'a' * 64);
+ await held.future.timeout(const Duration(seconds: 2));
+
+ // W2's primary is also dead; its failover retry selects the same node.
+ w2.currentFailoverIndex = 0;
+ await w2.checkElectrumAdapter();
+ expect(w2.getElectrumAdapter()!.port, listener.port);
+ expect(
+ w2.getElectrumAdapter(),
+ isNot(same(shared)),
+ reason: 'each owner connects for itself',
+ );
+ expect(accepted, 2);
+ expect(
+ shared.peer.isClosed,
+ false,
+ reason: "another owner's connection must not be closed",
+ );
+
+ // W2 closing cannot affect W1's in-flight request either.
+ await w2.closeAdapter();
+ release!();
+ expect(
+ (await inflight.timeout(const Duration(seconds: 2)))['confirmations'],
+ 7,
+ reason: "W1's in-flight RPC is not cut off",
+ );
+ });
+
+ test(
+ "another owner's primary connection cannot change the selected fallback",
+ () async {
+ final primary = await _PubServer.start(autoVersion: true);
+ final fallback = await _PubServer.start();
+ addTearDown(primary.close);
+ addTearDown(fallback.close);
+ primary.onRequest = (rpc) {
+ if (rpc.method == 'probe') rpc.reply({'error': 'primary unavailable'});
+ };
+ fallback.onRequest = (rpc) {
+ if (rpc.method == 'probe') rpc.reply({'via': 'fallback'});
+ };
+ final first = client(
+ node(primary.port, 'primary'),
+ failovers: [node(fallback.port, 'fallback')],
+ );
+ final second = client(
+ node(primary.port, 'primary'),
+ failovers: [node(fallback.port, 'fallback')],
+ );
+ final pending = first
+ .request(command: 'probe')
+ .then<Object?>((value) => value, onError: (Object e) => e);
+ await _until(() => fallback.versions.isNotEmpty);
+ // The second owner connects to the primary while the fallback waits.
+ await second.checkElectrumAdapter();
+ expect(second.getElectrumAdapter()!.port, primary.port);
+ final secondPrimary = second.getElectrumAdapter()!;
+ final reading = second
+ .getTransaction(txHash: 'a' * 64)
+ .then<Object?>((value) => value, onError: (Object e) => e);
+ await _until(
+ () => primary.requests.any(
+ (rpc) => rpc.method == 'blockchain.transaction.get',
+ ),
+ );
+ fallback.versions.single.reply(['test', '1.4']);
+ final result = await pending.timeout(const Duration(seconds: 4));
+ expect(result, {
+ 'via': 'fallback',
+ }, reason: 'the selected fallback must serve the retry, not the primary');
+ expect(first.getElectrumAdapter()!.port, fallback.port);
+ expect(secondPrimary.peer.isClosed, false);
+ primary.requests
+ .singleWhere((rpc) => rpc.method == 'blockchain.transaction.get')
+ .reply({'confirmations': 7});
+ expect(await reading, {'confirmations': 7});
+ // The second owner keeps its own primary connection.
+ expect(second.getElectrumAdapter(), same(secondPrimary));
+ expect(secondPrimary.peer.isClosed, false);
+ expect(
+ fallback.requests.where((r) => r.method == 'probe').length,
+ 1,
+ reason: 'the probe reaches the healthy fallback',
+ );
+ },
+ );
+ for (final batch in [false, true]) {
+ test(
+ 'failover survives another outstanding RPC closing (batch=$batch)',
+ () async {
+ final primary = await _RpcServer.start(batch: batch);
+ final failover = await _RpcServer.start(
+ batch: batch,
+ holdRequests: false,
+ );
+ addTearDown(failover.close);
+ final connection = client(
+ node(primary.port, 'primary'),
+ failovers: [node(failover.port, 'failover')],
+ );
+ final first =
+ (batch
+ ? connection.batchRequest(
+ command: 'probe.a',
+ args: [
+ ['address'],
+ ],
+ )
+ : connection.request(command: 'probe.a'))
+ .then<Object?>(
+ (value) => value,
+ onError: (Object error) => error,
+ );
+ final other = connection
+ .request(command: 'probe.b')
+ .then<Object?>((value) => value, onError: (Object error) => error);
+ try {
+ await primary.ready.future.timeout(const Duration(seconds: 2));
+ primary.fail!();
+ final result = await first.timeout(const Duration(seconds: 3));
+ expect(
+ result,
+ batch ? isA<List<dynamic>>() : isA<Map<dynamic, dynamic>>(),
+ );
+ expect(failover.requests, greaterThanOrEqualTo(2));
+ } finally {
+ await primary.close();
+ await other.timeout(const Duration(seconds: 3));
+ await connection.closeAdapter();
+ }
+ },
+ );
+ }
+}
### test/electrumx_late_approval_test.dart
@@ -0,0 +1,111 @@
+import 'dart:io';
+
+import 'package:event_bus/event_bus.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:logger/logger.dart' show Level;
+import 'package:mockito/mockito.dart';
+import 'package:stackwallet/electrumx_rpc/electrumx_client.dart';
+import 'package:stackwallet/services/event_bus/events/global/tor_connection_status_changed_event.dart';
+import 'package:stackwallet/services/tor_service.dart';
+import 'package:stackwallet/utilities/logger.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/utilities/tor_plain_net_option_enum.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+
+import 'utilities/tls_test_server.dart';
+
+class _Prefs extends Mock implements Prefs {
+ _Prefs(this.tor);
+ final bool tor;
+ @override
+ bool get useTor => tor;
+ @override
+ bool get wifiOnly => false;
+ @override
+ bool get torKillSwitch => true;
+}
+
+class _Tor extends Mock implements TorService {
+ _Tor(this.proxyInfo);
+ final ({InternetAddress host, int port}) proxyInfo;
+ @override
+ TorConnectionStatus get status => TorConnectionStatus.connected;
+ @override
+ ({InternetAddress host, int port}) getProxyInfo() {
+ return proxyInfo;
+ }
+}
+
+void main() {
+ test(
+ 'late adapter completion cannot republish a retired certificate approval',
+ () async {
+ final logs = await Directory.systemTemp.createTemp(
+ 'tls_only_late_approval',
+ );
+ await Logging.instance.initialize(logs.path, level: Level.off);
+ final oldServer = await TlsElectrumServer.start();
+ final newServer = await TlsElectrumServer.start(certificateName: null);
+ final proxy = await TlsTestProxy.start(
+ oldServer.port,
+ greetingDelay: const Duration(milliseconds: 200),
+ );
+ final tor = _Tor(proxy.info);
+ final coin = Bitcoin(CryptoCurrencyNetwork.main);
+ final bus = EventBus();
+ final oldClient = ElectrumXClient(
+ host: 'old.example',
+ port: oldServer.port,
+ useSSL: true,
+ trustedCertificatePem: TlsElectrumServer.certificate('node_a'),
+ prefs: _Prefs(true),
+ netType: TorPlainNetworkOption.both,
+ failovers: [],
+ cryptoCurrency: coin,
+ torService: tor,
+ globalEventBusForTesting: bus,
+ );
+ final newClient = ElectrumXClient(
+ host: '127.0.0.1',
+ port: newServer.port,
+ useSSL: false,
+ prefs: _Prefs(false),
+ netType: TorPlainNetworkOption.both,
+ failovers: [],
+ cryptoCurrency: coin,
+ torService: tor,
+ globalEventBusForTesting: bus,
+ );
+ addTearDown(() async {
+ await oldClient.closeAdapter();
+ await newClient.closeAdapter();
+ bus.destroy();
+ await proxy.close();
+ await oldServer.close();
+ await newServer.close();
+ await logs.delete(recursive: true);
+ });
+
+ final oldOutcome = oldClient.ping().then<Object?>(
+ (value) => value,
+ onError: (Object error) => error,
+ );
+ // Wait for actual socket setup, not just a proxy-settings lookup. The
+ // connection must finish late to exercise stale approval cleanup.
+ await proxy.connected.future.timeout(const Duration(seconds: 2));
+ await oldClient.closeAdapter();
+ expect(await newClient.ping(), true);
+ final replacement = newClient.getElectrumAdapter();
+ expect(replacement, isNotNull);
+
+ expect(
+ await oldOutcome.timeout(const Duration(seconds: 3)),
+ isA<StateError>(),
+ );
+ expect(proxy.destinations, ['old.example']);
+ expect(oldServer.requests, 0);
+ expect(newClient.getElectrumAdapter(), same(replacement));
+ expect(await newClient.ping(), true);
+ },
+ );
+}
### test/electrumx_request_policy_test.dart
@@ -0,0 +1,656 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:event_bus/event_bus.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:logger/logger.dart' show Level;
+import 'package:mockito/mockito.dart';
+import 'package:stackwallet/electrumx_rpc/electrum_request_timeouts.dart';
+import 'package:stackwallet/electrumx_rpc/electrumx_client.dart';
+import 'package:stackwallet/services/event_bus/events/global/tor_connection_status_changed_event.dart';
+import 'package:stackwallet/services/tor_service.dart';
+import 'package:stackwallet/utilities/logger.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/utilities/tor_plain_net_option_enum.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+
+const _historyMethod = 'blockchain.scripthash.get_history';
+const _broadcastMethod = 'blockchain.transaction.broadcast';
+const _short = Duration(milliseconds: 100);
+const _long = Duration(seconds: 1);
+
+class _Prefs extends Mock implements Prefs {
+ @override
+ bool get useTor => false;
+ @override
+ bool get wifiOnly => false;
+}
+
+class _Tor extends Mock implements TorService {
+ @override
+ TorConnectionStatus get status => TorConnectionStatus.disconnected;
+}
+
+class _ObservedTimeouts extends ElectrumRequestTimeouts {
+ final resolved = <({String method, Duration timeout})>[];
+
+ @override
+ Duration forMethod(String method) {
+ final timeout = super.forMethod(method);
+ resolved.add((method: method, timeout: timeout));
+ return timeout;
+ }
+}
+
+/// Setup and headers reply immediately; application responses take 250ms.
+class _PolicyServer {
+ _PolicyServer(this.listener) {
+ listener.listen((socket) {
+ accepted++;
+ sockets.add(socket);
+ socket
+ .cast<List<int>>()
+ .transform(utf8.decoder)
+ .transform(const LineSplitter())
+ .listen(
+ (line) {
+ final message = jsonDecode(line);
+ final requests = message is List ? message : [message];
+ final responses = <Map<String, dynamic>>[];
+ var delayed = false;
+ for (final dynamic request in requests) {
+ received.add(Map<String, dynamic>.from(request as Map));
+ final method = request['method'] as String;
+ methods.add(method);
+ final Object result;
+ switch (method) {
+ case 'server.version':
+ result = ['policy-test', '1.4'];
+ case 'blockchain.headers.subscribe':
+ result = {'height': 800000, 'hex': '00'};
+ case 'probe.ready':
+ result = <String, dynamic>{};
+ case _historyMethod:
+ delayed = true;
+ result = [
+ {'height': 1, 'tx_hash': request['params'][0]},
+ ];
+ case 'blockchain.transaction.get':
+ delayed = true;
+ result = request['params'][1] == true
+ ? {'txid': request['params'][0]}
+ : 'raw-transaction';
+ case _broadcastMethod:
+ delayed = true;
+ result = 'broadcast-txid';
+ case 'spark.getsparklatestcoinid':
+ case 'lelantus.getlatestcoinid':
+ delayed = true;
+ result = 42;
+ case 'blockchain.getfeerate':
+ delayed = true;
+ result = {'rate': 1000};
+ case 'lelantus.getmintmetadata':
+ delayed = true;
+ result = [
+ {'height': 10, 'groupId': 1},
+ ];
+ case 'lelantus.getanonymityset':
+ case 'spark.getsparkanonymityset':
+ delayed = true;
+ result = {
+ 'blockHash': '00',
+ 'setHash': '00',
+ 'coins': <dynamic>[],
+ };
+ default:
+ delayed = true;
+ result = {'ok': true};
+ }
+ responses.add({
+ 'jsonrpc': '2.0',
+ 'id': request['id'],
+ 'result': result,
+ });
+ }
+ void reply() {
+ if (sockets.contains(socket)) {
+ final payload = message is List
+ ? responses
+ : responses.single;
+ socket.write('${jsonEncode(payload)}\n');
+ }
+ }
+
+ if (delayed) {
+ timers.add(Timer(const Duration(milliseconds: 250), reply));
+ } else {
+ reply();
+ }
+ },
+ onError: (Object _) {},
+ onDone: () => sockets.remove(socket),
+ );
+ });
+ }
+
+ final ServerSocket listener;
+ final sockets = <Socket>[];
+ final timers = <Timer>[];
+ final methods = <String>[];
+ final received = <Map<String, dynamic>>[];
+ int accepted = 0;
+ int get port => listener.port;
+
+ static Future<_PolicyServer> start() async =>
+ _PolicyServer(await ServerSocket.bind(InternetAddress.loopbackIPv4, 0));
+
+ Future<void> close() async {
+ for (final timer in timers) {
+ timer.cancel();
+ }
+ for (final socket in sockets.toList()) {
+ socket.destroy();
+ }
+ sockets.clear();
+ await listener.close();
+ }
+}
+
+Matcher _deadline(Duration duration) => throwsA(
+ isA<TimeoutException>().having(
+ (error) => error.duration,
+ 'deadline',
+ duration,
+ ),
+);
+
+void main() {
+ late Directory logs;
+ late EventBus bus;
+ setUpAll(() async {
+ logs = await Directory.systemTemp.createTemp('electrum_request_policy');
+ await Logging.instance.initialize(logs.path, level: Level.off);
+ });
+ tearDownAll(() => logs.delete(recursive: true));
+ setUp(() => bus = EventBus());
+ // Each client closes itself through addTearDown in clientFor.
+ tearDown(() => bus.destroy());
+
+ Future<_PolicyServer> start() async {
+ final server = await _PolicyServer.start();
+ addTearDown(server.close);
+ return server;
+ }
+
+ ElectrumXClient clientFor(
+ _PolicyServer server, {
+ ElectrumRequestTimeouts policy = const ElectrumRequestTimeouts(),
+ CryptoCurrency? coin,
+ }) {
+ final client = ElectrumXClient(
+ host: '127.0.0.1',
+ port: server.port,
+ useSSL: false,
+ prefs: _Prefs(),
+ torService: _Tor(),
+ netType: TorPlainNetworkOption.both,
+ failovers: [],
+ cryptoCurrency: coin ?? Bitcoin(CryptoCurrencyNetwork.main),
+ globalEventBusForTesting: bus,
+ requestTimeouts: policy,
+ );
+ addTearDown(client.closeAdapter);
+ return client;
+ }
+
+ test(
+ 'default history limit is shared by individual and batch helpers',
+ () async {
+ final server = await start();
+ final policy = _ObservedTimeouts();
+ final client = clientFor(server, policy: policy);
+ expect(policy.standard, const Duration(seconds: 60));
+ expect(policy.history, const Duration(minutes: 5));
+ expect(policy.firoSet, const Duration(hours: 3));
+
+ expect(await client.getHistory(scripthash: 'single'), [
+ {'height': 1, 'tx_hash': 'single'},
+ ]);
+ expect(
+ await client.getBatchHistory(
+ args: [
+ ['batch'],
+ ],
+ ),
+ [
+ [
+ {'height': 1, 'tx_hash': 'batch'},
+ ],
+ ],
+ );
+ expect(policy.resolved, [
+ (method: _historyMethod, timeout: const Duration(minutes: 5)),
+ (method: _historyMethod, timeout: const Duration(minutes: 5)),
+ ]);
+ },
+ );
+
+ test('transaction batches have a separate five-minute default', () {
+ const policy = ElectrumRequestTimeouts();
+ expect(policy.transactionBatch, const Duration(minutes: 5));
+ expect(
+ policy.forMethod('blockchain.transaction.get'),
+ const Duration(seconds: 60),
+ );
+ });
+
+ test(
+ '100 verbose transactions may outlive the single-request deadline',
+ () async {
+ final server = await start();
+ final client = clientFor(
+ server,
+ policy: const ElectrumRequestTimeouts(
+ standard: _short,
+ transactionBatch: _long,
+ ),
+ );
+ final txids = List.generate(100, (index) => 'tx-$index');
+ // The server returns the complete JSON response array after 250ms.
+ // Each member must use the batch budget, not the adapter's short default.
+ expect(await client.getBatchTransactions(txHashes: txids), [
+ for (final txid in txids) {'txid': txid},
+ ]);
+ expect(
+ server.received
+ .where(
+ (request) => request['method'] == 'blockchain.transaction.get',
+ )
+ .map((request) => request['params'])
+ .toList(),
+ [
+ for (final txid in txids) [txid, true],
+ ],
+ );
+ await expectLater(
+ client.getTransaction(txHash: 'single'),
+ _deadline(_short),
+ );
+ },
+ );
+
+ test(
+ 'a configured transaction-batch deadline can be shorter than standard',
+ () async {
+ final server = await start();
+ final client = clientFor(
+ server,
+ policy: const ElectrumRequestTimeouts(
+ standard: _long,
+ transactionBatch: _short,
+ ),
+ );
+ expect(await client.getTransaction(txHash: 'single'), {'txid': 'single'});
+ await expectLater(
+ client.getBatchTransactions(txHashes: ['first', 'second']),
+ _deadline(_short),
+ );
+ },
+ );
+
+ test('transaction-batch policy must be positive', () async {
+ final server = await start();
+ for (final invalid in [Duration.zero, const Duration(milliseconds: -1)]) {
+ expect(
+ () => clientFor(
+ server,
+ policy: ElectrumRequestTimeouts(transactionBatch: invalid),
+ ),
+ throwsArgumentError,
+ );
+ }
+ expect(server.accepted, 0);
+ });
+
+ test('broadcast has its own five-minute default policy', () {
+ const policy = ElectrumRequestTimeouts();
+ expect(policy.broadcast, const Duration(minutes: 5));
+ expect(policy.forMethod(_broadcastMethod), policy.broadcast);
+ expect(policy.standard, const Duration(seconds: 60));
+ expect(policy.history, const Duration(minutes: 5));
+ expect(policy.firoSet, const Duration(hours: 3));
+ });
+
+ for (final generic in [false, true]) {
+ final mode = generic ? 'generic request' : 'broadcast helper';
+ for (final timeout in [_short, _long]) {
+ test('$mode uses the broadcast policy $timeout', () async {
+ final server = await start();
+ final client = clientFor(
+ server,
+ policy: ElectrumRequestTimeouts(
+ standard: timeout == _short ? _long : _short,
+ broadcast: timeout,
+ ),
+ );
+ final result = generic
+ ? client.request(command: _broadcastMethod, args: ['signed-tx'])
+ : client.broadcastTransaction(rawTx: 'signed-tx');
+ if (timeout == _short) {
+ await expectLater(result, _deadline(_short));
+ } else {
+ expect(await result, 'broadcast-txid');
+ }
+ expect(server.accepted, 1);
+ final sent = server.received
+ .where((request) => request['method'] == _broadcastMethod)
+ .single;
+ expect(sent['params'], ['signed-tx']);
+ });
+ }
+ }
+
+ for (final override in [_short, _long]) {
+ test(
+ 'explicit broadcast request timeout overrides policy: $override',
+ () async {
+ final server = await start();
+ final client = clientFor(
+ server,
+ policy: ElectrumRequestTimeouts(
+ standard: _long,
+ broadcast: override == _short ? _long : _short,
+ ),
+ );
+ final result = client.request(
+ command: _broadcastMethod,
+ args: ['signed-tx'],
+ requestTimeout: override,
+ );
+ if (override == _short) {
+ await expectLater(result, _deadline(_short));
+ } else {
+ expect(await result, 'broadcast-txid');
+ }
+ },
+ );
+ }
+
+ test('broadcast policy must be positive', () async {
+ final server = await start();
+ for (final invalid in [Duration.zero, const Duration(milliseconds: -1)]) {
+ expect(
+ () => clientFor(
+ server,
+ policy: ElectrumRequestTimeouts(broadcast: invalid),
+ ),
+ throwsArgumentError,
+ );
+ }
+ expect(server.accepted, 0);
+ });
+
+ test('history helpers share a longer limit than standard requests', () async {
+ final server = await start();
+ final client = clientFor(
+ server,
+ policy: const ElectrumRequestTimeouts(standard: _short, history: _long),
+ );
+ await client.request(command: 'probe.ready');
+
+ final results = await Future.wait([
+ client.getHistory(scripthash: 'single'),
+ client.getBatchHistory(
+ args: [
+ ['batch'],
+ ],
+ ),
+ ]);
+ expect(results, [
+ [
+ {'height': 1, 'tx_hash': 'single'},
+ ],
+ [
+ [
+ {'height': 1, 'tx_hash': 'batch'},
+ ],
+ ],
+ ]);
+ await expectLater(client.request(command: 'probe.slow'), _deadline(_short));
+ });
+
+ for (final batch in [false, true]) {
+ final mode = batch ? 'batch' : 'individual';
+ test('$mode history observes a shorter configured history limit', () async {
+ final server = await start();
+ final client = clientFor(
+ server,
+ policy: const ElectrumRequestTimeouts(standard: _long, history: _short),
+ );
+ await client.request(command: 'probe.ready');
+ await expectLater(
+ batch
+ ? client.getBatchHistory(
+ args: [
+ ['history'],
+ ],
+ )
+ : client.getHistory(scripthash: 'history'),
+ _deadline(_short),
+ );
+ expect(
+ server.methods.where((method) => method == _historyMethod),
+ hasLength(1),
+ );
+ });
+
+ test(
+ '$mode explicit timeout overrides the method policy in either direction',
+ () async {
+ final server = await start();
+ final client = clientFor(
+ server,
+ policy: const ElectrumRequestTimeouts(
+ standard: _long,
+ history: _short,
+ ),
+ );
+ Future<dynamic> history(Duration timeout) => batch
+ ? client.batchRequest(
+ command: _historyMethod,
+ args: [
+ ['history'],
+ ],
+ requestTimeout: timeout,
+ )
+ : client.request(
+ command: _historyMethod,
+ args: ['history'],
+ requestTimeout: timeout,
+ );
+
+ final result = await history(_long);
+ expect(
+ result,
+ batch
+ ? [
+ [
+ {'height': 1, 'tx_hash': 'history'},
+ ],
+ ]
+ : [
+ {'height': 1, 'tx_hash': 'history'},
+ ],
+ );
+ const shorter = Duration(milliseconds: 50);
+ await expectLater(history(shorter), _deadline(shorter));
+ },
+ );
+ }
+
+ test(
+ 'an empty history batch opens no connection or response timer',
+ () async {
+ final server = await start();
+ final client = clientFor(server);
+ expect(await client.getBatchHistory(args: []), isEmpty);
+ expect(server.accepted, 0);
+ expect(server.methods, isEmpty);
+ },
+ );
+
+ for (final verbose in [false, true]) {
+ for (final callerTimeout in [_short, _long]) {
+ test('getTransaction uses its own client timeout $callerTimeout '
+ '(verbose: $verbose)', () async {
+ final server = await start();
+ final coin = Bitcoin(CryptoCurrencyNetwork.main);
+ final owner = clientFor(
+ server,
+ coin: coin,
+ policy: ElectrumRequestTimeouts(
+ standard: callerTimeout == _short ? _long : _short,
+ ),
+ );
+ final caller = clientFor(
+ server,
+ coin: coin,
+ policy: ElectrumRequestTimeouts(standard: callerTimeout),
+ );
+ // Another client of the coin with a different policy has its own
+ // connection; it cannot lend the caller its deadline.
+ await owner.checkElectrumAdapter();
+ await caller.checkElectrumAdapter();
+ expect(
+ caller.getElectrumAdapter(),
+ isNot(same(owner.getElectrumAdapter())),
+ );
+
+ final result = caller.getTransaction(txHash: 'tx', verbose: verbose);
+ if (callerTimeout == _short) {
+ await expectLater(result, _deadline(_short));
+ } else {
+ expect(
+ await result,
+ verbose ? {'txid': 'tx'} : {'rawtx': 'raw-transaction'},
+ );
+ }
+ expect(server.accepted, 2);
+ expect(
+ server.methods.where(
+ (method) => method == 'blockchain.transaction.get',
+ ),
+ hasLength(1),
+ );
+ });
+ }
+ }
+
+ for (final (method, expected) in [
+ ('spark.getsparklatestcoinid', 42),
+ ('blockchain.getfeerate', {'rate': 1000}),
+ ('lelantus.getlatestcoinid', 42),
+ (
+ 'lelantus.getmintmetadata',
+ [
+ {'height': 10, 'groupId': 1},
+ ],
+ ),
+ ]) {
+ for (final callerTimeout in [_short, _long]) {
+ test('$method uses its own client timeout $callerTimeout', () async {
+ final server = await start();
+ final coin = method == 'blockchain.getfeerate'
+ ? Bitcoin(CryptoCurrencyNetwork.main)
+ : Firo(CryptoCurrencyNetwork.main);
+ final owner = clientFor(
+ server,
+ coin: coin,
+ policy: ElectrumRequestTimeouts(
+ standard: callerTimeout == _short ? _long : _short,
+ ),
+ );
+ final caller = clientFor(
+ server,
+ coin: coin,
+ policy: ElectrumRequestTimeouts(standard: callerTimeout),
+ );
+ // Another client of the coin with a different policy has its own
+ // connection; it cannot lend the caller its deadline.
+ await owner.checkElectrumAdapter();
+ await caller.checkElectrumAdapter();
+ expect(
+ caller.getElectrumAdapter(),
+ isNot(same(owner.getElectrumAdapter())),
+ );
+
+ final result = switch (method) {
+ 'spark.getsparklatestcoinid' => caller.getSparkLatestCoinId(),
+ 'blockchain.getfeerate' => caller.getFeeRate(),
+ 'lelantus.getlatestcoinid' => caller.getLelantusLatestCoinId(),
+ 'lelantus.getmintmetadata' => caller.getLelantusMintData(
+ mints: ['mint'],
+ ),
+ _ => throw StateError('Unexpected test method: $method'),
+ };
+ if (callerTimeout == _short) {
+ await expectLater(result, _deadline(_short));
+ } else {
+ expect(await result, expected);
+ }
+ expect(server.accepted, 2);
+ final sent = server.received
+ .where((request) => request['method'] == method)
+ .single;
+ expect(
+ sent['params'],
+ method == 'lelantus.getmintmetadata'
+ ? [
+ ['mint'],
+ ]
+ : null,
+ );
+ });
+ }
+ }
+
+ test('Firo set methods share their configurable policy', () {
+ const policy = ElectrumRequestTimeouts(
+ standard: _short,
+ history: _long,
+ firoSet: Duration(seconds: 2),
+ );
+ for (final method in [
+ 'lelantus.getanonymityset',
+ 'lelantus.getusedcoinserials',
+ 'spark.getusedcoinstags',
+ 'spark.getusedcoinstagstxhashes',
+ 'spark.getsparkanonymityset',
+ 'spark.getsparkanonymitysetsector',
+ ]) {
+ expect(policy.forMethod(method), policy.firoSet, reason: method);
+ }
+ expect(policy.forMethod('lelantus.getlatestcoinid'), _short);
+ expect(policy.forMethod('probe.unknown'), _short);
+ });
+
+ test(
+ 'Firo anonymity helpers pass the longer set policy to the adapter',
+ () async {
+ final server = await start();
+ final client = clientFor(
+ server,
+ coin: Firo(CryptoCurrencyNetwork.main),
+ policy: const ElectrumRequestTimeouts(standard: _short, firoSet: _long),
+ );
+ expect((await client.getLelantusAnonymitySet())['coins'], isEmpty);
+ expect((await client.getSparkAnonymitySet())['coins'], isEmpty);
+ await expectLater(
+ client.request(command: 'probe.slow'),
+ _deadline(_short),
+ );
+ },
+ );
+}
### test/electrumx_setup_failover_test.dart
@@ -0,0 +1,380 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:event_bus/event_bus.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:logger/logger.dart' show Level;
+import 'package:mockito/mockito.dart';
+import 'package:stackwallet/electrumx_rpc/electrumx_client.dart';
+import 'package:stackwallet/services/event_bus/events/global/tor_connection_status_changed_event.dart';
+import 'package:stackwallet/services/tor_service.dart';
+import 'package:stackwallet/utilities/logger.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/utilities/tor_plain_net_option_enum.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+
+import 'utilities/tls_test_server.dart';
+
+class _Prefs extends Mock implements Prefs {
+ _Prefs({this.useTor = false});
+ @override
+ final bool useTor;
+ @override
+ bool get wifiOnly => false;
+ @override
+ bool get torKillSwitch => true;
+}
+
+class _Tor extends Mock implements TorService {
+ @override
+ TorConnectionStatus get status => TorConnectionStatus.disconnected;
+}
+
+Future<void> _until(bool Function() ready) async {
+ final watch = Stopwatch()..start();
+ while (!ready()) {
+ if (watch.elapsed > const Duration(seconds: 3)) {
+ throw TimeoutException('Waiting for setup test server');
+ }
+ await Future<void>.delayed(const Duration(milliseconds: 5));
+ }
+}
+
+void main() {
+ late Directory logDirectory;
+ late EventBus bus;
+ setUpAll(() async {
+ logDirectory = await Directory.systemTemp.createTemp('electrum_setup');
+ await Logging.instance.initialize(logDirectory.path, level: Level.off);
+ });
+ tearDownAll(() => logDirectory.delete(recursive: true));
+ setUp(() => bus = EventBus());
+ // Each client closes itself through addTearDown in clientFor.
+ tearDown(() => bus.destroy());
+
+ Future<TlsElectrumServer> start({
+ String? certificateName,
+ bool stallHandshake = false,
+ bool versionError = false,
+ Set<String> ignoredMethods = const {},
+ }) async {
+ final server = await TlsElectrumServer.start(
+ certificateName: certificateName,
+ stallHandshake: stallHandshake,
+ versionError: versionError,
+ ignoredMethods: ignoredMethods,
+ );
+ addTearDown(server.close);
+ return server;
+ }
+
+ ElectrumXNode node(
+ TlsElectrumServer server, {
+ bool useSSL = false,
+ String? certificateName,
+ }) => ElectrumXNode(
+ address: '127.0.0.1',
+ port: server.port,
+ name: 'setup test',
+ id: '${server.port}',
+ useSSL: useSSL,
+ torEnabled: true,
+ clearnetEnabled: true,
+ trustedCertificatePem: certificateName == null
+ ? null
+ : TlsElectrumServer.certificate(certificateName),
+ );
+
+ ElectrumXClient clientFor(
+ int port,
+ List<ElectrumXNode> failovers, {
+ bool useSSL = false,
+ String? certificateName,
+ bool useTor = false,
+ Duration timeout = const Duration(milliseconds: 200),
+ }) {
+ final client = ElectrumXClient(
+ host: '127.0.0.1',
+ port: port,
+ useSSL: useSSL,
+ trustedCertificatePem: certificateName == null
+ ? null
+ : TlsElectrumServer.certificate(certificateName),
+ cryptoCurrency: Bitcoin(CryptoCurrencyNetwork.main),
+ prefs: _Prefs(useTor: useTor),
+ torService: _Tor(),
+ netType: TorPlainNetworkOption.both,
+ globalEventBusForTesting: bus,
+ connectionTimeoutForSpecialCaseJsonRPCClients: timeout,
+ failovers: failovers,
+ );
+ addTearDown(client.closeAdapter);
+ return client;
+ }
+
+ for (final caller in ['adapter', 'request', 'batch']) {
+ test('$caller reaches a failover after server.version times out', () async {
+ final primary = await start(ignoredMethods: {'server.version'});
+ final fallback = await start();
+ final client = clientFor(primary.port, [node(fallback)]);
+
+ switch (caller) {
+ case 'adapter':
+ await client.checkElectrumAdapter().timeout(
+ const Duration(seconds: 3),
+ );
+ case 'request':
+ expect(
+ await client
+ .request(command: 'probe')
+ .timeout(const Duration(seconds: 3)),
+ isEmpty,
+ );
+ case 'batch':
+ expect(
+ await client
+ .batchRequest(
+ command: 'probe',
+ args: [<dynamic>[], <dynamic>[]],
+ )
+ .timeout(const Duration(seconds: 3)),
+ [<String, dynamic>{}, <String, dynamic>{}],
+ );
+ }
+ expect(client.getElectrumAdapter()!.port, fallback.port);
+ expect(primary.methods, ['server.version']);
+ expect(primary.accepted, 1);
+ expect(fallback.accepted, 1);
+ await _until(() => primary.disconnections == 1);
+ });
+ }
+
+ test('a refused TCP connection reaches a healthy failover', () async {
+ final unused = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ final refusedPort = unused.port;
+ await unused.close();
+ final fallback = await start();
+ final client = clientFor(refusedPort, [node(fallback)]);
+
+ await client.checkElectrumAdapter().timeout(const Duration(seconds: 3));
+
+ expect(client.getElectrumAdapter()!.port, fallback.port);
+ expect(fallback.accepted, 1);
+ });
+
+ test('a server.version RPC rejection reaches a healthy failover', () async {
+ final primary = await start(versionError: true);
+ final fallback = await start();
+ final client = clientFor(primary.port, [node(fallback)]);
+
+ await client.checkElectrumAdapter().timeout(const Duration(seconds: 3));
+
+ expect(client.getElectrumAdapter()!.port, fallback.port);
+ expect(primary.methods, ['server.version']);
+ expect(primary.accepted, 1);
+ expect(fallback.accepted, 1);
+ await _until(() => primary.disconnections == 1);
+ });
+
+ test('TLS setup failovers require each endpoint own approval', () async {
+ final primary = await start(
+ certificateName: 'node_a',
+ stallHandshake: true,
+ );
+ final unapproved = await start(certificateName: 'node_a');
+ final approved = await start(certificateName: 'node_b');
+ final client = clientFor(
+ primary.port,
+ [
+ node(unapproved, useSSL: true),
+ node(approved, useSSL: true, certificateName: 'node_b'),
+ ],
+ useSSL: true,
+ certificateName: 'node_a',
+ );
+
+ await client.checkElectrumAdapter().timeout(const Duration(seconds: 3));
+
+ expect(client.getElectrumAdapter()!.port, approved.port);
+ expect(primary.accepted, 1);
+ expect(primary.requests, 0);
+ expect(unapproved.accepted, 1);
+ expect(unapproved.requests, 0);
+ expect(approved.accepted, 1);
+ await _until(() => primary.disconnections == 1);
+ });
+
+ test(
+ 'setup exhaustion tries each remaining endpoint once and resets selection',
+ () async {
+ final primary = await start(ignoredMethods: {'server.version'});
+ final first = await start(ignoredMethods: {'server.version'});
+ final last = await start(ignoredMethods: {'server.version'});
+ final client = clientFor(primary.port, [node(first), node(last)]);
+ client.currentFailoverIndex = 0;
+
+ await expectLater(
+ client.checkElectrumAdapter().timeout(const Duration(seconds: 3)),
+ throwsA(isA<TimeoutException>()),
+ );
+
+ expect(primary.accepted, 0);
+ expect(first.accepted, 1);
+ expect(last.accepted, 1);
+ expect(client.getElectrumAdapter(), isNull);
+ expect(client.currentFailoverIndex, -1);
+ await _until(() => first.disconnections == 1 && last.disconnections == 1);
+
+ // A later independent setup operation starts again from the primary.
+ await expectLater(
+ client.checkElectrumAdapter().timeout(const Duration(seconds: 3)),
+ throwsA(isA<TimeoutException>()),
+ );
+ expect(primary.accepted, 1);
+ expect(first.accepted, 2);
+ expect(last.accepted, 2);
+ },
+ );
+
+ test(
+ 'invalid fallback approval fails closed without trapping later setup',
+ () async {
+ final ignoredMethods = {'server.version'};
+ final primary = await start(ignoredMethods: ignoredMethods);
+ final invalid = await start(certificateName: 'node_a');
+ final healthy = await start();
+ final client = clientFor(primary.port, [
+ ElectrumXNode(
+ address: '127.0.0.1',
+ port: invalid.port,
+ name: 'invalid approval',
+ id: '${invalid.port}',
+ useSSL: true,
+ torEnabled: true,
+ clearnetEnabled: true,
+ trustedCertificatePem: 'invalid PEM',
+ ),
+ node(healthy),
+ ]);
+
+ await expectLater(
+ client.checkElectrumAdapter().timeout(const Duration(seconds: 3)),
+ throwsA(isA<FormatException>()),
+ );
+
+ expect(primary.accepted, 1);
+ expect(invalid.accepted, 0);
+ expect(healthy.accepted, 0);
+ expect(client.getElectrumAdapter(), isNull);
+ expect(client.currentFailoverIndex, -1);
+
+ ignoredMethods.clear();
+ await client.checkElectrumAdapter().timeout(const Duration(seconds: 3));
+
+ expect(client.getElectrumAdapter()!.port, primary.port);
+ expect(primary.accepted, 2);
+ expect(invalid.accepted, 0);
+ expect(healthy.accepted, 0);
+ },
+ );
+
+ test(
+ 'invalid fallback approval leaves the working connection in place',
+ () async {
+ final primary = await start();
+ final invalid = await start(certificateName: 'node_a');
+ final healthy = await start();
+ final client = clientFor(primary.port, [
+ ElectrumXNode(
+ address: '127.0.0.1',
+ port: invalid.port,
+ name: 'invalid approval',
+ id: '${invalid.port}',
+ useSSL: true,
+ torEnabled: true,
+ clearnetEnabled: true,
+ trustedCertificatePem: 'invalid PEM',
+ ),
+ node(healthy),
+ ]);
+ await client.checkElectrumAdapter().timeout(const Duration(seconds: 3));
+ final working = client.getElectrumAdapter()!;
+ expect(working.port, primary.port);
+
+ // A request on the primary failed, so the next attempt starts at the
+ // first failover, whose saved approval is damaged.
+ client.currentFailoverIndex = 0;
+ await expectLater(
+ client.checkElectrumAdapter().timeout(const Duration(seconds: 3)),
+ throwsA(isA<FormatException>()),
+ );
+
+ expect(client.getElectrumAdapter(), same(working));
+ expect(working.peer.isClosed, false);
+ expect(client.currentFailoverIndex, -1);
+ expect(invalid.accepted, 0);
+ expect(healthy.accepted, 0);
+
+ // The next attempt reuses the primary connection without reconnecting.
+ await client.checkElectrumAdapter().timeout(const Duration(seconds: 3));
+ expect(client.getElectrumAdapter(), same(working));
+ expect(primary.accepted, 1);
+ expect(primary.disconnections, 0);
+ },
+ );
+
+ test('concurrent setup callers share the successful fallback', () async {
+ final primary = await start(ignoredMethods: {'server.version'});
+ final fallback = await start();
+ final client = clientFor(primary.port, [node(fallback)]);
+
+ await Future.wait([
+ client.checkElectrumAdapter(),
+ client.checkElectrumAdapter(),
+ ]).timeout(const Duration(seconds: 3));
+
+ expect(client.getElectrumAdapter()!.port, fallback.port);
+ expect(primary.accepted, 1);
+ expect(fallback.accepted, 1);
+ });
+
+ test(
+ 'closing during negotiation cancels setup without trying failovers',
+ () async {
+ final primary = await start(ignoredMethods: {'server.version'});
+ final fallback = await start();
+ final client = clientFor(primary.port, [
+ node(fallback),
+ ], timeout: const Duration(seconds: 2));
+ final result = client.checkElectrumAdapter().then<Object?>(
+ (_) => null,
+ onError: (Object error) => error,
+ );
+ await _until(() => primary.methods.contains('server.version'));
+
+ await client.closeAdapter();
+
+ expect(
+ await result.timeout(const Duration(seconds: 3)),
+ isA<StateError>(),
+ );
+ expect(client.getElectrumAdapter(), isNull);
+ expect(fallback.accepted, 0);
+ await _until(() => primary.disconnections == 1);
+ },
+ );
+
+ test('Tor kill switch prevents all setup attempts', () async {
+ final primary = await start();
+ final fallback = await start();
+ final client = clientFor(primary.port, [node(fallback)], useTor: true);
+
+ await expectLater(
+ client.checkElectrumAdapter(),
+ throwsA(isA<StateError>()),
+ );
+
+ expect(primary.accepted, 0);
+ expect(fallback.accepted, 0);
+ });
+}
### test/electrumx_test.dart
@@ -87,6 +87,7 @@ void main() {
late FakeTorService torService;
late EventBus eventBus;
final servers = <MockElectrumServer>[];
+ final clients = <ElectrumXClient>[];
setUpAll(() async {
logDir = await Directory.systemTemp.createTemp('electrumx_test_logs');
@@ -110,8 +111,8 @@ void main() {
required CryptoCurrency coin,
TorPlainNetworkOption netType = TorPlainNetworkOption.both,
}) {
- return ManagedElectrumXClient(
- host: 'mock.stackwallet.dev',
+ final client = ManagedElectrumXClient(
+ host: clearServer.host,
port: 50002,
useSSL: true,
prefs: prefs,
@@ -123,6 +124,8 @@ void main() {
torServer: torServer,
globalEventBusForTesting: eventBus,
);
+ clients.add(client);
+ return client;
}
Matcher throwsCurrentCastError() => throwsA(
@@ -138,14 +141,15 @@ void main() {
torService = FakeTorService();
eventBus = EventBus();
servers.clear();
+ clients.clear();
when(prefs.wifiOnly).thenReturn(false);
when(prefs.useTor).thenReturn(false);
when(prefs.torKillSwitch).thenReturn(false);
});
tearDown(() async {
- await tearDownManagedElectrum(servers: servers);
+ await tearDownManagedElectrum(clients: clients, servers: servers);
});
group('factory constructors and getters', () {
@@ -206,7 +210,9 @@ void main() {
final result = await client.ping(requestID: 'ping-1');
expect(result, isTrue);
- expect(server.requestCount('blockchain.headers.subscribe'), 1);
+ // Setup negotiates once; no header subscription is opened per client.
+ expect(server.requestCount('server.version'), 1);
+ expect(server.requestCount('blockchain.headers.subscribe'), 0);
expect(server.requestCount('server.ping'), 1);
});
### test/electrumx_tls_test.dart
@@ -0,0 +1,279 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:event_bus/event_bus.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:mockito/mockito.dart';
+import 'package:logger/logger.dart' show Level;
+import 'package:stackwallet/electrumx_rpc/electrumx_client.dart';
+import 'package:stackwallet/models/node_model.dart';
+import 'package:stackwallet/services/node_service.dart';
+import 'package:stackwallet/services/event_bus/events/global/tor_status_changed_event.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/utilities/logger.dart';
+import 'package:stackwallet/services/tor_service.dart';
+import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/wallet/impl/bitcoin_wallet.dart';
+
+import 'utilities/tls_test_server.dart';
+
+class _Prefs extends Mock implements Prefs {
+ @override
+ bool get useTor => false;
+ @override
+ bool get wifiOnly => false;
+ @override
+ bool get torKillSwitch => false;
+}
+
+class _Tor extends Mock implements TorService {}
+
+/// Serves one primary node and no failovers to a wallet under test.
+class _Nodes extends NodeService {
+ _Nodes(this.node) : super(secureStorageInterface: FakeSecureStorage());
+ NodeModel node;
+ @override
+ NodeModel? getPrimaryNodeFor({required CryptoCurrency currency}) => node;
+ @override
+ List<NodeModel> failoverNodesFor({required CryptoCurrency currency}) => [];
+}
+
+void main() {
+ late Directory logDirectory;
+ setUpAll(() async {
+ logDirectory = await Directory.systemTemp.createTemp('electrum_tls_logs');
+ await Logging.instance.initialize(logDirectory.path, level: Level.off);
+ });
+ tearDownAll(() => logDirectory.delete(recursive: true));
+ final coin = Bitcoin(CryptoCurrencyNetwork.main);
+ final servers = <TlsElectrumServer>[];
+ late EventBus bus;
+ final prefs = _Prefs();
+
+ final clients = <ElectrumXClient>[];
+ setUp(() => bus = EventBus());
+ tearDown(() async {
+ for (final client in clients) {
+ await client.closeAdapter();
+ }
+ clients.clear();
+ bus.destroy();
+ for (final server in servers) {
+ await server.close();
+ }
+ servers.clear();
+ });
+
+ Future<TlsElectrumServer> start(String certificateName) async {
+ final server = await TlsElectrumServer.start(
+ certificateName: certificateName,
+ );
+ servers.add(server);
+ return server;
+ }
+
+ ElectrumXNode node(TlsElectrumServer server, {String? certificateName}) =>
+ ElectrumXNode(
+ address: '127.0.0.1',
+ port: server.port,
+ name: 'TLS node',
+ id: '${server.port}',
+ useSSL: true,
+ torEnabled: true,
+ clearnetEnabled: true,
+ trustedCertificatePem: certificateName == null
+ ? null
+ : TlsElectrumServer.certificate(certificateName),
+ );
+
+ ElectrumXClient client(
+ ElectrumXNode node, {
+ List<ElectrumXNode> failovers = const [],
+ }) {
+ final client = ElectrumXClient.from(
+ node: node,
+ prefs: prefs,
+ torService: _Tor(),
+ failovers: failovers,
+ cryptoCurrency: coin,
+ globalEventBusForTesting: bus,
+ );
+ clients.add(client);
+ return client;
+ }
+
+ test('live client connects using the approved primary certificate', () async {
+ final server = await start('node_a');
+ final primary = node(server, certificateName: 'node_a');
+ expect(
+ ElectrumXNode.from(primary).trustedCertificatePem,
+ primary.trustedCertificatePem,
+ );
+ final connection = client(primary);
+ await connection.checkElectrumAdapter();
+ final result = await connection.getTransaction(txHash: 'a' * 64);
+ expect(result['confirmations'], 3);
+ expect(connection.trustedCertificatePem, primary.trustedCertificatePem);
+ });
+
+ test('live client rejects an unapproved primary certificate', () async {
+ final server = await start('node_a');
+ await expectLater(
+ client(node(server)).checkElectrumAdapter(),
+ throwsA(isA<HandshakeException>()),
+ );
+ expect(server.requests, 0);
+ });
+
+ test('failover uses its own approved certificate', () async {
+ final primary = await start('node_a');
+ final failover = await start('node_b');
+ final connection = client(
+ node(primary, certificateName: 'node_a'),
+ failovers: [node(failover, certificateName: 'node_b')],
+ );
+ connection.currentFailoverIndex = 0;
+ await connection.checkElectrumAdapter();
+ await connection.getElectrumAdapter()!.request('server.version');
+ expect(connection.getElectrumAdapter()!.port, failover.port);
+ });
+
+ test('primary approval is not inherited by an unapproved failover', () async {
+ final primary = await start('node_a');
+ final failover = await start('node_b');
+ final connection = client(
+ node(primary, certificateName: 'node_a'),
+ failovers: [node(failover)],
+ );
+ connection.currentFailoverIndex = 0;
+ await expectLater(
+ connection.checkElectrumAdapter(),
+ throwsA(isA<HandshakeException>()),
+ );
+ expect(failover.requests, 0);
+ });
+
+ test('a client with the same approval opens its own connection', () async {
+ final server = await start('node_a');
+ final first = client(node(server, certificateName: 'node_a'));
+ await first.checkElectrumAdapter();
+ final second = client(node(server, certificateName: 'node_a'));
+ await second.checkElectrumAdapter();
+ expect(
+ second.getElectrumAdapter(),
+ isNot(same(first.getElectrumAdapter())),
+ );
+ expect(server.accepted, 2);
+ expect(server.disconnections, 0);
+ });
+
+ test('a revoked client never reuses a trusted connection', () async {
+ final server = await start('node_a');
+ final trusted = client(node(server, certificateName: 'node_a'));
+ await trusted.checkElectrumAdapter();
+ final peer = trusted.getElectrumAdapter()!.peer;
+ final revoked = client(node(server));
+ await expectLater(
+ revoked.checkElectrumAdapter(),
+ throwsA(isA<HandshakeException>()),
+ );
+ expect(revoked.getElectrumAdapter(), null);
+ // The trusted connection belongs to its own client. A revocation reaches
+ // it through that client being replaced, as updateNode() does.
+ expect(peer.isClosed, false);
+ await trusted.closeAdapter();
+ expect(peer.isClosed, true);
+ });
+
+ test(
+ 'updateNode closes the wallet connection a revocation replaces',
+ () async {
+ final server = await start('node_a');
+ NodeModel nodeModel({String? pem}) => NodeModel(
+ host: '127.0.0.1',
+ port: server.port,
+ name: 'TLS node',
+ id: 'tls-node',
+ useSSL: true,
+ enabled: true,
+ coinName: 'bitcoin',
+ isFailover: false,
+ isDown: false,
+ trusted: false,
+ torEnabled: true,
+ clearnetEnabled: true,
+ isPrimary: true,
+ trustedCertificatePem: pem,
+ );
+ final nodes = _Nodes(
+ nodeModel(pem: TlsElectrumServer.certificate('node_a')),
+ );
+ final wallet = BitcoinWallet<Bitcoin>(CryptoCurrencyNetwork.main)
+ ..prefs = prefs
+ ..nodeService = nodes;
+ // Wallet.load() calls this before the wallet has any client to close.
+ await wallet.updateNode();
+ final trusted = wallet.electrumXClient;
+ clients.add(trusted);
+ await trusted.request(command: 'server.version');
+ final peer = trusted.getElectrumAdapter()!.peer;
+
+ nodes.node = nodeModel();
+ await wallet.updateNode();
+ clients.add(wallet.electrumXClient);
+ expect(peer.isClosed, true);
+ await expectLater(
+ wallet.electrumXClient.request(command: 'server.version'),
+ throwsA(isA<HandshakeException>()),
+ );
+ },
+ );
+
+ for (final action in ['Tor change', 'close owner']) {
+ test('$action also closes a connection draining after failover', () async {
+ final primary = await TlsElectrumServer.start(
+ ignoredMethods: {'blockchain.transaction.get'},
+ );
+ servers.add(primary);
+ final fallback = await start('node_b');
+ final fallbackNode = node(fallback, certificateName: 'node_b');
+ final connection = client(
+ node(primary, certificateName: 'node_a'),
+ failovers: [fallbackNode],
+ );
+ await connection.checkElectrumAdapter();
+ final previous = connection.getElectrumAdapter()!;
+ final pending = connection
+ .getTransaction(txHash: 'a' * 64)
+ .then<Object?>((value) => value, onError: (Object e) => e);
+ await _until(
+ () => primary.methods.contains('blockchain.transaction.get'),
+ );
+ connection.currentFailoverIndex = 0;
+ await connection.checkElectrumAdapter();
+ expect(connection.getElectrumAdapter()!.port, fallback.port);
+ expect(previous.peer.isClosed, false);
+
+ switch (action) {
+ case 'Tor change':
+ bus.fire(TorPreferenceChangedEvent(status: TorStatus.enabled));
+ case 'close owner':
+ // A revocation or node change replaces the owner via updateNode().
+ await connection.closeAdapter();
+ }
+ await _until(() => previous.peer.isClosed);
+ expect(await pending, isA<StateError>());
+ });
+ }
+}
+
+Future<void> _until(bool Function() ready) async {
+ final watch = Stopwatch()..start();
+ while (!ready()) {
+ if (watch.elapsed > const Duration(seconds: 3)) {
+ throw TimeoutException('Waiting for TLS lifecycle');
+ }
+ await Future<void>.delayed(const Duration(milliseconds: 5));
+ }
+}
### test/electrumx_tor_gate_test.dart
@@ -0,0 +1,172 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:event_bus/event_bus.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:logger/logger.dart' show Level;
+import 'package:mockito/mockito.dart';
+import 'package:stackwallet/electrumx_rpc/electrumx_client.dart';
+import 'package:stackwallet/services/event_bus/events/global/tor_connection_status_changed_event.dart';
+import 'package:stackwallet/services/tor_service.dart';
+import 'package:stackwallet/utilities/logger.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/utilities/tor_plain_net_option_enum.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+
+import 'utilities/tls_test_server.dart';
+
+class _Prefs extends Mock implements Prefs {
+ @override
+ bool get useTor => false;
+ @override
+ bool get wifiOnly => false;
+ @override
+ bool get torKillSwitch => false;
+}
+
+class _Tor extends Mock implements TorService {
+ @override
+ TorConnectionStatus get status => TorConnectionStatus.disconnected;
+}
+
+Future<void> _until(bool Function() ready) async {
+ final watch = Stopwatch()..start();
+ while (!ready()) {
+ if (watch.elapsed > const Duration(seconds: 3)) {
+ throw TimeoutException('Waiting for Tor gate test server');
+ }
+ await Future<void>.delayed(const Duration(milliseconds: 5));
+ }
+}
+
+Future<Object?> _outcome(Future<dynamic> future) =>
+ future.then<Object?>((value) => value, onError: (Object error) => error);
+
+void main() {
+ late Directory logs;
+ late EventBus bus;
+ setUpAll(() async {
+ logs = await Directory.systemTemp.createTemp('electrum_tor_gate');
+ await Logging.instance.initialize(logs.path, level: Level.off);
+ });
+ tearDownAll(() => logs.delete(recursive: true));
+ setUp(() => bus = EventBus(sync: true));
+ // Each client closes itself through addTearDown in clientFor.
+ tearDown(() => bus.destroy());
+
+ Future<TlsElectrumServer> start({bool stallVersion = false}) async {
+ final server = await TlsElectrumServer.start(
+ certificateName: null,
+ ignoredMethods: stallVersion ? {'server.version'} : const {},
+ );
+ addTearDown(server.close);
+ return server;
+ }
+
+ ElectrumXClient clientFor(TlsElectrumServer server) {
+ final client = ElectrumXClient(
+ host: '127.0.0.1',
+ port: server.port,
+ useSSL: false,
+ prefs: _Prefs(),
+ torService: _Tor(),
+ cryptoCurrency: Bitcoin(CryptoCurrencyNetwork.main),
+ netType: TorPlainNetworkOption.both,
+ failovers: [],
+ globalEventBusForTesting: bus,
+ connectionTimeoutForSpecialCaseJsonRPCClients: const Duration(seconds: 2),
+ );
+ addTearDown(client.closeAdapter);
+ return client;
+ }
+
+ void status(TorConnectionStatus value) {
+ bus.fire(TorConnectionStatusChangedEvent(value, 'test'));
+ }
+
+ final cancelled = isA<StateError>().having(
+ (error) => error.message,
+ 'message',
+ 'Electrum client changed',
+ );
+
+ for (final batch in [false, true]) {
+ final label = batch ? 'batch' : 'request';
+ Future<dynamic> send(ElectrumXClient client) => batch
+ ? client.batchRequest(command: 'probe', args: [<dynamic>[]])
+ : client.request(command: 'probe');
+
+ test('$label waiters cancel when closed while Tor is connecting', () async {
+ final server = await start();
+ final client = clientFor(server);
+ status(TorConnectionStatus.connecting);
+ await Future<void>.delayed(Duration.zero);
+ final pending = [for (var i = 0; i < 3; i++) _outcome(send(client))];
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+ expect(server.accepted, 0);
+
+ await client.closeAdapter();
+
+ for (final result in pending) {
+ expect(await result.timeout(const Duration(seconds: 3)), cancelled);
+ }
+ expect(server.accepted, 0);
+ expect(client.getElectrumAdapter(), isNull);
+ });
+
+ test(
+ '$label close after Tor resumes preserves setup cancellation',
+ () async {
+ final server = await start(stallVersion: true);
+ final client = clientFor(server);
+ status(TorConnectionStatus.connecting);
+ await Future<void>.delayed(Duration.zero);
+ final result = _outcome(send(client));
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+ expect(server.accepted, 0);
+ status(TorConnectionStatus.connected);
+ await _until(() => server.methods.contains('server.version'));
+
+ await client.closeAdapter();
+
+ expect(await result.timeout(const Duration(seconds: 3)), cancelled);
+ expect(client.getElectrumAdapter(), isNull);
+ expect(server.methods, ['server.version']);
+ await _until(() => server.disconnections == 1);
+ },
+ );
+
+ for (final finished in [
+ TorConnectionStatus.connected,
+ TorConnectionStatus.disconnected,
+ ]) {
+ test(
+ '$label waiters resume on $finished after repeated connecting events',
+ () async {
+ final server = await start();
+ final client = clientFor(server);
+ status(TorConnectionStatus.connecting);
+ status(TorConnectionStatus.connecting);
+ await Future<void>.delayed(Duration.zero);
+ final pending = [for (var i = 0; i < 3; i++) _outcome(send(client))];
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+ expect(server.accepted, 0);
+
+ status(finished);
+
+ for (final result in pending) {
+ expect(
+ await result.timeout(const Duration(seconds: 3)),
+ batch ? [<String, dynamic>{}] : <String, dynamic>{},
+ );
+ }
+ expect(server.accepted, 1);
+ expect(
+ server.methods.where((method) => method == 'probe'),
+ hasLength(3),
+ );
+ },
+ );
+ }
+ }
+}
### test/electrumx_wallet_isolation_test.dart
@@ -0,0 +1,395 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import 'package:event_bus/event_bus.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:logger/logger.dart' show Level;
+import 'package:mockito/mockito.dart';
+import 'package:stackwallet/electrumx_rpc/electrumx_client.dart';
+import 'package:stackwallet/models/node_model.dart';
+import 'package:stackwallet/services/node_service.dart';
+import 'package:stackwallet/services/tor_service.dart';
+import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart';
+import 'package:stackwallet/utilities/logger.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/wallet/impl/bitcoin_wallet.dart';
+
+class _Prefs extends Mock implements Prefs {
+ _Prefs({this.useTor = false});
+ @override
+ final bool useTor;
+ @override
+ bool get wifiOnly => false;
+ @override
+ bool get torKillSwitch => false;
+}
+
+class _Tor extends Mock implements TorService {}
+
+class _Nodes extends NodeService {
+ _Nodes(this.node) : super(secureStorageInterface: FakeSecureStorage());
+ final NodeModel node;
+ @override
+ NodeModel? getPrimaryNodeFor({required CryptoCurrency currency}) => node;
+ @override
+ List<NodeModel> failoverNodesFor({required CryptoCurrency currency}) => [];
+}
+
+/// A plain JSON-RPC server. It answers setup and header requests, holds
+/// `probe.held` until [release], fails `probe.fail` on [failing] servers and
+/// never answers `probe.silent`.
+class _Server {
+ _Server(this.listener, {required this.failing});
+ final ServerSocket listener;
+ final bool failing;
+ final sockets = <Socket>[];
+ final methods = <String>[];
+ final _held = <void Function()>[];
+ int accepted = 0;
+ int height = 100;
+ int get port => listener.port;
+
+ static Future<_Server> start({bool failing = false}) async {
+ final server = _Server(
+ await ServerSocket.bind(InternetAddress.loopbackIPv4, 0),
+ failing: failing,
+ );
+ server.listener.listen((socket) {
+ server.accepted++;
+ server.sockets.add(socket);
+ socket.done.ignore();
+ socket
+ .cast<List<int>>()
+ .transform(utf8.decoder)
+ .transform(const LineSplitter())
+ .listen((line) {
+ final request = jsonDecode(line) as Map<String, dynamic>;
+ final method = request['method'] as String;
+ server.methods.add(method);
+ void reply(Object? result) {
+ final response = {
+ 'jsonrpc': '2.0',
+ 'id': request['id'],
+ 'result': result,
+ };
+ socket.write('${jsonEncode(response)}\n');
+ }
+
+ switch (method) {
+ case 'server.version':
+ reply(['test', '1.4']);
+ case 'blockchain.headers.subscribe':
+ reply({'height': server.height, 'hex': '00' * 80});
+ case 'probe.held':
+ server._held.add(() => reply({'held': 'done'}));
+ case 'probe.fail':
+ reply(
+ server.failing
+ ? {'error': 'try the fallback'}
+ : {'via': 'fallback'},
+ );
+ case 'probe.silent':
+ break;
+ default:
+ reply({});
+ }
+ }, onError: (Object _) {});
+ });
+ return server;
+ }
+
+ bool get holding => _held.isNotEmpty;
+
+ void release() {
+ for (final reply in _held) {
+ reply();
+ }
+ _held.clear();
+ }
+
+ /// Announces a new block to every connection, as a subscribed server does.
+ void notifyHeader(int height) {
+ final notification = {
+ 'jsonrpc': '2.0',
+ 'method': 'blockchain.headers.subscribe',
+ 'params': [
+ {'height': height, 'hex': '00' * 80},
+ ],
+ };
+ for (final socket in sockets) {
+ socket.write('${jsonEncode(notification)}\n');
+ }
+ }
+
+ Future<void> close() async {
+ for (final socket in sockets) {
+ socket.destroy();
+ }
+ await listener.close();
+ }
+}
+
+Future<void> _until(bool Function() ready) async {
+ final watch = Stopwatch()..start();
+ while (!ready()) {
+ if (watch.elapsed > const Duration(seconds: 3)) {
+ throw TimeoutException('Waiting for isolation test server');
+ }
+ await Future<void>.delayed(const Duration(milliseconds: 5));
+ }
+}
+
+void main() {
+ late Directory logs;
+ late EventBus bus;
+ final clients = <ElectrumXClient>[];
+ final coin = Bitcoin(CryptoCurrencyNetwork.main);
+
+ setUpAll(() async {
+ logs = await Directory.systemTemp.createTemp('electrum_isolation');
+ await Logging.instance.initialize(logs.path, level: Level.off);
+ });
+ tearDownAll(() => logs.delete(recursive: true));
+ setUp(() => bus = EventBus());
+ tearDown(() async {
+ for (final client in clients) {
+ await client.closeAdapter();
+ }
+ clients.clear();
+ bus.destroy();
+ });
+
+ Future<_Server> start({bool failing = false}) async {
+ final server = await _Server.start(failing: failing);
+ addTearDown(server.close);
+ return server;
+ }
+
+ ElectrumXNode node(_Server server) => ElectrumXNode(
+ address: '127.0.0.1',
+ port: server.port,
+ name: '${server.port}',
+ id: '${server.port}',
+ useSSL: false,
+ torEnabled: true,
+ clearnetEnabled: true,
+ );
+
+ ElectrumXClient client(_Server primary, {_Server? fallback}) {
+ final client = ElectrumXClient.from(
+ node: node(primary),
+ prefs: _Prefs(),
+ torService: _Tor(),
+ failovers: [if (fallback != null) node(fallback)],
+ cryptoCurrency: coin,
+ globalEventBusForTesting: bus,
+ );
+ clients.add(client);
+ return client;
+ }
+
+ test(
+ 'two clients of the same coin and node have distinct connections',
+ () async {
+ final server = await start();
+ final first = client(server);
+ final second = client(server);
+
+ await first.checkElectrumAdapter();
+ await second.checkElectrumAdapter();
+
+ expect(first.getElectrumAdapter(), isNotNull);
+ expect(second.getElectrumAdapter(), isNotNull);
+ expect(
+ first.getElectrumAdapter(),
+ isNot(same(second.getElectrumAdapter())),
+ );
+ expect(server.accepted, 2);
+ },
+ );
+
+ for (final action in ['failover', 'timeout', 'closeAdapter']) {
+ test("another client's $action never fails this client's in-flight "
+ 'request', () async {
+ final primary = await start(failing: true);
+ final fallback = await start();
+ final actor = client(primary, fallback: fallback);
+ final bystander = client(primary, fallback: fallback);
+ await actor.checkElectrumAdapter();
+ final actorConnection = actor.getElectrumAdapter()!;
+
+ final inFlight = bystander
+ .request(command: 'probe.held')
+ .then<Object?>((value) => value, onError: (Object e) => e);
+ await _until(() => primary.holding);
+ final bystanderConnection = bystander.getElectrumAdapter()!;
+ expect(bystanderConnection, isNot(same(actorConnection)));
+
+ switch (action) {
+ case 'failover':
+ expect(await actor.request(command: 'probe.fail'), {
+ 'via': 'fallback',
+ });
+ expect(actor.getElectrumAdapter()!.port, fallback.port);
+ case 'timeout':
+ await expectLater(
+ actor.request(
+ command: 'probe.silent',
+ requestTimeout: const Duration(milliseconds: 150),
+ ),
+ throwsA(isA<TimeoutException>()),
+ );
+ case 'closeAdapter':
+ await actor.closeAdapter();
+ }
+ // The action really ended the actor's connection.
+ await _until(() => actorConnection.peer.isClosed);
+
+ expect(bystanderConnection.peer.isClosed, false);
+ expect(bystander.getElectrumAdapter(), same(bystanderConnection));
+ primary.release();
+ expect(await inFlight.timeout(const Duration(seconds: 2)), {
+ 'held': 'done',
+ });
+ expect(bystander.currentFailoverIndex, -1);
+ });
+ }
+
+ test('header notifications after a tip request are not unknown', () async {
+ final server = await start();
+ final prints = <String>[];
+ // The adapter reports unhandled notifications with print().
+ await runZoned(
+ () async {
+ final tipClient = client(server);
+ expect((await tipClient.getBlockHeadTip())['height'], 100);
+ server.notifyHeader(101);
+ await Future<void>.delayed(const Duration(milliseconds: 200));
+ },
+ zoneSpecification: ZoneSpecification(
+ print: (self, parent, zone, line) => prints.add(line),
+ ),
+ );
+ expect(
+ prints.where((line) => line.contains('blockchain.headers')),
+ isEmpty,
+ );
+ });
+
+ test('disconnect lets in-flight requests finish, then reconnects', () async {
+ final server = await start();
+ final owner = client(server);
+ final inFlight = owner.request(command: 'probe.held');
+ await _until(() => server.holding);
+ final connection = owner.getElectrumAdapter()!;
+
+ await owner.disconnect();
+ expect(owner.getElectrumAdapter(), isNull);
+ expect(connection.peer.isClosed, false);
+
+ server.release();
+ expect(await inFlight.timeout(const Duration(seconds: 2)), {
+ 'held': 'done',
+ });
+ await _until(() => connection.peer.isClosed);
+
+ expect((await owner.getBlockHeadTip())['height'], 100);
+ expect(server.accepted, 2);
+ });
+
+ group('wallet chain height', () {
+ NodeModel nodeModel(
+ _Server server, {
+ bool torEnabled = true,
+ bool clearnetEnabled = true,
+ }) => NodeModel(
+ host: '127.0.0.1',
+ port: server.port,
+ name: 'node',
+ id: 'node',
+ useSSL: false,
+ enabled: true,
+ coinName: coin.identifier,
+ isFailover: false,
+ isDown: false,
+ trusted: false,
+ torEnabled: torEnabled,
+ clearnetEnabled: clearnetEnabled,
+ isPrimary: true,
+ );
+
+ Future<BitcoinWallet<Bitcoin>> wallet(NodeModel node, Prefs prefs) async {
+ final wallet = BitcoinWallet<Bitcoin>(CryptoCurrencyNetwork.main)
+ ..prefs = prefs
+ ..nodeService = _Nodes(node);
+ // Wallet.load() calls this before the wallet has any client to close.
+ await wallet.updateNode();
+ clients.add(wallet.electrumXClient);
+ return wallet;
+ }
+
+ test('each wallet reads the current tip on its own connection', () async {
+ final server = await start();
+ final first = await wallet(nodeModel(server), _Prefs());
+ final second = await wallet(nodeModel(server), _Prefs());
+
+ expect(await first.fetchChainHeight(), 100);
+ expect(await second.fetchChainHeight(), 100);
+ expect(server.accepted, 2);
+
+ // Nothing is cached between calls: a new block is seen at once.
+ server.height = 101;
+ expect(await first.fetchChainHeight(), 101);
+ expect(
+ server.methods.where((m) => m == 'blockchain.headers.subscribe'),
+ hasLength(3),
+ );
+ expect(server.accepted, 2);
+ });
+
+ test('a clearnet-only node still fails chain height under Tor', () async {
+ final server = await start();
+ final clearOnly = await wallet(
+ nodeModel(server, torEnabled: false),
+ _Prefs(useTor: true),
+ );
+
+ await expectLater(
+ clearOnly.fetchChainHeight(),
+ throwsA(
+ isA<Exception>().having(
+ (e) => e.toString(),
+ 'message',
+ contains('Non-TOR only client'),
+ ),
+ ),
+ );
+ expect(server.methods, isNot(contains('blockchain.headers.subscribe')));
+ });
+
+ test(
+ 'an exited wallet releases its connection after its refresh',
+ () async {
+ final server = await start();
+ final exited = await wallet(nodeModel(server), _Prefs());
+ expect(await exited.fetchChainHeight(), 100);
+ final connection = exited.electrumXClient.getElectrumAdapter()!;
+
+ // exit() runs this. A refresh in progress keeps the connection.
+ await exited.refreshMutex.acquire();
+ final released = exited.releaseConnectionWhenIdle();
+ await Future<void>.delayed(const Duration(milliseconds: 50));
+ expect(connection.peer.isClosed, false);
+ exited.refreshMutex.release();
+ await released;
+ await _until(() => connection.peer.isClosed);
+
+ // Opening the wallet again reconnects.
+ expect(await exited.fetchChainHeight(), 100);
+ expect(server.accepted, 2);
+ },
+ );
+ });
+}
### test/fixtures/tls/expired.key.pem
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQC2Y1jMxcqqPHby
++c9On7aAdWHUy9cAaKGMzcmEDK/kuo8mjpZeVT7NnXGot65j4WWeWfo3coIYuC3+
+aA5obDMj04cAv9VNFPtJGyFVFt/UyM7kE8dVZc3/lkv+IyUMs0mBs/b09NhMHsZE
+P+H4bzZuF75Sb6LJtCcl9rpztROp2GklpEnsynIuAFZA8jigUnpmvMjptPCAQhyq
+QMiTyFqT2zJVfWPuuQkYa/1YQdwfjAv4+JsnQhjtYgk9eg6m/r24RZK0hp2cDTQh
+Oc6juSwUgG6zKh56qo9L89g0+IH3dKk2hYOc50p9Gs5N81ohH3LbeNktjGAzWp8y
+rHhe/sAxAgMBAAECggEBAInVJEuEAjeKgD35CXCahDop+yfsb+vQJp4Y+nw/dkG9
+tublhL9/XnnWzQk63qB+uuPjjZOPhr+VmLSVAKZrdm5RscmgL1sUSx6hURxTsA3H
+P4rfY5mm2PmZJI7HEn25lAhf73aI/ljwPNdhC61KpnCmot77nKMf8SHghmFg655D
+NezEYaUemR3W1yQAdkk/5p+Bzd+mLBj7MRY+BAvlz3WbBk7n3hvPqB6XjvPDhhMZ
+aVjsnzLKsHqxiaZn/0VepR//bkVlThGNUnUkuzz/NZvdNVXu1e9gkBCN2mS2huAX
+laPr73/9EjaE6XQRDWfMiItzswXCQCsBrt25ZrPh7G0CgYEA3RMDFRfMSS05aepe
+432pnCSI8gcVQWamPSdguobPBo74ZwhmeRo5cLUocOW+HmbjrKCyfisQCBuEgd1g
+9zMo5X/cwFTSmzurWFNpK+tC2P9u70SSou/lrjIFDW9bQGjvoux23XYlnGoQznPP
+/7dWYGgzU238/K+zihYTMe01CosCgYEA0zO8I63Tqlo5nF2mDDLVCCvMXHvAi0IT
+HoSR8OYG66l8qY8VyQWf9UWEvbnWeFtODdG48zKX+BhP6iyKQtlBNIno5oc8sXab
+Q6upwNIJHOlwSga2JSncKGE6Uf4XDuCtSAUAwLryJyHPpdtFy9hvtIliAs6xd7fZ
+Vcxhl/YyQ7MCgYEAz83GMPaMtSBIfpGqngYJ/1asT2xvA2ncy1EPcGW1hkGvpxHT
+WPRYl+QBXpXl7qfiTOtEvKn3yNcs5/FS6ypwv8E/nJ5e1UHyXvUQwBLFZDo+abQ4
+beY4LFSiQS2yRcodrzS8ypD665sbryRXmNQZ4kcwL7UMf+0cQ6laY6zIFd8CgYAl
+db+g9GvegzJEsbeJ4lo2oM4WeTyldoq9lvXrrGD924no6SAMD5tXfYUVwahwoIEv
+oksTl52su2MxPcUoJjCSiQNuH/5723WegwwQzzAemKj5+EbGQK5z2wrlEBQ251LU
+u05u4LmihzS1TjcK+NCXTOa9aLvBaDJ8LUwCEADKUQKBgQCWcdXV4zA9KrPd8pzn
+U20x3RXYTLLDYygsQm0wWBOUw+aQJBJPBJuw1PzkYUoQI2icXPtjAMeMykIU4LkY
+UKkZokaRmlAdddE9dTlYyaVOjVrEOdcExN0mJisoS2UDxmJG77mZ5Bb573dfsm3K
+WLCf3QE5JJ/7uYfxVKuKfA/dmw==
+-----END PRIVATE KEY-----
### test/fixtures/tls/expired.pem
@@ -0,0 +1,18 @@
+-----BEGIN CERTIFICATE-----
+MIIC5zCCAc+gAwIBAgIBATANBgkqhkiG9w0BAQsFADAUMRIwEAYDVQQDDAlsb2Nh
+bGhvc3QwHhcNMjAwMTAxMDAwMDAwWhcNMjEwMTAxMDAwMDAwWjAUMRIwEAYDVQQD
+DAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC2Y1jM
+xcqqPHby+c9On7aAdWHUy9cAaKGMzcmEDK/kuo8mjpZeVT7NnXGot65j4WWeWfo3
+coIYuC3+aA5obDMj04cAv9VNFPtJGyFVFt/UyM7kE8dVZc3/lkv+IyUMs0mBs/b0
+9NhMHsZEP+H4bzZuF75Sb6LJtCcl9rpztROp2GklpEnsynIuAFZA8jigUnpmvMjp
+tPCAQhyqQMiTyFqT2zJVfWPuuQkYa/1YQdwfjAv4+JsnQhjtYgk9eg6m/r24RZK0
+hp2cDTQhOc6juSwUgG6zKh56qo9L89g0+IH3dKk2hYOc50p9Gs5N81ohH3LbeNkt
+jGAzWp8yrHhe/sAxAgMBAAGjRDBCMA8GA1UdEwEB/wQFMAMBAf8wGgYDVR0RBBMw
+EYIJbG9jYWxob3N0hwR/AAABMBMGA1UdJQQMMAoGCCsGAQUFBwMBMA0GCSqGSIb3
+DQEBCwUAA4IBAQCZiHHwkDZtLK9qSaoKaHL5voxvbH00ggjIS7FDGUUQFpSwbYgy
+kzm23UID7sQwBzWh3KVfCOAeYmNL6mEV61gcoIKd8u4W/MArklQH6gX+jJENVgRl
+N/hd2TXvGV625S8/2jksNCYsHcWVYkB7hJ3IGEqSFVFtOt6HkxX2s3VSOAeoRNNa
+RjPRF+H2yx6K0kw6PdLvWXw3vY399XORkmXEN+CNPXqjARgee8jgR9Byf+LJZ/Wp
+mUelvexeQhhYQh6qBSDfvNUDWqM1MUwEYJ3ZwePhRivR2t4k0b+MyeuyxyLsDs5t
+lUGqkNlu6y7G24L7pDYPMAUjO1HnfB3kdv3x
+-----END CERTIFICATE-----
### test/fixtures/tls/node_a.key.pem
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC+BqJm1wyIEii2
+9MO2qtBr0Ne5I0bFf1aNA5b1hz7QapEQRO8gdL93DlpAJw0pAGa5rSEdAV7A2MgV
+u35rfjG8MWoZblANv5rlHprkAnMl4oIRCXt3voIyVNUM4eZJu2pifEjT5GwDiHR3
+HsovdgPM7bzUjVzdBIOhhNXRp8Fkayo6IyChzA/3Gj6ehbOhHwOW05B4o3Pzj9lr
+9gf4l9X/cwihuuvL+n0ZUrBMScQtiZ73LhyqcqQvcS7azy4FFzrdzrXFwtO6nxUN
+mG6C/sPAZwY1ml6Dnadroc61eF4gLFIQyL4wDpuzLb7z3ENONO2b4yjenstc6Xkz
+xCJgBFulAgMBAAECggEARpMINdGgodi8rlZxaaI/DgveUrA7VJZaerzekAnO1nD9
+t2EivpcdlQYLls/qH1Q60rLuHWuo2U6p4Qhlh16y8gYYNaG2saR7zqRzOkN+qI9b
+ZyBybqKekDrZdZNgh/nHJRSrp6aqRxWiy6rvxHi8KJwTCY4G8z799Dr1fowjUzul
+4omUkQBA81qfHWzAU1PRQ9FyQtzM+/Y+7JIA5j7zo06GgU+NjJx+SC6jd8Ym8s5p
+xdKw1JrrNcWn6Z1n/nV1WamqDI/uodFij97nKIuR2839hb4zE6rxMC4o8EYxxXP/
+VIcKQqTWysBChA6Bg0kqEB6X6yaSU51Pjl23VOylcQKBgQDkIEPBZjs8efoxU3ao
+UnohQ4djZXzksdWh4GfNtT5Z9LhG8wrAiTLaPcl4bgt9wmfY8294i7S/fsvUFeMt
+qfAziogi/IqyOaM42R/iRoKMSDsVhHrg/2hC24hbfpMDiPEJjEogAJJbC+DpgGC3
+cmrYxNDJXzDNgHYuoxU47wMucwKBgQDVPpsZyfdftuSJvNx/t0W2yTw1nKW9pxVw
+Gb6irgrVq7YRUukPfhP2yAwwGgz7T/Cg/W3hLAnqva3AQFflTlkCtO6bTY2AL77F
+AsUgajq6vIm+a5VHj+zP2jFVnPftdpDuUAHu5sEw9ykEsXEja5nP6jT/Lf8pdyXj
+1P4c80FvhwKBgQClSg9tyOHwvryeEshty1y8T06AoV8t4QBWSt9LeCAWU69VkPHg
+cUhMQuqAfNOMqlhOJIxG/orXGUscf0Ncqb3lymE7YFoqKoLuRLvKWqZqeEd/Hr9d
+2RE1KBWTnZFtxUJIVcK7j057845iAWeSY6+xImHZFkSpEYQP5JAS8XMPqwKBgF6B
+uZGLXfPwhYa5yetcWSwyMVn9S8Mqqqic8Ez+31RlHnK9EQdJtCVZ8XTcBsbWXemr
+h6gUsWx0le2vVoUM3QwDDgCMNVsLTfvYR28fRVn/NvjKi0VE9woDRHwR7hsywfas
+RL8RS6ucznQDBAZTqL5pqQUy6HQDFyrK+bfw4x4/AoGAI/IdlKo7jILyis9ASL14
+ckSUcXjuiyI2ha4ap1+EpDOTIpkAsbCEXDqnDfpbpjL847vs4mxsJP7+ZF50j0F/
+XQr1ZCKWYc2CXjYxdq7udM2rfWrT2WX9goj44iftF2jK/HzgzEEKhk3ldXMLDeSO
+vlfmIeCu1QiTx7TY4WamPWA=
+-----END PRIVATE KEY-----
### test/fixtures/tls/node_b.key.pem
@@ -0,0 +1,28 @@
+-----BEGIN PRIVATE KEY-----
+MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDqOJsCQTKfiveh
+k1in+TEkQndzNDuzKFSAzyZ+nWthUAvp1XxFdlcOiWBL5mwLkC0zqRrasBTW4bQu
+w+Kbw4n7NzBjcs1FSgz86PBJ/5R1UznEGe3G1+83U7noxKqdrPWkwVt14Qolp9At
+BvhRBciH/VjvwRfuwSMkCb6aGZgYLiFcGDvk+nvlpE0BYjq61zpd8p+U3EoFwTr4
+5mvG7uNFFC08wQzXKcU5CHNneq1vg42quUHn503q1l/RH4D9wD/sVb3UeqD6KeXp
+VrOQ63dh85gdgDf39VNp23oy7BmbiUzi2h9Ir5FQejr+oAq25lIUPc2OsU1ofrKh
+gBa6wKDxAgMBAAECggEACCCCsGdWvFZ0FTUppFpvLBTqVCMB10uU8ws9CLOpoCzI
+3Qo9T6O1jZmSr8+E/Dm6d8psVh45+uLF/8FoQYNdbEwT779yA+931+a1P7wQiKmk
+nXtQ1s9zS3YqQztfuCziMR9MbyCp23ihLo7JWvZaaO2PgnIuxGgLMhrsdChjMKOI
+InI2SCAt3tnx6uRDJbgRDFsMM3zZepqZSFa7aoeSiT9QvZakCOqqwZUbv4oUdNwf
+QuLeURmaFv/xJR1TbzEm7qenAZj2WxBYsDD6WP5mu0EMT6OPFOAQPTkJey4mOyeq
+3vmy+q6/iZJeeTcQsnUmKTQBfsBoEuzd3gULRepYyQKBgQD2mOkVzQN0x2Dukcsq
+3FIkD0LQVLG7xhECsXfqrtb3j/FSD9IA9n0b7U04Hus9A7sMAIATSnoEWYFBro/s
+FyozOioPhWAdXz0/isxM4HRlkcZvg5Ypq4PRthCKBa+ZrZkjAPyZod1dKfEFgxXN
+QFYO7tCD9XMUdOu/3MpMcs681wKBgQDzJuNqRvhhEFMLCOZP0KYZL9RybU3Lxv9C
++xpTBUtcatoh/0wTzs7r6c3+pOSMO/xHPI8OMkNGWQpZro2392garWBnsfMeDsy0
+t/bdWT8JhXM6/IvcQ/vZ0V6PVgfhRjW7tavEptoPMHQKEx7Z/7MXbTtzKrQcNPzo
+Fhz9ghPPdwKBgQCZG9nk2lTiBgUOO2GM7BzoHL2cQmnUL6dSJ8RP51y7exkXnZED
+XgfR9iXyyWe/i3hwfEMJNz3JQ5V4pZzgtoVSJzQETQifVAngURqGRPqgMcGmbWon
+10FSTRu5xsv/vASP8kXkUdbyyF7I0FoSBXcpcGfw9s4MDohtqPXGP6ZTIwKBgBoS
+OmIj1+/4Yx8UxjUapySeN0ZJqATIgog5ClqKf8kZ/+eTSyH4k8FB4X+DSKosqGEv
+AhvAkewSEgUJrVJjabsqieK0dt/rMFHUQ9j5/8NSlsdlWs20UGXLiDsQO2oRMCO/
+V/qO9WSZimemIzG2tAo4AR7ZHlTD7bYo4NThxKQDAoGBAM34F/m4W6KqOUJ+Jq+k
+pkmx3rBMIE+Qnr2pU8z9hwemWDPmZc/R5eVoOACaoMjA8+GN5hQa/FWBMxzgZZRA
+lDXrzlFXv7MMTQpKl6YPNHhgfy1IHwWqtNGFCwVqQsFrbmolILuZkjixfUbrh9pl
+2pqXZd1YKFsdGSLym41sGkiu
+-----END PRIVATE KEY-----
### test/models/node_model_backup_test.dart
@@ -1,7 +1,48 @@
+import 'dart:io';
+
import 'package:flutter_test/flutter_test.dart';
import 'package:stackwallet/models/node_model.dart';
void main() {
+ test('keeps a PEM whose contents are not a certificate', () {
+ // It cannot match any server certificate, so the node is simply not
+ // approved until its certificate is reviewed again.
+ for (final body in ['aGVsbG8=', 'MAA=']) {
+ final pem =
+ '-----BEGIN CERTIFICATE-----\n$body\n-----END CERTIFICATE-----\n';
+ final node = NodeModel.fromStackBackup({
+ 'host': 'node.example.com',
+ 'port': 50002,
+ 'name': 'Node',
+ 'id': 'tls',
+ 'coinName': 'bitcoin',
+ 'trustedCertificatePem': pem,
+ });
+ expect(node.trustedCertificatePem, pem);
+ }
+ });
+
+ test('restores a trusted certificate and drops a damaged one', () {
+ final pem = File('test/fixtures/tls/expired.pem').readAsStringSync();
+ final map = {
+ 'host': 'node.example.com',
+ 'port': 50002,
+ 'name': 'Node',
+ 'id': 'tls',
+ 'coinName': 'bitcoin',
+ 'trustedCertificatePem': pem,
+ };
+ expect(NodeModel.fromStackBackup(map).trustedCertificatePem, pem);
+ for (final damaged in ['', 'not a certificate', 42, pem.substring(40)]) {
+ map['trustedCertificatePem'] = damaged;
+ expect(
+ NodeModel.fromStackBackup(map).trustedCertificatePem,
+ null,
+ reason: '$damaged',
+ );
+ }
+ });
+
test('restores current and legacy node backup fields', () {
final source = NodeModel(
host: 'node.example.com',
### test/models/node_tls_trust_test.dart
@@ -0,0 +1,198 @@
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:hive_ce/hive.dart';
+import 'package:stackwallet/models/node_form_data.dart';
+import 'package:stackwallet/models/node_model.dart';
+
+import '../utilities/tls_test_server.dart';
+
+NodeModel tlsNode({String? certificatePem}) => NodeModel(
+ host: '127.0.0.1',
+ port: 50002,
+ name: 'TLS node',
+ id: 'tls-node',
+ useSSL: true,
+ enabled: true,
+ coinName: 'bitcoin',
+ isFailover: false,
+ isDown: false,
+ trusted: false,
+ torEnabled: true,
+ clearnetEnabled: true,
+ isPrimary: false,
+ trustedCertificatePem: certificatePem,
+);
+
+void main() {
+ final pem = TlsElectrumServer.certificate('node_a');
+
+ test(
+ 'backup round trip preserves TLS approval independently of daemon trust',
+ () {
+ final node = tlsNode(certificatePem: pem);
+ final restored = NodeModel.fromStackBackup(node.toMap());
+ expect(restored.trustedCertificatePem, pem);
+ expect(restored.trusted, false);
+ final legacy = node.toMap()..remove('trustedCertificatePem');
+ expect(NodeModel.fromStackBackup(legacy).trustedCertificatePem, null);
+ },
+ );
+
+ test(
+ 'node edits preserve approval for the same endpoint and can revoke it',
+ () {
+ final node = tlsNode(certificatePem: pem);
+ expect(
+ node
+ .copyWith(name: 'Renamed', loginName: null, trusted: false)
+ .trustedCertificatePem,
+ pem,
+ );
+ expect(
+ node
+ .copyWith(
+ loginName: null,
+ trusted: false,
+ clearTrustedCertificate: true,
+ )
+ .trustedCertificatePem,
+ null,
+ );
+ expect(
+ node
+ .copyWith(host: 'another.example', loginName: null, trusted: false)
+ .trustedCertificatePem,
+ null,
+ );
+ expect(
+ node
+ .copyWith(port: 50003, loginName: null, trusted: false)
+ .trustedCertificatePem,
+ null,
+ );
+ expect(
+ node
+ .copyWith(useSSL: false, loginName: null, trusted: false)
+ .trustedCertificatePem,
+ null,
+ );
+ },
+ );
+
+ test('form edits clear approval only when the endpoint changes', () {
+ final data = NodeFormData.fromNode(tlsNode(certificatePem: pem));
+ data.name = 'Renamed';
+ data.host = data.host;
+ data.port = data.port;
+ data.useSSL = data.useSSL;
+ expect(data.trustedCertificatePem, pem);
+ data.host = 'another.example';
+ expect(data.trustedCertificatePem, null);
+ data.trustedCertificatePem = pem;
+ data.port = 50003;
+ expect(data.trustedCertificatePem, null);
+ data.trustedCertificatePem = pem;
+ data.useSSL = false;
+ expect(data.trustedCertificatePem, null);
+ });
+
+ test('restoring an edited endpoint restores its approval', () {
+ final data = NodeFormData.fromNode(tlsNode(certificatePem: pem));
+ data.host = 'another.example';
+ expect(data.trustedCertificatePem, null);
+ data.host = '127.0.0.1';
+ expect(data.trustedCertificatePem, pem);
+ data.port = 50003;
+ data.port = 50002;
+ data.useSSL = false;
+ data.useSSL = true;
+ expect(data.trustedCertificatePem, pem);
+ expect(data.matchesEndpointOf(tlsNode()), true);
+ data.trustedCertificatePem = null;
+ data.host = 'another.example';
+ data.host = '127.0.0.1';
+ expect(data.trustedCertificatePem, null);
+ });
+
+ test(
+ 'manual Hive adapter persists approval across close and reopen',
+ () async {
+ final directory = await Directory.systemTemp.createTemp('node_tls_hive');
+ Hive.init(directory.path);
+ Hive.resetAdapters();
+ Hive.registerAdapter(NodeModelAdapter());
+ try {
+ var box = await Hive.openBox<NodeModel>('nodes');
+ await box.put('node', tlsNode(certificatePem: pem));
+ await box.close();
+ box = await Hive.openBox<NodeModel>('nodes');
+ expect(box.get('node')!.trustedCertificatePem, pem);
+ expect(box.get('node')!.trusted, false);
+ await box.close();
+ } finally {
+ await Hive.close();
+ Hive.resetAdapters();
+ await directory.delete(recursive: true);
+ }
+ },
+ );
+
+ test('manual Hive adapter reads legacy nodes without migration', () async {
+ final directory = await Directory.systemTemp.createTemp('node_tls_legacy');
+ Hive.init(directory.path);
+ Hive.registerAdapter(_LegacyNodeAdapter(), override: true);
+ try {
+ var box = await Hive.openBox<NodeModel>('nodes');
+ await box.put('node', tlsNode());
+ await box.close();
+ Hive.resetAdapters();
+ Hive.registerAdapter(NodeModelAdapter());
+ box = await Hive.openBox<NodeModel>('nodes');
+ expect(box.get('node')!.trustedCertificatePem, null);
+ expect(box.get('node')!.host, '127.0.0.1');
+ await box.close();
+ } finally {
+ await Hive.close();
+ Hive.resetAdapters();
+ await directory.delete(recursive: true);
+ }
+ });
+}
+
+/// The sixteen fields written before TLS trust was introduced.
+class _LegacyNodeAdapter extends TypeAdapter<NodeModel> {
+ @override
+ int get typeId => 12;
+
+ @override
+ NodeModel read(BinaryReader reader) => NodeModelAdapter().read(reader);
+
+ @override
+ void write(BinaryWriter writer, NodeModel node) {
+ final fields = [
+ node.id,
+ node.host,
+ node.port,
+ node.name,
+ node.useSSL,
+ node.loginName,
+ node.enabled,
+ node.coinName,
+ node.isFailover,
+ node.isDown,
+ node.trusted,
+ node.torEnabled,
+ node.clearnetEnabled,
+ node.forceNoTor,
+ node.isPrimary,
+ node.nodeApiSecret,
+ ];
+ writer.writeByte(fields.length);
+ for (int i = 0; i < fields.length; i++) {
+ writer
+ ..writeByte(i)
+ ..write(fields[i]);
+ }
+ }
+}
### test/services/node_certificate_writes_test.dart
@@ -0,0 +1,293 @@
+import 'dart:async';
+
+import 'package:flutter_secure_storage/flutter_secure_storage.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/db/hive/db.dart';
+import 'package:stackwallet/models/node_form_data.dart';
+import 'package:stackwallet/models/node_model.dart';
+import 'package:stackwallet/services/node_service.dart';
+import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+
+import '../hive/hive_ce_test_utils.dart';
+import '../utilities/tls_test_server.dart';
+
+class _PausedPassword extends FakeSecureStorage {
+ final started = Completer<void>();
+ final release = Completer<void>();
+ @override
+ Future<void> delete({
+ required String key,
+ IOSOptions? iOptions,
+ AndroidOptions? aOptions,
+ LinuxOptions? lOptions,
+ WebOptions? webOptions,
+ MacOsOptions? mOptions,
+ WindowsOptions? wOptions,
+ }) async {
+ started.complete();
+ await release.future;
+ await super.delete(key: key);
+ }
+}
+
+void main() {
+ final coin = Bitcoin(CryptoCurrencyNetwork.main);
+ late NodeService service;
+ late FakeSecureStorage storage;
+ late NodeModel original;
+ late String pem;
+ NodeModel current() => service.getNodeById(id: original.id)!;
+ NodeFormData approved(NodeModel node) =>
+ NodeFormData.fromNode(node)..trustedCertificatePem = pem;
+
+ setUp(() async {
+ await setUpHiveCeTest();
+ if (!DB.instance.hive.isAdapterRegistered(12)) {
+ DB.instance.hive.registerAdapter(NodeModelAdapter());
+ }
+ final box = await DB.instance.hive.openBox<NodeModel>(DB.boxNameNodeModels);
+ storage = FakeSecureStorage();
+ service = NodeService(secureStorageInterface: storage);
+ original = NodeModel(
+ host: 'node.example',
+ port: 50002,
+ name: 'Node',
+ id: 'n',
+ useSSL: true,
+ enabled: true,
+ coinName: coin.identifier,
+ isFailover: true,
+ isDown: false,
+ torEnabled: true,
+ clearnetEnabled: true,
+ isPrimary: false,
+ );
+ await box.put(original.id, original);
+ pem = TlsElectrumServer.certificate('node_a');
+ });
+ tearDown(tearDownHiveCeTest);
+
+ test('a certificate-only write keeps node metadata and never reads or changes credentials', () async {
+ expect(identical(current(), current()), true);
+ expect(
+ await service.saveTrustedCertificate(original, approved(original)),
+ true,
+ );
+ expect(current().trustedCertificatePem, pem);
+ expect(current().name, original.name);
+ expect(current().isPrimary, false);
+ expect(storage.interactions, 0);
+ });
+
+ for (final change in [
+ 'forget empty',
+ 'forget approved',
+ 'replace',
+ 'endpoint',
+ 'delete',
+ ]) {
+ test('a late approval cannot undo $change', () async {
+ if (change == 'forget approved') {
+ await service.saveTrustedCertificate(original, approved(original));
+ original = current();
+ }
+ final result = approved(original);
+ switch (change) {
+ case 'forget empty':
+ case 'forget approved':
+ await service.forgetTrustedCertificate(original);
+ case 'replace':
+ final replacement = approved(original)
+ ..trustedCertificatePem = TlsElectrumServer.certificate('node_b');
+ await service.saveTrustedCertificate(original, replacement);
+ case 'endpoint':
+ await DB.instance.put<NodeModel>(
+ boxName: DB.boxNameNodeModels,
+ key: original.id,
+ value: original.copyWith(
+ host: 'elsewhere.example',
+ loginName: null,
+ trusted: null,
+ ),
+ );
+ case 'delete':
+ await DB.instance.delete<NodeModel>(
+ boxName: DB.boxNameNodeModels,
+ key: original.id,
+ );
+ }
+ final before = service.getNodeById(id: original.id);
+ expect(await service.saveTrustedCertificate(original, result), false);
+ expect(identical(service.getNodeById(id: original.id), before), true);
+ });
+ }
+
+ test(
+ 'a queued approval checks the row after an earlier queued Forget',
+ () async {
+ await DB.instance.mutex.acquire();
+ final forgotten = service.forgetTrustedCertificate(original);
+ final late = service.saveTrustedCertificate(original, approved(original));
+ DB.instance.mutex.release();
+ expect(await forgotten, true);
+ expect(await late, false);
+ expect(current().trustedCertificatePem, null);
+ },
+ );
+
+ test(
+ 'a Save waiting for the password cannot restore a forgotten certificate',
+ () async {
+ await service.saveTrustedCertificate(original, approved(original));
+ final opened = current();
+ final paused = _PausedPassword();
+ final editor = NodeService(secureStorageInterface: paused);
+ final saving = editor.saveEdit(
+ opened.copyWith(name: 'Edited', loginName: null, trusted: null),
+ null,
+ true,
+ opened: opened,
+ );
+ await paused.started.future;
+ await service.forgetTrustedCertificate(opened);
+ paused.release.complete();
+ expect(await saving, true);
+ expect(current().name, 'Edited');
+ expect(current().trustedCertificatePem, null);
+ },
+ );
+
+ test('an explicit staged Forget wins an approval made before Save', () async {
+ await service.saveTrustedCertificate(original, approved(original));
+ final edited = original.copyWith(
+ loginName: null,
+ trusted: null,
+ clearTrustedCertificate: true,
+ );
+ expect(
+ await service.saveEdit(
+ edited,
+ null,
+ true,
+ opened: original,
+ forgetCertificate: true,
+ ),
+ true,
+ );
+ expect(current().trustedCertificatePem, null);
+ });
+
+ test(
+ 'a fresh test discards stale form trust and can approve after Forget',
+ () async {
+ await service.saveTrustedCertificate(original, approved(original));
+ final form = NodeFormData.fromNode(current());
+ await service.forgetTrustedCertificate(current());
+ expect(service.prepareCertificateTest(form), true);
+ expect(form.trustedCertificatePem, null);
+ form.trustedCertificatePem = pem;
+ final edit = current().copyWith(
+ loginName: null,
+ trusted: null,
+ trustedCertificatePem: form.trustedCertificatePem,
+ );
+ expect(
+ await service.saveEdit(edit, null, true, opened: form.source!),
+ true,
+ );
+ expect(current().trustedCertificatePem, pem);
+ },
+ );
+
+ test('a staged Forget survives preparing another test after an external approval', () async {
+ final form = NodeFormData.fromNode(original)..forgetCertificate();
+ await service.saveTrustedCertificate(original, approved(original));
+ expect(service.prepareCertificateTest(form), true);
+ expect(form.certificateForgotten, true);
+ expect(form.trustedCertificatePem, null);
+ });
+
+ for (final flag in ['primary', 'enabled', 'failover']) {
+ test(
+ 'updating $flag keeps the latest certificate and credentials',
+ () async {
+ await service.saveTrustedCertificate(original, approved(original));
+ switch (flag) {
+ case 'primary':
+ await service.setPrimaryNodeFor(coin: coin, node: original);
+ case 'enabled':
+ await service.setEnabledState(original.id, false, true);
+ case 'failover':
+ await service.setFailover(original.id, false);
+ }
+ expect(current().trustedCertificatePem, pem);
+ expect(storage.interactions, 0);
+ },
+ );
+ }
+
+ test('Connect stores its approval and primary flag together without touching credentials', () async {
+ expect(
+ await service.commitConnectionTest(
+ node: original,
+ formData: approved(original),
+ ),
+ true,
+ );
+ expect(current().trustedCertificatePem, pem);
+ expect(current().isPrimary, true);
+ expect(storage.interactions, 0);
+ });
+
+ for (final change in ['Forget', 'edit', 'delete']) {
+ test('Connect cannot promote or restore trust after $change', () async {
+ final result = approved(original);
+ switch (change) {
+ case 'Forget':
+ await service.forgetTrustedCertificate(original);
+ case 'edit':
+ await DB.instance.put<NodeModel>(
+ boxName: DB.boxNameNodeModels,
+ key: original.id,
+ value: original.copyWith(
+ host: 'new.example',
+ loginName: null,
+ trusted: null,
+ ),
+ );
+ case 'delete':
+ await DB.instance.delete<NodeModel>(
+ boxName: DB.boxNameNodeModels,
+ key: original.id,
+ );
+ }
+ expect(
+ await service.commitConnectionTest(node: original, formData: result),
+ false,
+ );
+ expect(service.getPrimaryNodeFor(currency: coin), null);
+ });
+ }
+
+ test(
+ 'an edited endpoint keeps only the approval tested for that endpoint',
+ () async {
+ final form = approved(original)..host = 'new.example';
+ expect(form.trustedCertificatePem, null);
+ form.trustedCertificatePem = pem;
+ final edited = original.copyWith(
+ host: form.host,
+ loginName: null,
+ trusted: null,
+ trustedCertificatePem: form.trustedCertificatePem,
+ );
+ expect(
+ await service.saveEdit(edited, null, true, opened: original),
+ true,
+ );
+ expect(current().host, 'new.example');
+ expect(current().trustedCertificatePem, pem);
+ },
+ );
+}
### test/services/notification_certificate_revocation_test.dart
@@ -0,0 +1,194 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:logger/logger.dart' show Level;
+import 'package:stackwallet/db/hive/db.dart';
+import 'package:stackwallet/electrumx_rpc/electrumx_client.dart';
+import 'package:stackwallet/models/node_model.dart';
+import 'package:stackwallet/models/notification_model.dart';
+import 'package:stackwallet/services/node_service.dart';
+import 'package:stackwallet/services/notifications_service.dart';
+import 'package:stackwallet/services/tor_service.dart';
+import 'package:stackwallet/services/trade_service.dart';
+import 'package:stackwallet/services/wallets.dart';
+import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart';
+import 'package:stackwallet/utilities/logger.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/wallet/wallet_mixin_interfaces/electrumx_interface.dart';
+
+import '../hive/hive_ce_test_utils.dart';
+import '../utilities/tls_test_server.dart';
+
+class _Wallet extends Fake implements ElectrumXInterface<Bitcoin> {
+ @override
+ String get walletId => 'watched-wallet';
+ @override
+ Bitcoin get cryptoCurrency => Bitcoin(CryptoCurrencyNetwork.main);
+ @override
+ late ElectrumXClient electrumXClient;
+}
+
+class _Tor extends Fake implements TorService {}
+
+class _Prefs extends Fake implements Prefs {
+ @override
+ bool get useTor => false;
+ @override
+ bool get wifiOnly => false;
+ @override
+ bool get externalCalls => false;
+}
+
+class _Trades extends Fake implements TradesService {}
+
+Future<void> _until(bool Function() done, String waitingFor) async {
+ final watch = Stopwatch()..start();
+ while (!done()) {
+ if (watch.elapsed > const Duration(seconds: 2)) {
+ fail('Timed out waiting for $waitingFor');
+ }
+ await Future<void>.delayed(const Duration(milliseconds: 5));
+ }
+}
+
+void main() {
+ late Directory logs;
+ setUpAll(() async {
+ logs = await Directory.systemTemp.createTemp('notification_tls');
+ await Logging.instance.initialize(logs.path, level: Level.off);
+ });
+ tearDownAll(() => logs.delete(recursive: true));
+
+ /// Watches two transactions of a Bitcoin wallet whose primary node is
+ /// [server], checking every 50ms until the test stops it.
+ Future<({NodeService service, NodeModel node})> watch(
+ TlsElectrumServer server,
+ ) async {
+ await setUpHiveCeTest();
+ final nodeAdapter = NodeModelAdapter();
+ if (!DB.instance.hive.isAdapterRegistered(nodeAdapter.typeId)) {
+ DB.instance.hive.registerAdapter(nodeAdapter);
+ }
+ final notificationAdapter = NotificationModelAdapter();
+ if (!DB.instance.hive.isAdapterRegistered(notificationAdapter.typeId)) {
+ DB.instance.hive.registerAdapter(notificationAdapter);
+ }
+ final nodes = await DB.instance.hive.openBox<NodeModel>(
+ DB.boxNameNodeModels,
+ );
+ final watched = await DB.instance.hive.openBox<NotificationModel>(
+ DB.boxNameWatchedTransactions,
+ );
+ final wallet = _Wallet();
+ final coin = wallet.cryptoCurrency;
+ final node = NodeModel(
+ id: 'n',
+ host: '127.0.0.1',
+ port: server.port,
+ name: 'Node',
+ useSSL: true,
+ enabled: true,
+ coinName: coin.identifier,
+ isFailover: false,
+ isDown: false,
+ torEnabled: true,
+ clearnetEnabled: true,
+ isPrimary: true,
+ trustedCertificatePem: TlsElectrumServer.certificate('node_a'),
+ );
+ await nodes.put(node.id, node);
+ await watched.put(
+ 0,
+ NotificationModel(
+ id: 0,
+ title: 'Transaction (0/${coin.minConfirms})',
+ description: '',
+ iconAssetName: '',
+ date: DateTime.now(),
+ walletId: wallet.walletId,
+ read: false,
+ shouldWatchForUpdates: true,
+ txid: 'a' * 64,
+ coinName: coin.identifier,
+ ),
+ );
+ await watched.put(
+ 1,
+ NotificationModel(
+ id: 1,
+ title: 'Transaction (0/${coin.minConfirms})',
+ description: '',
+ iconAssetName: '',
+ date: DateTime.now(),
+ walletId: wallet.walletId,
+ read: false,
+ shouldWatchForUpdates: true,
+ txid: 'b' * 64,
+ coinName: coin.identifier,
+ ),
+ );
+ final client = ElectrumXClient.from(
+ node: ElectrumXNode(
+ address: node.host,
+ port: node.port,
+ name: node.name,
+ id: node.id,
+ useSSL: true,
+ trustedCertificatePem: node.trustedCertificatePem,
+ torEnabled: true,
+ clearnetEnabled: true,
+ ),
+ prefs: _Prefs(),
+ torService: _Tor(),
+ failovers: const [],
+ cryptoCurrency: coin,
+ );
+ wallet.electrumXClient = client;
+ // The shared registry keeps the wallet added by an earlier test.
+ if (!Wallets.sharedInstance.wallets.any(
+ (e) => e.walletId == wallet.walletId,
+ )) {
+ Wallets.sharedInstance.addWallet(wallet);
+ }
+ final service = NodeService(secureStorageInterface: FakeSecureStorage());
+ final notifications = NotificationsService.instance;
+ await notifications.init(
+ nodeService: service,
+ tradesService: _Trades(),
+ prefs: _Prefs(),
+ );
+ final interval = NotificationsService.notificationRefreshInterval;
+ addTearDown(() async {
+ notifications.stopCheckingWatchedTransactions();
+ NotificationsService.notificationRefreshInterval = interval;
+ await client.closeAdapter();
+ await server.close();
+ await tearDownHiveCeTest();
+ });
+ NotificationsService.notificationRefreshInterval = const Duration(
+ milliseconds: 50,
+ );
+ notifications.startCheckingWatchedNotifications();
+ return (service: service, node: node);
+ }
+
+ test('notification checks use the wallet connection', () async {
+ // A node or approval change replaces the wallet's client through
+ // updateNode(), so the checks need no connection of their own.
+ final server = await TlsElectrumServer.start();
+ await watch(server);
+ await _until(
+ () =>
+ server.methods
+ .where((method) => method == 'blockchain.transaction.get')
+ .length >=
+ 2,
+ 'both watched transactions to be checked',
+ );
+ NotificationsService.instance.stopCheckingWatchedTransactions();
+ expect(server.accepted, 1);
+ expect(server.disconnections, 0);
+ });
+}
### test/utilities/electrum_connection_check_test.dart
@@ -0,0 +1,96 @@
+import 'dart:io';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:logger/logger.dart' show Level;
+import 'package:mockito/mockito.dart';
+import 'package:stackwallet/services/event_bus/events/global/tor_connection_status_changed_event.dart';
+import 'package:stackwallet/services/tor_service.dart';
+import 'package:stackwallet/utilities/connection_check/electrum_connection_check.dart';
+import 'package:stackwallet/utilities/logger.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+
+import 'tls_test_server.dart';
+
+class _TorPrefs extends Mock implements Prefs {
+ @override
+ bool get useTor => true;
+ @override
+ bool get torKillSwitch => false;
+}
+
+class _ConnectedTor extends Mock implements TorService {
+ _ConnectedTor(this.proxy);
+ final ({InternetAddress host, int port}) proxy;
+ @override
+ TorConnectionStatus get status => TorConnectionStatus.connected;
+ @override
+ ({InternetAddress host, int port}) getProxyInfo() => proxy;
+}
+
+void main() {
+ late Directory logDirectory;
+ setUpAll(() async {
+ logDirectory = await Directory.systemTemp.createTemp('electrum_check');
+ await Logging.instance.initialize(logDirectory.path, level: Level.off);
+ });
+ tearDownAll(() => logDirectory.delete(recursive: true));
+
+ // The test server and the test SOCKS proxy both listen on 127.0.0.1; the
+ // onion name is only ever sent to that proxy, never resolved.
+ Future<void> withOnionServer(
+ String? certificateName,
+ Future<void> Function(TlsElectrumServer server, TlsTestProxy proxy) body,
+ ) async {
+ final server = await TlsElectrumServer.start(
+ certificateName: certificateName,
+ );
+ final proxy = await TlsTestProxy.start(server.port);
+ try {
+ await body(server, proxy);
+ } finally {
+ await proxy.close();
+ await server.close();
+ }
+ }
+
+ test('an onion node with SSL is tested over TLS and can be trusted', () {
+ return withOnionServer('node_a', (server, proxy) async {
+ final rejected = await checkElectrumServer(
+ host: 'tlsx.test.onion',
+ port: server.port,
+ useSSL: true,
+ overridePrefs: _TorPrefs(),
+ overrideTorService: _ConnectedTor(proxy.info),
+ );
+ expect(rejected.success, false);
+ expect(rejected.certificate, isNotNull);
+ expect(server.requests, 0);
+ final approved = await checkElectrumServer(
+ host: 'tlsx.test.onion',
+ port: server.port,
+ useSSL: true,
+ trustedCertificatePem: rejected.certificate!.pem,
+ overridePrefs: _TorPrefs(),
+ overrideTorService: _ConnectedTor(proxy.info),
+ );
+ expect(approved.success, true, reason: approved.error?.toString());
+ expect(server.requests, 1);
+ expect(proxy.destinations, everyElement('tlsx.test.onion'));
+ });
+ });
+
+ test('an onion node without SSL is tested in plain text', () {
+ return withOnionServer(null, (server, proxy) async {
+ final result = await checkElectrumServer(
+ host: 'tlsx.test.onion',
+ port: server.port,
+ useSSL: false,
+ overridePrefs: _TorPrefs(),
+ overrideTorService: _ConnectedTor(proxy.info),
+ );
+ expect(result.success, true, reason: result.error?.toString());
+ expect(result.certificate, null);
+ expect(proxy.destinations, ['tlsx.test.onion']);
+ });
+ });
+}
### test/utilities/electrum_tls_test.dart
@@ -0,0 +1,232 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:electrum_adapter/electrum_adapter.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/utilities/connection_check/electrum_connection_check.dart';
+import 'package:stackwallet/utilities/tls_certificate.dart';
+
+import 'tls_test_server.dart';
+
+void main() {
+ final servers = <TlsElectrumServer>[];
+ final proxies = <TlsTestProxy>[];
+
+ Future<TlsElectrumServer> start({
+ String? certificateName = 'node_a',
+ bool respond = true,
+ }) async {
+ final server = await TlsElectrumServer.start(
+ certificateName: certificateName,
+ respond: respond,
+ );
+ servers.add(server);
+ return server;
+ }
+
+ Future<ElectrumConnectionResult> check(
+ TlsElectrumServer server, {
+ String? trustedCertificatePem,
+ String host = '127.0.0.1',
+ bool useSSL = true,
+ ({InternetAddress host, int port})? proxyInfo,
+ Duration timeout = const Duration(seconds: 2),
+ }) => testElectrumConnection(
+ host: host,
+ port: server.port,
+ useSSL: useSSL,
+ trustedCertificatePem: trustedCertificatePem,
+ proxyInfo: proxyInfo,
+ timeout: timeout,
+ );
+
+ tearDown(() async {
+ for (final proxy in proxies) {
+ await proxy.close();
+ }
+ for (final server in servers) {
+ await server.close();
+ }
+ proxies.clear();
+ servers.clear();
+ });
+
+ test('untrusted TLS returns a certificate without sending an RPC', () async {
+ final server = await start();
+ final result = await check(server);
+ expect(result.success, false);
+ expect(result.certificate, isNotNull);
+ expect(
+ certificateDer(result.certificate!.pem),
+ certificateDer(TlsElectrumServer.certificate('node_a')),
+ );
+ expect(
+ trustedCertificateCheck(TlsElectrumServer.certificate('node_a'))!(
+ result.certificate!,
+ ),
+ true,
+ );
+ expect(
+ trustedCertificateCheck(TlsElectrumServer.certificate('node_b'))!(
+ result.certificate!,
+ ),
+ false,
+ );
+ expect(server.requests, 0);
+ });
+
+ test('approval enables RPC and closes the test connection', () async {
+ final server = await start();
+ final rejected = await check(server);
+ final approved = await check(
+ server,
+ trustedCertificatePem: rejected.certificate!.pem,
+ );
+ expect(approved.success, true, reason: approved.error?.toString());
+ expect(server.requests, 1);
+ await Future<void>.delayed(const Duration(milliseconds: 30));
+ expect(server.disconnections, 1);
+ });
+
+ test('approval does not change the default trust store', () async {
+ final server = await start();
+ expect(
+ (await check(
+ server,
+ trustedCertificatePem: TlsElectrumServer.certificate('node_a'),
+ )).success,
+ true,
+ );
+ expect((await check(server)).success, false);
+ });
+
+ test('another certificate is rejected and returned for review', () async {
+ final server = await start(certificateName: 'node_b');
+ final result = await check(
+ server,
+ trustedCertificatePem: TlsElectrumServer.certificate('node_a'),
+ );
+ expect(result.success, false);
+ expect(
+ certificateDer(result.certificate!.pem),
+ certificateDer(TlsElectrumServer.certificate('node_b')),
+ );
+ expect(server.requests, 0);
+ });
+
+ test('invalid saved PEM fails without connecting', () async {
+ final server = await start();
+ final result = await check(server, trustedCertificatePem: 'invalid');
+ expect(result.success, false);
+ expect(result.error, isA<FormatException>());
+ expect(server.requests, 0);
+ });
+
+ test('approval accepts the certificate even after it expired', () async {
+ final server = await start(certificateName: 'expired');
+ final rejected = await check(server);
+ expect(rejected.success, false);
+ expect(rejected.certificate, isNotNull);
+ final approved = await check(
+ server,
+ trustedCertificatePem: TlsElectrumServer.certificate('expired'),
+ );
+ expect(approved.success, true, reason: approved.error?.toString());
+ expect(server.requests, 1);
+ });
+
+ test('plain TCP can be tested without a certificate', () async {
+ final server = await start(certificateName: null);
+ final result = await check(server, useSSL: false);
+ expect(result.success, true);
+ expect(result.certificate, null);
+ });
+
+ test('RPC timeout fails and closes the connection', () async {
+ final server = await start(respond: false);
+ final result = await check(
+ server,
+ trustedCertificatePem: TlsElectrumServer.certificate('node_a'),
+ timeout: const Duration(milliseconds: 200),
+ );
+ expect(result.success, false);
+ expect(result.certificate, null);
+ await Future<void>.delayed(const Duration(milliseconds: 30));
+ expect(server.disconnections, 1);
+ });
+
+ test('SOCKS TLS rejection and approval use the same proxy', () async {
+ final server = await start();
+ final proxy = await TlsTestProxy.start(server.port);
+ proxies.add(proxy);
+ final rejected = await check(
+ server,
+ host: 'tlsx.test.onion',
+ proxyInfo: proxy.info,
+ );
+ expect(rejected.success, false);
+ expect(rejected.certificate, isNotNull);
+ expect(server.requests, 0);
+ final approved = await check(
+ server,
+ host: 'tlsx.test.onion',
+ proxyInfo: proxy.info,
+ trustedCertificatePem: rejected.certificate!.pem,
+ );
+ expect(approved.success, true, reason: approved.error?.toString());
+ expect(proxy.destinations, everyElement('tlsx.test.onion'));
+ expect(proxy.destinations.length, 2);
+ });
+
+ test('approved certificate does not have to match the hostname', () async {
+ final server = await start();
+ final proxy = await TlsTestProxy.start(server.port);
+ proxies.add(proxy);
+ final result = await check(
+ server,
+ host: 'wrong.example',
+ proxyInfo: proxy.info,
+ trustedCertificatePem: TlsElectrumServer.certificate('node_a'),
+ );
+ expect(result.success, true, reason: result.error?.toString());
+ expect(server.requests, 1);
+ });
+
+ for (final proxied in [false, true]) {
+ test(
+ 'a stalled ${proxied ? 'SOCKS' : 'direct'} TLS handshake releases its socket',
+ () async {
+ final stalled = await TlsElectrumServer.start(stallHandshake: true);
+ servers.add(stalled);
+ final proxy = proxied ? await TlsTestProxy.start(stalled.port) : null;
+ if (proxy != null) proxies.add(proxy);
+ final result = await check(
+ stalled,
+ proxyInfo: proxy?.info,
+ timeout: const Duration(milliseconds: 300),
+ ).timeout(const Duration(seconds: 3));
+ expect(result.success, false);
+ expect(result.error, isA<ConnectionTimeoutException>());
+ expect(result.certificate, null);
+ final watch = Stopwatch()..start();
+ while (stalled.disconnections == 0 &&
+ watch.elapsed < const Duration(seconds: 2)) {
+ await Future<void>.delayed(const Duration(milliseconds: 5));
+ }
+ expect(stalled.accepted, 1);
+ expect(stalled.disconnections, 1);
+ },
+ );
+ }
+
+ test('PEM parsing accepts one certificate and rejects bundles', () {
+ final pem = TlsElectrumServer.certificate('node_a');
+ expect(
+ certificateFingerprint(certificateDer(pem)),
+ matches(RegExp(r'^(?:[0-9A-F]{2}:){31}[0-9A-F]{2}$')),
+ );
+ expect(() => certificateDer('$pem$pem'), throwsFormatException);
+ expect(trustedCertificateCheck(null), null);
+ expect(() => trustedCertificateCheck('invalid'), throwsFormatException);
+ });
+}
### test/utilities/mock_electrum_server.dart
@@ -5,12 +5,10 @@ import 'package:electrum_adapter/electrum_adapter.dart';
import 'package:event_bus/event_bus.dart';
import 'package:json_rpc_2/json_rpc_2.dart' as rpc;
import 'package:stackwallet/app_config.dart';
-import 'package:stackwallet/electrumx_rpc/client_manager.dart';
import 'package:stackwallet/electrumx_rpc/electrumx_client.dart';
import 'package:stackwallet/services/event_bus/events/global/tor_connection_status_changed_event.dart';
import 'package:stackwallet/services/tor_service.dart';
import 'package:stackwallet/utilities/prefs.dart';
-import 'package:stackwallet/utilities/tor_plain_net_option_enum.dart';
import 'package:stackwallet/wallets/crypto_currency/coins/firo.dart';
import 'package:stream_channel/stream_channel.dart';
@@ -26,6 +24,11 @@ class MockElectrumServer {
this.useSSL = true,
}) : _handlers = Map<String, MockElectrumHandler>.from(handlers),
_latestHeader = initialHeader ?? BlockHeader('00', 1) {
+ _handlers.putIfAbsent(
+ 'server.version',
+ () =>
+ (_) => ['mock', '1.4'],
+ );
_handlers.putIfAbsent(
'blockchain.headers.subscribe',
() =>
@@ -137,60 +140,42 @@ class ManagedElectrumXClient extends ElectrumXClient {
@override
Future<void> checkElectrumAdapter() async {
- ({InternetAddress host, int port})? proxyInfo;
-
- if (AppConfig.hasFeature(AppFeature.tor)) {
- if (_prefsForTest.useTor) {
- if (_torServiceForTest.status != TorConnectionStatus.connected) {
- if (_prefsForTest.torKillSwitch) {
- throw Exception(
- 'Tor preference and killswitch set but Tor is not enabled, '
- 'not connecting to Electrum adapter',
- );
- }
- } else {
- proxyInfo = _torServiceForTest.getProxyInfo();
- }
-
- if (netType == TorPlainNetworkOption.clear) {
- await (await ClientManager.sharedInstance.remove(
- cryptoCurrency: cryptoCurrency,
- )).$1?.close();
- }
- } else if (netType == TorPlainNetworkOption.tor) {
- await (await ClientManager.sharedInstance.remove(
- cryptoCurrency: cryptoCurrency,
- )).$1?.close();
- }
- }
-
- final existing = getElectrumAdapter();
- if (existing != null && !existing.peer.isClosed) {
- return;
- }
- if (existing != null) {
- await (await ClientManager.sharedInstance.remove(
- cryptoCurrency: cryptoCurrency,
- )).$1?.close();
+ if (AppConfig.hasFeature(AppFeature.tor) &&
+ _prefsForTest.useTor &&
+ _torServiceForTest.status != TorConnectionStatus.connected &&
+ _prefsForTest.torKillSwitch) {
+ throw Exception(
+ 'Tor preference and killswitch set but Tor is not enabled, '
+ 'not connecting to Electrum adapter',
+ );
}
+ await super.checkElectrumAdapter();
+ }
- final server = proxyInfo != null ? (torServer ?? clearServer) : clearServer;
- final adapter = cryptoCurrency is Firo
- ? await server.createFiroElectrumClient(proxyInfo: proxyInfo)
- : await server.createElectrumClient(proxyInfo: proxyInfo);
-
- await ClientManager.sharedInstance.addClient(
- adapter,
- cryptoCurrency: cryptoCurrency,
- netType: netType,
- );
+ /// Serves this client from the in-memory mock: the Tor server when the
+ /// client chose a proxy, otherwise the clearnet server.
+ @override
+ Future<ElectrumClient> openConnection({
+ required String host,
+ required int port,
+ required bool useSSL,
+ required ({InternetAddress host, int port})? proxy,
+ required bool Function(X509Certificate)? onBadCertificate,
+ }) async {
+ final server = proxy != null ? (torServer ?? clearServer) : clearServer;
+ return cryptoCurrency is Firo
+ ? await server.createFiroElectrumClient(proxyInfo: proxy)
+ : await server.createElectrumClient(proxyInfo: proxy);
}
}
Future<void> tearDownManagedElectrum({
+ Iterable<ElectrumXClient> clients = const [],
Iterable<MockElectrumServer> servers = const [],
}) async {
- await ClientManager.sharedInstance.closeAll();
+ for (final client in clients) {
+ await client.closeAdapter();
+ }
for (final server in servers) {
await server.close();
}
### test/utilities/monero_socks_write_test.dart
@@ -0,0 +1,116 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:async/async.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:logger/logger.dart' show Level;
+import 'package:stackwallet/utilities/logger.dart';
+import 'package:stackwallet/utilities/test_monero_node_connection.dart';
+
+class _Reader {
+ _Reader(Socket socket) : input = StreamQueue(socket);
+ final StreamQueue<List<int>> input;
+ final bytes = <int>[];
+ Future<List<int>> take(int count) async {
+ while (bytes.length < count) {
+ bytes.addAll(await input.next);
+ }
+ final result = bytes.sublist(0, count);
+ bytes.removeRange(0, count);
+ return result;
+ }
+}
+
+void main() {
+ test('Monero handles SOCKS resets without uncaught write errors', () async {
+ final logs = await Directory.systemTemp.createTemp(
+ 'monero_dependency_probe',
+ );
+ await Logging.instance.initialize(logs.path, level: Level.off);
+ final proxy = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
+ final peers = <Socket>[];
+ final handlers = <Future<void>>[];
+ var accepted = 0;
+ final subscription = proxy.listen((socket) {
+ peers.add(socket);
+ final ordinal = accepted++;
+ final handler = () async {
+ final reader = _Reader(socket);
+ try {
+ final greeting = await reader.take(2);
+ await reader.take(greeting[1]);
+ socket.add([5, 0]);
+ final connect = await reader.take(4);
+ if (connect[3] == 3) {
+ await reader.take((await reader.take(1)).single);
+ } else {
+ await reader.take(4);
+ }
+ await reader.take(2);
+ socket.add([5, 0, 0, 1, 127, 0, 0, 1, 0, 0]);
+ await socket.flush();
+ if (ordinal % 3 != 0) {
+ await Future<void>.delayed(Duration(milliseconds: ordinal % 3));
+ }
+ final linger = Int32List.fromList([1, 0]);
+ socket.setRawOption(
+ RawSocketOption(
+ RawSocketOption.levelSocket,
+ Platform.isMacOS ? 0x0080 : 13,
+ linger.buffer.asUint8List(),
+ ),
+ );
+ socket.destroy();
+ } catch (_) {
+ socket.destroy();
+ } finally {
+ await reader.input.cancel();
+ }
+ }();
+ handlers.add(handler);
+ });
+ addTearDown(() async {
+ for (final peer in peers) {
+ peer.destroy();
+ }
+ await subscription.cancel();
+ await proxy.close();
+ await Future.wait(handlers);
+ await logs.delete(recursive: true);
+ });
+
+ final results = <Map<String, Object?>>[];
+ for (var i = 0; i < 15; i++) {
+ final uncaught = <String>[];
+ final completed = Completer<Map<String, Object?>>();
+ runZonedGuarded(
+ () async {
+ Object? outcome;
+ try {
+ outcome = (await testMoneroNodeConnection(
+ Uri.parse('http://node.example.onion:18081/json_rpc'),
+ null,
+ null,
+ false,
+ proxyInfo: (host: InternetAddress.loopbackIPv4, port: proxy.port),
+ ).timeout(const Duration(milliseconds: 500))).success;
+ } catch (error) {
+ outcome = error.runtimeType.toString();
+ }
+ await Future<void>.delayed(const Duration(milliseconds: 20));
+ completed.complete({'outcome': outcome, 'uncaught': uncaught});
+ },
+ (Object error, StackTrace stack) {
+ uncaught.add('${error.runtimeType}: $error');
+ },
+ );
+ results.add(await completed.future.timeout(const Duration(seconds: 2)));
+ }
+ expect(results, hasLength(15));
+ expect(
+ results.expand((result) => result['uncaught'] as List<String>),
+ isEmpty,
+ );
+ });
+}
### test/utilities/test_electrum_node_connection_test.dart
@@ -0,0 +1,205 @@
+import 'dart:async';
+
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/models/node_form_data.dart';
+import 'package:stackwallet/utilities/connection_check/electrum_connection_check.dart';
+import 'package:stackwallet/utilities/tor_plain_net_option_enum.dart';
+
+import 'tls_test_server.dart';
+
+void main() {
+ late TlsElectrumServer server;
+ late NodeFormData data;
+ int approvals = 0;
+ int successes = 0;
+
+ setUp(() async {
+ server = await TlsElectrumServer.start();
+ data = NodeFormData()
+ ..host = '127.0.0.1'
+ ..port = server.port
+ ..useSSL = true;
+ approvals = 0;
+ successes = 0;
+ });
+ tearDown(() => server.close());
+
+ Future<bool> testNode({
+ bool approve = true,
+ Future<bool> Function()? approval,
+ ElectrumNodeTester? tester,
+ bool Function()? isActive,
+ }) => testElectrumNodeConnection(
+ data,
+ isActive: isActive ?? () => true,
+ onSuccess: (_) => successes++,
+ requestTrust: (certificate, host, port) async {
+ approvals++;
+ expect(host, '127.0.0.1');
+ expect(port, server.port);
+ return approval == null ? approve : await approval();
+ },
+ testConnection:
+ tester ??
+ ({
+ required host,
+ required port,
+ required useSSL,
+ trustedCertificatePem,
+ }) => testElectrumConnection(
+ host: host,
+ port: port,
+ useSSL: useSSL,
+ trustedCertificatePem: trustedCertificatePem,
+ timeout: const Duration(seconds: 2),
+ ),
+ );
+
+ test('Cancel leaves the form untrusted and sends no RPC', () async {
+ expect(await testNode(approve: false), false);
+ expect(data.trustedCertificatePem, null);
+ expect(approvals, 1);
+ expect(successes, 0);
+ expect(server.requests, 0);
+ });
+
+ test(
+ 'Trust saves the reviewed certificate after a successful RPC retry',
+ () async {
+ expect(await testNode(), true);
+ expect(
+ data.trustedCertificatePem,
+ TlsElectrumServer.certificate('node_a'),
+ );
+ expect(approvals, 1);
+ expect(successes, 1);
+ expect(server.requests, 1);
+ expect(await testNode(), true);
+ expect(approvals, 1);
+ expect(successes, 2);
+ },
+ );
+
+ test('a failed retry saves no approval', () async {
+ final rejected = await testElectrumConnection(
+ host: data.host!,
+ port: data.port!,
+ useSSL: true,
+ timeout: const Duration(seconds: 2),
+ );
+ expect(
+ await testNode(
+ tester:
+ ({
+ required host,
+ required port,
+ required useSSL,
+ trustedCertificatePem,
+ }) async => trustedCertificatePem == null
+ ? rejected
+ : const ElectrumConnectionResult(
+ success: false,
+ error: 'still rejected',
+ ),
+ ),
+ false,
+ );
+ expect(data.trustedCertificatePem, null);
+ expect(successes, 0);
+ });
+
+ test('editing the endpoint during review cancels the retry', () async {
+ expect(
+ await testNode(
+ approval: () async {
+ data.host = 'another.example';
+ return true;
+ },
+ ),
+ false,
+ );
+ expect(data.trustedCertificatePem, null);
+ expect(server.requests, 0);
+ });
+
+ test('leaving the screen during review cancels the retry', () async {
+ bool active = true;
+ expect(
+ await testNode(
+ isActive: () => active,
+ approval: () async {
+ active = false;
+ return true;
+ },
+ ),
+ false,
+ );
+ expect(data.trustedCertificatePem, null);
+ expect(server.requests, 0);
+ });
+
+ test('changing the network option during review cancels approval', () async {
+ expect(
+ await testNode(
+ approval: () async {
+ data.netOption = TorPlainNetworkOption.tor;
+ return true;
+ },
+ ),
+ false,
+ );
+ expect(data.trustedCertificatePem, null);
+ expect(server.requests, 0);
+ });
+
+ test('a late successful retry cannot trust a changed endpoint', () async {
+ final retry = Completer<ElectrumConnectionResult>();
+ final retryStarted = Completer<void>();
+ final rejected = await testElectrumConnection(
+ host: data.host!,
+ port: data.port!,
+ useSSL: true,
+ timeout: const Duration(seconds: 2),
+ );
+ final result = testNode(
+ tester:
+ ({
+ required host,
+ required port,
+ required useSSL,
+ trustedCertificatePem,
+ }) async {
+ if (trustedCertificatePem == null) return rejected;
+ retryStarted.complete();
+ return retry.future;
+ },
+ );
+ await retryStarted.future;
+ data.port = data.port! + 1;
+ retry.complete(const ElectrumConnectionResult(success: true));
+ expect(await result, false);
+ expect(data.trustedCertificatePem, null);
+ expect(successes, 0);
+ });
+ for (final clearThenRestore in [false, true]) {
+ test(
+ 'an intervening certificate decision cancels review ($clearThenRestore)',
+ () async {
+ final before = data.trustedCertificatePem;
+ expect(
+ await testNode(
+ approval: () async {
+ data.forgetCertificate();
+ if (clearThenRestore) data.trustedCertificatePem = before;
+ return true;
+ },
+ ),
+ false,
+ );
+ expect(data.trustedCertificatePem, null);
+ expect(server.requests, 0);
+ expect(successes, 0);
+ },
+ );
+ }
+}
### test/utilities/tls_test_server.dart
@@ -0,0 +1,326 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+import 'dart:math';
+
+import 'package:async/async.dart';
+import 'package:basic_utils/basic_utils.dart';
+import 'package:pointycastle/asn1.dart';
+import 'package:pointycastle/export.dart';
+
+/// Certificates for the test servers, built in Dart so the tests need no
+/// native tooling. The 'expired' certificate is a committed fixture; the
+/// others are generated once per test process from the committed test keys.
+final _certificates = <String, String>{};
+
+String _keyPem(String name) =>
+ File('test/fixtures/tls/$name.key.pem').readAsStringSync();
+
+String _certificatePem(String name) {
+ if (name == 'expired') {
+ return File('test/fixtures/tls/expired.pem').readAsStringSync();
+ }
+ return _certificates[name] ??= generateServerCertificatePem(
+ privateKeyPem: _keyPem(name),
+ commonName: 'localhost',
+ validity: const Duration(days: 1),
+ );
+}
+
+/// A self-signed X.509 server certificate, SHA-256 with RSA, in PEM.
+String generateServerCertificatePem({
+ required String privateKeyPem,
+ required String commonName,
+ required Duration validity,
+}) {
+ final privateKey = CryptoUtils.rsaPrivateKeyFromPem(privateKeyPem);
+ final now = DateTime.now().toUtc();
+
+ ASN1Sequence algorithm(String oid) => ASN1Sequence(
+ elements: [ASN1ObjectIdentifier.fromIdentifierString(oid), ASN1Null()],
+ );
+ final name = ASN1Sequence(
+ elements: [
+ ASN1Set(
+ elements: [
+ ASN1Sequence(
+ elements: [
+ ASN1ObjectIdentifier.fromIdentifierString('2.5.4.3'),
+ ASN1UTF8String(utf8StringValue: commonName),
+ ],
+ ),
+ ],
+ ),
+ ],
+ );
+ final publicKeyInfo = ASN1Sequence(
+ elements: [
+ algorithm('1.2.840.113549.1.1.1'),
+ ASN1BitString(
+ stringValues: ASN1Sequence(
+ elements: [
+ ASN1Integer(privateKey.modulus!),
+ ASN1Integer(privateKey.publicExponent!),
+ ],
+ ).encode(),
+ ),
+ ],
+ );
+ final random = Random.secure();
+ final serial =
+ (BigInt.from(random.nextInt(1 << 31)) << 32) +
+ BigInt.from(random.nextInt(1 << 32));
+ final tbsCertificate = ASN1Sequence(
+ elements: [
+ ASN1Integer(serial),
+ algorithm('1.2.840.113549.1.1.11'),
+ name,
+ ASN1Sequence(
+ elements: [
+ ASN1UtcTime(now.subtract(const Duration(hours: 1))),
+ ASN1UtcTime(now.add(validity)),
+ ],
+ ),
+ name,
+ publicKeyInfo,
+ ],
+ );
+ final signer = RSASigner(SHA256Digest(), '0609608648016503040201')
+ ..init(true, PrivateKeyParameter<RSAPrivateKey>(privateKey));
+ final signature = signer.generateSignature(tbsCertificate.encode());
+ final certificate = ASN1Sequence(
+ elements: [
+ tbsCertificate,
+ algorithm('1.2.840.113549.1.1.11'),
+ ASN1BitString(stringValues: signature.bytes),
+ ],
+ );
+ final body = base64Encode(certificate.encode());
+ final lines = [
+ for (var i = 0; i < body.length; i += 64)
+ body.substring(i, min(i + 64, body.length)),
+ ];
+ return '-----BEGIN CERTIFICATE-----\n${lines.join('\n')}\n'
+ '-----END CERTIFICATE-----\n';
+}
+
+/// Loopback fixtures only; the private keys under fixtures/tls are test keys.
+class TlsElectrumServer {
+ TlsElectrumServer._(this._server);
+
+ final ServerSocket _server;
+ final _sockets = <Socket>[];
+ late final StreamSubscription<Socket> _subscription;
+ int requests = 0;
+ final methods = <String>[];
+ int disconnections = 0;
+ int accepted = 0;
+ int get port => _server.port;
+
+ static String certificate(String name) => _certificatePem(name);
+
+ /// With [versionError], server.version is answered with a JSON-RPC error,
+ /// as a server that rejects the client would.
+ static Future<TlsElectrumServer> start({
+ String? certificateName = 'node_a',
+ bool respond = true,
+ bool versionError = false,
+ bool stallHandshake = false,
+ Set<String> ignoredMethods = const {},
+ }) async {
+ final server = TlsElectrumServer._(
+ await ServerSocket.bind(InternetAddress.loopbackIPv4, 0),
+ );
+ final context = certificateName == null
+ ? null
+ : (SecurityContext()
+ ..useCertificateChainBytes(
+ utf8.encode(_certificatePem(certificateName)),
+ )
+ ..usePrivateKeyBytes(utf8.encode(_keyPem(certificateName))));
+ server._subscription = server._server.listen((raw) async {
+ server.accepted++;
+ server._sockets.add(raw);
+ raw.done.ignore();
+ if (stallHandshake) {
+ raw.listen(
+ (_) {},
+ onError: (Object _) {},
+ onDone: () => server.disconnections++,
+ );
+ return;
+ }
+ try {
+ final socket = context == null
+ ? raw
+ : await SecureSocket.secureServer(raw, context);
+ server._sockets.add(socket);
+ socket.done.ignore();
+ socket
+ .cast<List<int>>()
+ .transform(utf8.decoder)
+ .transform(const LineSplitter())
+ .listen(
+ (line) {
+ final decoded = jsonDecode(line);
+ final replies = <Map<String, dynamic>>[];
+ for (final request in decoded is List ? decoded : [decoded]) {
+ server.requests++;
+ server.methods.add(request['method'] as String);
+ if (!respond || ignoredMethods.contains(request['method'])) {
+ continue;
+ }
+ if (versionError && request['method'] == 'server.version') {
+ replies.add({
+ 'jsonrpc': '2.0',
+ 'id': request['id'],
+ 'error': {'code': -32601, 'message': 'unsupported'},
+ });
+ continue;
+ }
+ final Object result;
+ switch (request['method']) {
+ case 'server.version':
+ result = ['ElectrumX TLS test', '1.4'];
+ case 'blockchain.headers.subscribe':
+ result = {'height': 100, 'hex': '00' * 80};
+ case 'blockchain.transaction.get':
+ result = {
+ 'txid': request['params'][0],
+ 'confirmations': 3,
+ };
+ default:
+ result = {};
+ }
+ replies.add({
+ 'jsonrpc': '2.0',
+ 'id': request['id'],
+ 'result': result,
+ });
+ }
+ if (replies.isNotEmpty) {
+ socket.write(
+ '${jsonEncode(decoded is List ? replies : replies.single)}\n',
+ );
+ }
+ },
+ onError: (Object _) {},
+ onDone: () {
+ server.disconnections++;
+ },
+ );
+ } catch (_) {
+ raw.destroy();
+ }
+ });
+ return server;
+ }
+
+ void disconnectClients() {
+ for (final socket in _sockets) {
+ socket.destroy();
+ }
+ _sockets.clear();
+ }
+
+ Future<void> close() async {
+ disconnectClients();
+ await _subscription.cancel();
+ await _server.close();
+ }
+}
+
+/// A local SOCKS5 tunnel that records destination names without DNS lookups.
+class TlsTestProxy {
+ TlsTestProxy._(this._server, this.destinationPort, this.greetingDelay);
+
+ final ServerSocket _server;
+ final int destinationPort;
+ final Duration greetingDelay;
+ final destinations = <String>[];
+ final connected = Completer<void>();
+ final _sockets = <Socket>[];
+ late final StreamSubscription<Socket> _subscription;
+ ({InternetAddress host, int port}) get info =>
+ (host: InternetAddress.loopbackIPv4, port: _server.port);
+
+ static Future<TlsTestProxy> start(
+ int destinationPort, {
+ Duration greetingDelay = Duration.zero,
+ }) async {
+ final proxy = TlsTestProxy._(
+ await ServerSocket.bind(InternetAddress.loopbackIPv4, 0),
+ destinationPort,
+ greetingDelay,
+ );
+ proxy._subscription = proxy._server.listen(proxy._forward);
+ return proxy;
+ }
+
+ Future<void> _forward(Socket client) async {
+ _sockets.add(client);
+ if (!connected.isCompleted) connected.complete();
+ final input = _SocketReader(client);
+ bool inputForwarded = false;
+ try {
+ final greeting = await input.read(2);
+ await input.read(greeting[1]);
+ if (greetingDelay != Duration.zero) {
+ await Future<void>.delayed(greetingDelay);
+ }
+ client.add([5, 0]);
+ final header = await input.read(4);
+ final String host;
+ switch (header[3]) {
+ case 3:
+ final length = (await input.read(1)).single;
+ host = utf8.decode(await input.read(length));
+ case 1:
+ host = (await input.read(4)).join('.');
+ default:
+ throw StateError('Unexpected SOCKS destination type');
+ }
+ await input.read(2);
+ destinations.add(host);
+ final upstream = await Socket.connect(
+ InternetAddress.loopbackIPv4,
+ destinationPort,
+ );
+ _sockets.add(upstream);
+ client.add([5, 0, 0, 1, 127, 0, 0, 1, 0, 0]);
+ if (input.pending.isNotEmpty) upstream.add(input.pending);
+ final remainingInput = input.queue.rest;
+ inputForwarded = true;
+ await Future.wait([
+ remainingInput.pipe(upstream),
+ upstream.cast<List<int>>().pipe(client),
+ ]);
+ } catch (_) {
+ client.destroy();
+ if (!inputForwarded) await input.queue.cancel();
+ }
+ }
+
+ Future<void> close() async {
+ for (final socket in _sockets) {
+ socket.destroy();
+ }
+ await _subscription.cancel();
+ await _server.close();
+ }
+}
+
+class _SocketReader {
+ _SocketReader(Socket socket) : queue = StreamQueue(socket.cast<List<int>>());
+ final StreamQueue<List<int>> queue;
+ List<int> pending = [];
+
+ Future<List<int>> read(int count) async {
+ while (pending.length < count) {
+ pending.addAll(await queue.next);
+ }
+ final value = pending.sublist(0, count);
+ pending = pending.sublist(count);
+ return value;
+ }
+}
### test/widget_tests/node_card_test.dart
@@ -77,9 +77,8 @@ void main() {
when(
nodeService.getPrimaryNodeFor(currency: bitcoin),
).thenAnswer((_) => buildNode(id: 'other node id', name: 'Stack Default'));
- when(
- nodeService.getNodeById(id: 'node id'),
- ).thenAnswer((_) => buildNode(id: 'node id', name: 'some other name'));
+ when(nodeService.getNodeById(id: 'node id'))
+ .thenAnswer((_) => buildNode(id: 'node id', name: 'some other name'));
await pumpSubject(
tester,
@@ -101,9 +100,8 @@ void main() {
final nodeService = MockNodeService();
final activeNode = buildNode(id: 'node id', name: 'Some other node name');
- when(
- nodeService.getPrimaryNodeFor(currency: bitcoin),
- ).thenAnswer((_) => activeNode);
+ when(nodeService.getPrimaryNodeFor(currency: bitcoin))
+ .thenAnswer((_) => activeNode);
when(nodeService.getNodeById(id: 'node id')).thenAnswer((_) => activeNode);
await pumpSubject(
@@ -127,9 +125,8 @@ void main() {
final nodeService = MockNodeService();
final activeNode = buildNode(id: 'node id', name: 'Stack Default');
- when(
- nodeService.getPrimaryNodeFor(currency: bitcoin),
- ).thenAnswer((_) => activeNode);
+ when(nodeService.getPrimaryNodeFor(currency: bitcoin))
+ .thenAnswer((_) => activeNode);
when(nodeService.getNodeById(id: 'node id')).thenAnswer((_) => activeNode);
await pumpSubject(
@@ -178,9 +175,8 @@ void main() {
when(nodeService.getPrimaryNodeFor(currency: bitcoin)).thenAnswer(
(_) => buildNode(id: 'other node id', name: 'Some other node name'),
);
- when(
- nodeService.getNodeById(id: 'node id'),
- ).thenAnswer((_) => disconnectedNode);
+ when(nodeService.getNodeById(id: 'node id'))
+ .thenAnswer((_) => disconnectedNode);
await pumpSubject(
tester,
@@ -211,10 +207,9 @@ void main() {
expect(platformOverrides.connectionInvocations.single.host, '127.0.0.1');
verifyNever(
- nodeService.setPrimaryNodeFor(
- coin: bitcoin,
+ nodeService.commitConnectionTest(
node: anyNamed('node'),
- shouldNotifyListeners: anyNamed('shouldNotifyListeners'),
+ formData: anyNamed('formData'),
),
);
},
### test/widget_tests/node_card_test.mocks.dart
@@ -8,6 +8,7 @@ import 'dart:ui' as _i8;
import 'package:mockito/mockito.dart' as _i1;
import 'package:stackwallet/models/epicbox_server_model.dart' as _i7;
+import 'package:stackwallet/models/node_form_data.dart' as _iTls;
import 'package:stackwallet/models/node_model.dart' as _i4;
import 'package:stackwallet/services/node_service.dart' as _i3;
import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart'
@@ -45,77 +46,65 @@ class MockNodeService extends _i1.Mock implements _i3.NodeService {
}
@override
- _i2.SecureStorageInterface get secureStorageInterface =>
- (super.noSuchMethod(
- Invocation.getter(#secureStorageInterface),
- returnValue: _FakeSecureStorageInterface_0(
- this,
- Invocation.getter(#secureStorageInterface),
- ),
- )
- as _i2.SecureStorageInterface);
+ _i2.SecureStorageInterface get secureStorageInterface => (super.noSuchMethod(
+ Invocation.getter(#secureStorageInterface),
+ returnValue: _FakeSecureStorageInterface_0(
+ this,
+ Invocation.getter(#secureStorageInterface),
+ ),
+ ) as _i2.SecureStorageInterface);
@override
- List<_i4.NodeModel> get primaryNodes =>
- (super.noSuchMethod(
- Invocation.getter(#primaryNodes),
- returnValue: <_i4.NodeModel>[],
- )
- as List<_i4.NodeModel>);
+ List<_i4.NodeModel> get primaryNodes => (super.noSuchMethod(
+ Invocation.getter(#primaryNodes),
+ returnValue: <_i4.NodeModel>[],
+ ) as List<_i4.NodeModel>);
@override
- List<_i4.NodeModel> get nodes =>
- (super.noSuchMethod(
- Invocation.getter(#nodes),
- returnValue: <_i4.NodeModel>[],
- )
- as List<_i4.NodeModel>);
+ List<_i4.NodeModel> get nodes => (super.noSuchMethod(
+ Invocation.getter(#nodes),
+ returnValue: <_i4.NodeModel>[],
+ ) as List<_i4.NodeModel>);
@override
bool get hasListeners =>
(super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false)
as bool);
@override
- _i5.Future<void> updateDefaults() =>
- (super.noSuchMethod(
- Invocation.method(#updateDefaults, []),
- returnValue: _i5.Future<void>.value(),
- returnValueForMissingStub: _i5.Future<void>.value(),
- )
- as _i5.Future<void>);
+ _i5.Future<void> updateDefaults() => (super.noSuchMethod(
+ Invocation.method(#updateDefaults, []),
+ returnValue: _i5.Future<void>.value(),
+ returnValueForMissingStub: _i5.Future<void>.value(),
+ ) as _i5.Future<void>);
@override
_i5.Future<void> setPrimaryNodeFor({
required _i6.CryptoCurrency? coin,
required _i4.NodeModel? node,
bool? shouldNotifyListeners = false,
- }) =>
- (super.noSuchMethod(
- Invocation.method(#setPrimaryNodeFor, [], {
- #coin: coin,
- #node: node,
- #shouldNotifyListeners: shouldNotifyListeners,
- }),
- returnValue: _i5.Future<void>.value(),
- returnValueForMissingStub: _i5.Future<void>.value(),
- )
- as _i5.Future<void>);
+ }) => (super.noSuchMethod(
+ Invocation.method(#setPrimaryNodeFor, [], {
+ #coin: coin,
+ #node: node,
+ #shouldNotifyListeners: shouldNotifyListeners,
+ }),
+ returnValue: _i5.Future<void>.value(),
+ returnValueForMissingStub: _i5.Future<void>.value(),
+ ) as _i5.Future<void>);
@override
_i4.NodeModel? getPrimaryNodeFor({required _i6.CryptoCurrency? currency}) =>
(super.noSuchMethod(
- Invocation.method(#getPrimaryNodeFor, [], {#currency: currency}),
- )
- as _i4.NodeModel?);
+ Invocation.method(#getPrimaryNodeFor, [], {#currency: currency}),
+ ) as _i4.NodeModel?);
@override
List<_i4.NodeModel> getNodesFor(_i6.CryptoCurrency? coin) =>
(super.noSuchMethod(
- Invocation.method(#getNodesFor, [coin]),
- returnValue: <_i4.NodeModel>[],
- )
- as List<_i4.NodeModel>);
+ Invocation.method(#getNodesFor, [coin]),
+ returnValue: <_i4.NodeModel>[],
+ ) as List<_i4.NodeModel>);
@override
_i4.NodeModel? getNodeById({required String? id}) =>
@@ -125,83 +114,78 @@ class MockNodeService extends _i1.Mock implements _i3.NodeService {
@override
List<_i4.NodeModel> failoverNodesFor({
required _i6.CryptoCurrency? currency,
- }) =>
- (super.noSuchMethod(
- Invocation.method(#failoverNodesFor, [], {#currency: currency}),
- returnValue: <_i4.NodeModel>[],
- )
- as List<_i4.NodeModel>);
+ }) => (super.noSuchMethod(
+ Invocation.method(#failoverNodesFor, [], {#currency: currency}),
+ returnValue: <_i4.NodeModel>[],
+ ) as List<_i4.NodeModel>);
@override
_i5.Future<void> save(
_i4.NodeModel? node,
String? password,
bool? shouldNotifyListeners,
- ) =>
- (super.noSuchMethod(
- Invocation.method(#save, [node, password, shouldNotifyListeners]),
- returnValue: _i5.Future<void>.value(),
- returnValueForMissingStub: _i5.Future<void>.value(),
- )
- as _i5.Future<void>);
+ ) => (super.noSuchMethod(
+ Invocation.method(#save, [node, password, shouldNotifyListeners]),
+ returnValue: _i5.Future<void>.value(),
+ returnValueForMissingStub: _i5.Future<void>.value(),
+ ) as _i5.Future<void>);
+
+ @override
+ _i5.Future<bool> commitConnectionTest({
+ required _i4.NodeModel? node,
+ required _iTls.NodeFormData? formData,
+ }) => (super.noSuchMethod(
+ Invocation.method(#commitConnectionTest, [], {
+ #node: node,
+ #formData: formData,
+ }),
+ returnValue: _i5.Future<bool>.value(false),
+ ) as _i5.Future<bool>);
@override
_i5.Future<void> delete(String? id, bool? shouldNotifyListeners) =>
(super.noSuchMethod(
- Invocation.method(#delete, [id, shouldNotifyListeners]),
- returnValue: _i5.Future<void>.value(),
- returnValueForMissingStub: _i5.Future<void>.value(),
- )
- as _i5.Future<void>);
+ Invocation.method(#delete, [id, shouldNotifyListeners]),
+ returnValue: _i5.Future<void>.value(),
+ returnValueForMissingStub: _i5.Future<void>.value(),
+ ) as _i5.Future<void>);
@override
_i5.Future<void> setEnabledState(
String? id,
bool? enabled,
bool? shouldNotifyListeners,
- ) =>
- (super.noSuchMethod(
- Invocation.method(#setEnabledState, [
- id,
- enabled,
- shouldNotifyListeners,
- ]),
- returnValue: _i5.Future<void>.value(),
- returnValueForMissingStub: _i5.Future<void>.value(),
- )
- as _i5.Future<void>);
+ ) => (super.noSuchMethod(
+ Invocation.method(#setEnabledState, [id, enabled, shouldNotifyListeners]),
+ returnValue: _i5.Future<void>.value(),
+ returnValueForMissingStub: _i5.Future<void>.value(),
+ ) as _i5.Future<void>);
@override
- _i5.Future<void> updateDefaultEpicBoxes() =>
- (super.noSuchMethod(
- Invocation.method(#updateDefaultEpicBoxes, []),
- returnValue: _i5.Future<void>.value(),
- returnValueForMissingStub: _i5.Future<void>.value(),
- )
- as _i5.Future<void>);
+ _i5.Future<void> updateDefaultEpicBoxes() => (super.noSuchMethod(
+ Invocation.method(#updateDefaultEpicBoxes, []),
+ returnValue: _i5.Future<void>.value(),
+ returnValueForMissingStub: _i5.Future<void>.value(),
+ ) as _i5.Future<void>);
@override
_i5.Future<void> setPrimaryEpicBox({
required _i7.EpicBoxServerModel? epicBox,
bool? shouldNotifyListeners = false,
- }) =>
- (super.noSuchMethod(
- Invocation.method(#setPrimaryEpicBox, [], {
- #epicBox: epicBox,
- #shouldNotifyListeners: shouldNotifyListeners,
- }),
- returnValue: _i5.Future<void>.value(),
- returnValueForMissingStub: _i5.Future<void>.value(),
- )
- as _i5.Future<void>);
+ }) => (super.noSuchMethod(
+ Invocation.method(#setPrimaryEpicBox, [], {
+ #epicBox: epicBox,
+ #shouldNotifyListeners: shouldNotifyListeners,
+ }),
+ returnValue: _i5.Future<void>.value(),
+ returnValueForMissingStub: _i5.Future<void>.value(),
+ ) as _i5.Future<void>);
@override
- List<_i7.EpicBoxServerModel> getEpicBoxes() =>
- (super.noSuchMethod(
- Invocation.method(#getEpicBoxes, []),
- returnValue: <_i7.EpicBoxServerModel>[],
- )
- as List<_i7.EpicBoxServerModel>);
+ List<_i7.EpicBoxServerModel> getEpicBoxes() => (super.noSuchMethod(
+ Invocation.method(#getEpicBoxes, []),
+ returnValue: <_i7.EpicBoxServerModel>[],
+ ) as List<_i7.EpicBoxServerModel>);
@override
_i7.EpicBoxServerModel? getEpicBoxById({required String? id}) =>
@@ -212,31 +196,26 @@ class MockNodeService extends _i1.Mock implements _i3.NodeService {
_i5.Future<void> addEpicBox(
_i7.EpicBoxServerModel? epicBox,
bool? shouldNotifyListeners,
- ) =>
- (super.noSuchMethod(
- Invocation.method(#addEpicBox, [epicBox, shouldNotifyListeners]),
- returnValue: _i5.Future<void>.value(),
- returnValueForMissingStub: _i5.Future<void>.value(),
- )
- as _i5.Future<void>);
+ ) => (super.noSuchMethod(
+ Invocation.method(#addEpicBox, [epicBox, shouldNotifyListeners]),
+ returnValue: _i5.Future<void>.value(),
+ returnValueForMissingStub: _i5.Future<void>.value(),
+ ) as _i5.Future<void>);
@override
_i5.Future<void> deleteEpicBox(String? id, bool? shouldNotifyListeners) =>
(super.noSuchMethod(
- Invocation.method(#deleteEpicBox, [id, shouldNotifyListeners]),
- returnValue: _i5.Future<void>.value(),
- returnValueForMissingStub: _i5.Future<void>.value(),
- )
- as _i5.Future<void>);
+ Invocation.method(#deleteEpicBox, [id, shouldNotifyListeners]),
+ returnValue: _i5.Future<void>.value(),
+ returnValueForMissingStub: _i5.Future<void>.value(),
+ ) as _i5.Future<void>);
@override
- _i5.Future<void> updateCommunityNodes() =>
- (super.noSuchMethod(
- Invocation.method(#updateCommunityNodes, []),
- returnValue: _i5.Future<void>.value(),
- returnValueForMissingStub: _i5.Future<void>.value(),
- )
- as _i5.Future<void>);
+ _i5.Future<void> updateCommunityNodes() => (super.noSuchMethod(
+ Invocation.method(#updateCommunityNodes, []),
+ returnValue: _i5.Future<void>.value(),
+ returnValueForMissingStub: _i5.Future<void>.value(),
+ ) as _i5.Future<void>);
@override
void addListener(_i8.VoidCallback? listener) => super.noSuchMethod(
### test/widget_tests/node_options_sheet_test.dart
@@ -62,9 +62,8 @@ void main() {
when(wallets.wallets).thenReturn([]);
when(prefs.syncType).thenReturn(SyncingType.currentWalletOnly);
when(nodeService.getNodeById(id: node.id)).thenAnswer((_) => node);
- when(
- nodeService.getPrimaryNodeFor(currency: bitcoin),
- ).thenAnswer((_) => primaryNode);
+ when(nodeService.getPrimaryNodeFor(currency: bitcoin))
+ .thenAnswer((_) => primaryNode);
}
Future<void> pumpSubject(
@@ -209,12 +208,11 @@ void main() {
primaryNode: otherPrimary,
);
when(
- mockNodeService.setPrimaryNodeFor(
- coin: bitcoin,
+ mockNodeService.commitConnectionTest(
node: node,
- shouldNotifyListeners: true,
+ formData: anyNamed('formData'),
),
- ).thenAnswer((_) async {});
+ ).thenAnswer((_) async => true);
await pumpSubject(
tester,
@@ -238,10 +236,9 @@ void main() {
expect(platformOverrides.connectionInvocations.single.host, '127.0.0.1');
verify(
- mockNodeService.setPrimaryNodeFor(
- coin: bitcoin,
+ mockNodeService.commitConnectionTest(
node: node,
- shouldNotifyListeners: true,
+ formData: anyNamed('formData'),
),
).called(1);
});
@@ -285,10 +282,9 @@ void main() {
expect(platformOverrides.connectionInvocations.single.password, isNull);
verifyNever(
- mockNodeService.setPrimaryNodeFor(
- coin: bitcoin,
+ mockNodeService.commitConnectionTest(
node: anyNamed('node'),
- shouldNotifyListeners: anyNamed('shouldNotifyListeners'),
+ formData: anyNamed('formData'),
),
);
},
### test/widget_tests/node_options_sheet_test.mocks.dart
@@ -12,6 +12,7 @@ import 'package:mockito/mockito.dart' as _i1;
import 'package:mockito/src/dummies.dart' as _i14;
import 'package:stackwallet/db/isar/main_db.dart' as _i3;
import 'package:stackwallet/models/epicbox_server_model.dart' as _i20;
+import 'package:stackwallet/models/node_form_data.dart' as _iTls;
import 'package:stackwallet/models/node_model.dart' as _i19;
import 'package:stackwallet/services/event_bus/events/global/tor_connection_status_changed_event.dart'
as _i22;
@@ -88,31 +89,22 @@ class MockWallets extends _i1.Mock implements _i9.Wallets {
}
@override
- _i2.NodeService get nodeService =>
- (super.noSuchMethod(
- Invocation.getter(#nodeService),
- returnValue: _FakeNodeService_0(
- this,
- Invocation.getter(#nodeService),
- ),
- )
- as _i2.NodeService);
+ _i2.NodeService get nodeService => (super.noSuchMethod(
+ Invocation.getter(#nodeService),
+ returnValue: _FakeNodeService_0(this, Invocation.getter(#nodeService)),
+ ) as _i2.NodeService);
@override
- _i3.MainDB get mainDB =>
- (super.noSuchMethod(
- Invocation.getter(#mainDB),
- returnValue: _FakeMainDB_1(this, Invocation.getter(#mainDB)),
- )
- as _i3.MainDB);
+ _i3.MainDB get mainDB => (super.noSuchMethod(
+ Invocation.getter(#mainDB),
+ returnValue: _FakeMainDB_1(this, Invocation.getter(#mainDB)),
+ ) as _i3.MainDB);
@override
- List<_i5.Wallet<_i4.CryptoCurrency>> get wallets =>
- (super.noSuchMethod(
- Invocation.getter(#wallets),
- returnValue: <_i5.Wallet<_i4.CryptoCurrency>>[],
- )
- as List<_i5.Wallet<_i4.CryptoCurrency>>);
+ List<_i5.Wallet<_i4.CryptoCurrency>> get wallets => (super.noSuchMethod(
+ Invocation.getter(#wallets),
+ returnValue: <_i5.Wallet<_i4.CryptoCurrency>>[],
+ ) as List<_i5.Wallet<_i4.CryptoCurrency>>);
@override
set nodeService(_i2.NodeService? value) => super.noSuchMethod(
@@ -129,13 +121,12 @@ class MockWallets extends _i1.Mock implements _i9.Wallets {
@override
_i5.Wallet<_i4.CryptoCurrency> getWallet(String? walletId) =>
(super.noSuchMethod(
- Invocation.method(#getWallet, [walletId]),
- returnValue: _FakeWallet_2<_i4.CryptoCurrency>(
- this,
- Invocation.method(#getWallet, [walletId]),
- ),
- )
- as _i5.Wallet<_i4.CryptoCurrency>);
+ Invocation.method(#getWallet, [walletId]),
+ returnValue: _FakeWallet_2<_i4.CryptoCurrency>(
+ this,
+ Invocation.method(#getWallet, [walletId]),
+ ),
+ ) as _i5.Wallet<_i4.CryptoCurrency>);
@override
void addWallet(_i5.Wallet<_i4.CryptoCurrency>? wallet) => super.noSuchMethod(
@@ -147,43 +138,33 @@ class MockWallets extends _i1.Mock implements _i9.Wallets {
_i10.Future<void> deleteWallet(
_i11.WalletInfo? info,
_i7.SecureStorageInterface? secureStorage,
- ) =>
- (super.noSuchMethod(
- Invocation.method(#deleteWallet, [info, secureStorage]),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
+ ) => (super.noSuchMethod(
+ Invocation.method(#deleteWallet, [info, secureStorage]),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
@override
_i10.Future<void> load(
_i12.Prefs? prefs,
_i3.MainDB? mainDB,
bool? isDuress,
- ) =>
- (super.noSuchMethod(
- Invocation.method(#load, [prefs, mainDB, isDuress]),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
+ ) => (super.noSuchMethod(
+ Invocation.method(#load, [prefs, mainDB, isDuress]),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
@override
_i10.Future<void> loadAfterStackRestore(
_i12.Prefs? prefs,
List<_i5.Wallet<_i4.CryptoCurrency>>? wallets,
bool? isDesktop,
- ) =>
- (super.noSuchMethod(
- Invocation.method(#loadAfterStackRestore, [
- prefs,
- wallets,
- isDesktop,
- ]),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
+ ) => (super.noSuchMethod(
+ Invocation.method(#loadAfterStackRestore, [prefs, wallets, isDesktop]),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
}
/// A class which mocks [Prefs].
@@ -200,76 +181,56 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs {
as bool);
@override
- int get lastUnlockedTimeout =>
- (super.noSuchMethod(
- Invocation.getter(#lastUnlockedTimeout),
- returnValue: 0,
- )
- as int);
+ int get lastUnlockedTimeout => (super.noSuchMethod(
+ Invocation.getter(#lastUnlockedTimeout),
+ returnValue: 0,
+ ) as int);
@override
int get lastUnlocked =>
(super.noSuchMethod(Invocation.getter(#lastUnlocked), returnValue: 0)
as int);
@override
- int get currentNotificationId =>
- (super.noSuchMethod(
- Invocation.getter(#currentNotificationId),
- returnValue: 0,
- )
- as int);
+ int get currentNotificationId => (super.noSuchMethod(
+ Invocation.getter(#currentNotificationId),
+ returnValue: 0,
+ ) as int);
@override
- List<String> get walletIdsSyncOnStartup =>
- (super.noSuchMethod(
- Invocation.getter(#walletIdsSyncOnStartup),
- returnValue: <String>[],
- )
- as List<String>);
+ List<String> get walletIdsSyncOnStartup => (super.noSuchMethod(
+ Invocation.getter(#walletIdsSyncOnStartup),
+ returnValue: <String>[],
+ ) as List<String>);
@override
- _i13.SyncingType get syncType =>
- (super.noSuchMethod(
- Invocation.getter(#syncType),
- returnValue: _i13.SyncingType.currentWalletOnly,
- )
- as _i13.SyncingType);
+ _i13.SyncingType get syncType => (super.noSuchMethod(
+ Invocation.getter(#syncType),
+ returnValue: _i13.SyncingType.currentWalletOnly,
+ ) as _i13.SyncingType);
@override
bool get wifiOnly =>
(super.noSuchMethod(Invocation.getter(#wifiOnly), returnValue: false)
as bool);
@override
- bool get showFavoriteWallets =>
- (super.noSuchMethod(
- Invocation.getter(#showFavoriteWallets),
- returnValue: false,
- )
- as bool);
+ bool get showFavoriteWallets => (super.noSuchMethod(
+ Invocation.getter(#showFavoriteWallets),
+ returnValue: false,
+ ) as bool);
@override
- String get language =>
- (super.noSuchMethod(
- Invocation.getter(#language),
- returnValue: _i14.dummyValue<String>(
- this,
- Invocation.getter(#language),
- ),
- )
- as String);
+ String get language => (super.noSuchMethod(
+ Invocation.getter(#language),
+ returnValue: _i14.dummyValue<String>(this, Invocation.getter(#language)),
+ ) as String);
@override
- String get currency =>
- (super.noSuchMethod(
- Invocation.getter(#currency),
- returnValue: _i14.dummyValue<String>(
- this,
- Invocation.getter(#currency),
- ),
- )
- as String);
+ String get currency => (super.noSuchMethod(
+ Invocation.getter(#currency),
+ returnValue: _i14.dummyValue<String>(this, Invocation.getter(#currency)),
+ ) as String);
@override
bool get randomizePIN =>
@@ -292,12 +253,10 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs {
as bool);
@override
- bool get biometricsDuress =>
- (super.noSuchMethod(
- Invocation.getter(#biometricsDuress),
- returnValue: false,
- )
- as bool);
+ bool get biometricsDuress => (super.noSuchMethod(
+ Invocation.getter(#biometricsDuress),
+ returnValue: false,
+ ) as bool);
@override
int get familiarity =>
@@ -310,98 +269,75 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs {
as bool);
@override
- bool get showTestNetCoins =>
- (super.noSuchMethod(
- Invocation.getter(#showTestNetCoins),
- returnValue: false,
- )
- as bool);
+ bool get showTestNetCoins => (super.noSuchMethod(
+ Invocation.getter(#showTestNetCoins),
+ returnValue: false,
+ ) as bool);
@override
- bool get isAutoBackupEnabled =>
- (super.noSuchMethod(
- Invocation.getter(#isAutoBackupEnabled),
- returnValue: false,
- )
- as bool);
+ bool get isAutoBackupEnabled => (super.noSuchMethod(
+ Invocation.getter(#isAutoBackupEnabled),
+ returnValue: false,
+ ) as bool);
@override
- _i15.BackupFrequencyType get backupFrequencyType =>
- (super.noSuchMethod(
- Invocation.getter(#backupFrequencyType),
- returnValue: _i15.BackupFrequencyType.everyTenMinutes,
- )
- as _i15.BackupFrequencyType);
+ _i15.BackupFrequencyType get backupFrequencyType => (super.noSuchMethod(
+ Invocation.getter(#backupFrequencyType),
+ returnValue: _i15.BackupFrequencyType.everyTenMinutes,
+ ) as _i15.BackupFrequencyType);
@override
- bool get hideBlockExplorerWarning =>
- (super.noSuchMethod(
- Invocation.getter(#hideBlockExplorerWarning),
- returnValue: false,
- )
- as bool);
+ bool get hideBlockExplorerWarning => (super.noSuchMethod(
+ Invocation.getter(#hideBlockExplorerWarning),
+ returnValue: false,
+ ) as bool);
@override
- bool get gotoWalletOnStartup =>
- (super.noSuchMethod(
- Invocation.getter(#gotoWalletOnStartup),
- returnValue: false,
- )
- as bool);
+ bool get gotoWalletOnStartup => (super.noSuchMethod(
+ Invocation.getter(#gotoWalletOnStartup),
+ returnValue: false,
+ ) as bool);
@override
bool get externalCalls =>
(super.noSuchMethod(Invocation.getter(#externalCalls), returnValue: false)
as bool);
@override
- bool get enableCoinControl =>
- (super.noSuchMethod(
- Invocation.getter(#enableCoinControl),
- returnValue: false,
- )
- as bool);
+ bool get enableCoinControl => (super.noSuchMethod(
+ Invocation.getter(#enableCoinControl),
+ returnValue: false,
+ ) as bool);
@override
- bool get enableSystemBrightness =>
- (super.noSuchMethod(
- Invocation.getter(#enableSystemBrightness),
- returnValue: false,
- )
- as bool);
+ bool get enableSystemBrightness => (super.noSuchMethod(
+ Invocation.getter(#enableSystemBrightness),
+ returnValue: false,
+ ) as bool);
@override
- String get themeId =>
- (super.noSuchMethod(
- Invocation.getter(#themeId),
- returnValue: _i14.dummyValue<String>(
- this,
- Invocation.getter(#themeId),
- ),
- )
- as String);
+ String get themeId => (super.noSuchMethod(
+ Invocation.getter(#themeId),
+ returnValue: _i14.dummyValue<String>(this, Invocation.getter(#themeId)),
+ ) as String);
@override
- String get systemBrightnessLightThemeId =>
- (super.noSuchMethod(
- Invocation.getter(#systemBrightnessLightThemeId),
- returnValue: _i14.dummyValue<String>(
- this,
- Invocation.getter(#systemBrightnessLightThemeId),
- ),
- )
- as String);
+ String get systemBrightnessLightThemeId => (super.noSuchMethod(
+ Invocation.getter(#systemBrightnessLightThemeId),
+ returnValue: _i14.dummyValue<String>(
+ this,
+ Invocation.getter(#systemBrightnessLightThemeId),
+ ),
+ ) as String);
@override
- String get systemBrightnessDarkThemeId =>
- (super.noSuchMethod(
- Invocation.getter(#systemBrightnessDarkThemeId),
- returnValue: _i14.dummyValue<String>(
- this,
- Invocation.getter(#systemBrightnessDarkThemeId),
- ),
- )
- as String);
+ String get systemBrightnessDarkThemeId => (super.noSuchMethod(
+ Invocation.getter(#systemBrightnessDarkThemeId),
+ returnValue: _i14.dummyValue<String>(
+ this,
+ Invocation.getter(#systemBrightnessDarkThemeId),
+ ),
+ ) as String);
@override
bool get useTor =>
@@ -414,49 +350,39 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs {
as bool);
@override
- bool get enableExchange =>
- (super.noSuchMethod(
- Invocation.getter(#enableExchange),
- returnValue: false,
- )
- as bool);
+ bool get enableExchange => (super.noSuchMethod(
+ Invocation.getter(#enableExchange),
+ returnValue: false,
+ ) as bool);
@override
- bool get advancedFiroFeatures =>
- (super.noSuchMethod(
- Invocation.getter(#advancedFiroFeatures),
- returnValue: false,
- )
- as bool);
+ bool get advancedFiroFeatures => (super.noSuchMethod(
+ Invocation.getter(#advancedFiroFeatures),
+ returnValue: false,
+ ) as bool);
@override
- _i16.Level get logLevel =>
- (super.noSuchMethod(
- Invocation.getter(#logLevel),
- returnValue: _i16.Level.all,
- )
- as _i16.Level);
+ _i16.Level get logLevel => (super.noSuchMethod(
+ Invocation.getter(#logLevel),
+ returnValue: _i16.Level.all,
+ ) as _i16.Level);
@override
- ({bool enabled, int minutes}) get autoLockInfo =>
- (super.noSuchMethod(
- Invocation.getter(#autoLockInfo),
- returnValue: (enabled: false, minutes: 0),
- )
- as ({bool enabled, int minutes}));
+ ({bool enabled, int minutes}) get autoLockInfo => (super.noSuchMethod(
+ Invocation.getter(#autoLockInfo),
+ returnValue: (enabled: false, minutes: 0),
+ ) as ({bool enabled, int minutes}));
@override
bool get privacyScreen =>
(super.noSuchMethod(Invocation.getter(#privacyScreen), returnValue: false)
as bool);
@override
- bool get disableScreenShots =>
- (super.noSuchMethod(
- Invocation.getter(#disableScreenShots),
- returnValue: false,
- )
- as bool);
+ bool get disableScreenShots => (super.noSuchMethod(
+ Invocation.getter(#disableScreenShots),
+ returnValue: false,
+ ) as bool);
@override
set lastUnlockedTimeout(int? lastUnlockedTimeout) => super.noSuchMethod(
@@ -705,55 +631,43 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs {
as bool);
@override
- _i10.Future<void> init() =>
- (super.noSuchMethod(
- Invocation.method(#init, []),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
+ _i10.Future<void> init() => (super.noSuchMethod(
+ Invocation.method(#init, []),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
@override
- _i10.Future<int> incrementCurrentNotificationIndex() =>
- (super.noSuchMethod(
- Invocation.method(#incrementCurrentNotificationIndex, []),
- returnValue: _i10.Future<int>.value(0),
- )
- as _i10.Future<int>);
+ _i10.Future<int> incrementCurrentNotificationIndex() => (super.noSuchMethod(
+ Invocation.method(#incrementCurrentNotificationIndex, []),
+ returnValue: _i10.Future<int>.value(0),
+ ) as _i10.Future<int>);
@override
- _i10.Future<bool> isExternalCallsSet() =>
- (super.noSuchMethod(
- Invocation.method(#isExternalCallsSet, []),
- returnValue: _i10.Future<bool>.value(false),
- )
- as _i10.Future<bool>);
+ _i10.Future<bool> isExternalCallsSet() => (super.noSuchMethod(
+ Invocation.method(#isExternalCallsSet, []),
+ returnValue: _i10.Future<bool>.value(false),
+ ) as _i10.Future<bool>);
@override
- _i10.Future<void> saveUserID(String? userId) =>
- (super.noSuchMethod(
- Invocation.method(#saveUserID, [userId]),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
+ _i10.Future<void> saveUserID(String? userId) => (super.noSuchMethod(
+ Invocation.method(#saveUserID, [userId]),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
@override
- _i10.Future<void> saveSignupEpoch(int? signupEpoch) =>
- (super.noSuchMethod(
- Invocation.method(#saveSignupEpoch, [signupEpoch]),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
+ _i10.Future<void> saveSignupEpoch(int? signupEpoch) => (super.noSuchMethod(
+ Invocation.method(#saveSignupEpoch, [signupEpoch]),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
@override
- _i17.AmountUnit amountUnit(_i4.CryptoCurrency? coin) =>
- (super.noSuchMethod(
- Invocation.method(#amountUnit, [coin]),
- returnValue: _i17.AmountUnit.normal,
- )
- as _i17.AmountUnit);
+ _i17.AmountUnit amountUnit(_i4.CryptoCurrency? coin) => (super.noSuchMethod(
+ Invocation.method(#amountUnit, [coin]),
+ returnValue: _i17.AmountUnit.normal,
+ ) as _i17.AmountUnit);
@override
void updateAmountUnit({
@@ -768,12 +682,10 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs {
);
@override
- int maxDecimals(_i4.CryptoCurrency? coin) =>
- (super.noSuchMethod(
- Invocation.method(#maxDecimals, [coin]),
- returnValue: 0,
- )
- as int);
+ int maxDecimals(_i4.CryptoCurrency? coin) => (super.noSuchMethod(
+ Invocation.method(#maxDecimals, [coin]),
+ returnValue: 0,
+ ) as int);
@override
void updateMaxDecimals({
@@ -790,13 +702,12 @@ class MockPrefs extends _i1.Mock implements _i12.Prefs {
@override
_i6.FusionInfo getFusionServerInfo(_i4.CryptoCurrency? coin) =>
(super.noSuchMethod(
- Invocation.method(#getFusionServerInfo, [coin]),
- returnValue: _FakeFusionInfo_3(
- this,
- Invocation.method(#getFusionServerInfo, [coin]),
- ),
- )
- as _i6.FusionInfo);
+ Invocation.method(#getFusionServerInfo, [coin]),
+ returnValue: _FakeFusionInfo_3(
+ this,
+ Invocation.method(#getFusionServerInfo, [coin]),
+ ),
+ ) as _i6.FusionInfo);
@override
void setFusionServerInfo(
@@ -841,77 +752,65 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService {
}
@override
- _i7.SecureStorageInterface get secureStorageInterface =>
- (super.noSuchMethod(
- Invocation.getter(#secureStorageInterface),
- returnValue: _FakeSecureStorageInterface_4(
- this,
- Invocation.getter(#secureStorageInterface),
- ),
- )
- as _i7.SecureStorageInterface);
+ _i7.SecureStorageInterface get secureStorageInterface => (super.noSuchMethod(
+ Invocation.getter(#secureStorageInterface),
+ returnValue: _FakeSecureStorageInterface_4(
+ this,
+ Invocation.getter(#secureStorageInterface),
+ ),
+ ) as _i7.SecureStorageInterface);
@override
- List<_i19.NodeModel> get primaryNodes =>
- (super.noSuchMethod(
- Invocation.getter(#primaryNodes),
- returnValue: <_i19.NodeModel>[],
- )
- as List<_i19.NodeModel>);
+ List<_i19.NodeModel> get primaryNodes => (super.noSuchMethod(
+ Invocation.getter(#primaryNodes),
+ returnValue: <_i19.NodeModel>[],
+ ) as List<_i19.NodeModel>);
@override
- List<_i19.NodeModel> get nodes =>
- (super.noSuchMethod(
- Invocation.getter(#nodes),
- returnValue: <_i19.NodeModel>[],
- )
- as List<_i19.NodeModel>);
+ List<_i19.NodeModel> get nodes => (super.noSuchMethod(
+ Invocation.getter(#nodes),
+ returnValue: <_i19.NodeModel>[],
+ ) as List<_i19.NodeModel>);
@override
bool get hasListeners =>
(super.noSuchMethod(Invocation.getter(#hasListeners), returnValue: false)
as bool);
@override
- _i10.Future<void> updateDefaults() =>
- (super.noSuchMethod(
- Invocation.method(#updateDefaults, []),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
+ _i10.Future<void> updateDefaults() => (super.noSuchMethod(
+ Invocation.method(#updateDefaults, []),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
@override
_i10.Future<void> setPrimaryNodeFor({
required _i4.CryptoCurrency? coin,
required _i19.NodeModel? node,
bool? shouldNotifyListeners = false,
- }) =>
- (super.noSuchMethod(
- Invocation.method(#setPrimaryNodeFor, [], {
- #coin: coin,
- #node: node,
- #shouldNotifyListeners: shouldNotifyListeners,
- }),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
+ }) => (super.noSuchMethod(
+ Invocation.method(#setPrimaryNodeFor, [], {
+ #coin: coin,
+ #node: node,
+ #shouldNotifyListeners: shouldNotifyListeners,
+ }),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
@override
_i19.NodeModel? getPrimaryNodeFor({required _i4.CryptoCurrency? currency}) =>
(super.noSuchMethod(
- Invocation.method(#getPrimaryNodeFor, [], {#currency: currency}),
- )
- as _i19.NodeModel?);
+ Invocation.method(#getPrimaryNodeFor, [], {#currency: currency}),
+ ) as _i19.NodeModel?);
@override
List<_i19.NodeModel> getNodesFor(_i4.CryptoCurrency? coin) =>
(super.noSuchMethod(
- Invocation.method(#getNodesFor, [coin]),
- returnValue: <_i19.NodeModel>[],
- )
- as List<_i19.NodeModel>);
+ Invocation.method(#getNodesFor, [coin]),
+ returnValue: <_i19.NodeModel>[],
+ ) as List<_i19.NodeModel>);
@override
_i19.NodeModel? getNodeById({required String? id}) =>
@@ -921,83 +820,78 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService {
@override
List<_i19.NodeModel> failoverNodesFor({
required _i4.CryptoCurrency? currency,
- }) =>
- (super.noSuchMethod(
- Invocation.method(#failoverNodesFor, [], {#currency: currency}),
- returnValue: <_i19.NodeModel>[],
- )
- as List<_i19.NodeModel>);
+ }) => (super.noSuchMethod(
+ Invocation.method(#failoverNodesFor, [], {#currency: currency}),
+ returnValue: <_i19.NodeModel>[],
+ ) as List<_i19.NodeModel>);
@override
_i10.Future<void> save(
_i19.NodeModel? node,
String? password,
bool? shouldNotifyListeners,
- ) =>
- (super.noSuchMethod(
- Invocation.method(#save, [node, password, shouldNotifyListeners]),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
+ ) => (super.noSuchMethod(
+ Invocation.method(#save, [node, password, shouldNotifyListeners]),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
+
+ @override
+ _i10.Future<bool> commitConnectionTest({
+ required _i19.NodeModel? node,
+ required _iTls.NodeFormData? formData,
+ }) => (super.noSuchMethod(
+ Invocation.method(#commitConnectionTest, [], {
+ #node: node,
+ #formData: formData,
+ }),
+ returnValue: _i10.Future<bool>.value(false),
+ ) as _i10.Future<bool>);
@override
_i10.Future<void> delete(String? id, bool? shouldNotifyListeners) =>
(super.noSuchMethod(
- Invocation.method(#delete, [id, shouldNotifyListeners]),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
+ Invocation.method(#delete, [id, shouldNotifyListeners]),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
@override
_i10.Future<void> setEnabledState(
String? id,
bool? enabled,
bool? shouldNotifyListeners,
- ) =>
- (super.noSuchMethod(
- Invocation.method(#setEnabledState, [
- id,
- enabled,
- shouldNotifyListeners,
- ]),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
-
- @override
- _i10.Future<void> updateDefaultEpicBoxes() =>
- (super.noSuchMethod(
- Invocation.method(#updateDefaultEpicBoxes, []),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
+ ) => (super.noSuchMethod(
+ Invocation.method(#setEnabledState, [id, enabled, shouldNotifyListeners]),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
+
+ @override
+ _i10.Future<void> updateDefaultEpicBoxes() => (super.noSuchMethod(
+ Invocation.method(#updateDefaultEpicBoxes, []),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
@override
_i10.Future<void> setPrimaryEpicBox({
required _i20.EpicBoxServerModel? epicBox,
bool? shouldNotifyListeners = false,
- }) =>
- (super.noSuchMethod(
- Invocation.method(#setPrimaryEpicBox, [], {
- #epicBox: epicBox,
- #shouldNotifyListeners: shouldNotifyListeners,
- }),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
+ }) => (super.noSuchMethod(
+ Invocation.method(#setPrimaryEpicBox, [], {
+ #epicBox: epicBox,
+ #shouldNotifyListeners: shouldNotifyListeners,
+ }),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
@override
- List<_i20.EpicBoxServerModel> getEpicBoxes() =>
- (super.noSuchMethod(
- Invocation.method(#getEpicBoxes, []),
- returnValue: <_i20.EpicBoxServerModel>[],
- )
- as List<_i20.EpicBoxServerModel>);
+ List<_i20.EpicBoxServerModel> getEpicBoxes() => (super.noSuchMethod(
+ Invocation.method(#getEpicBoxes, []),
+ returnValue: <_i20.EpicBoxServerModel>[],
+ ) as List<_i20.EpicBoxServerModel>);
@override
_i20.EpicBoxServerModel? getEpicBoxById({required String? id}) =>
@@ -1008,31 +902,26 @@ class MockNodeService extends _i1.Mock implements _i2.NodeService {
_i10.Future<void> addEpicBox(
_i20.EpicBoxServerModel? epicBox,
bool? shouldNotifyListeners,
- ) =>
- (super.noSuchMethod(
- Invocation.method(#addEpicBox, [epicBox, shouldNotifyListeners]),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
+ ) => (super.noSuchMethod(
+ Invocation.method(#addEpicBox, [epicBox, shouldNotifyListeners]),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
@override
_i10.Future<void> deleteEpicBox(String? id, bool? shouldNotifyListeners) =>
(super.noSuchMethod(
- Invocation.method(#deleteEpicBox, [id, shouldNotifyListeners]),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
+ Invocation.method(#deleteEpicBox, [id, shouldNotifyListeners]),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
@override
- _i10.Future<void> updateCommunityNodes() =>
- (super.noSuchMethod(
- Invocation.method(#updateCommunityNodes, []),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
+ _i10.Future<void> updateCommunityNodes() => (super.noSuchMethod(
+ Invocation.method(#updateCommunityNodes, []),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
@override
void addListener(_i18.VoidCallback? listener) => super.noSuchMethod(
@@ -1068,26 +957,19 @@ class MockTorService extends _i1.Mock implements _i21.TorService {
}
@override
- _i22.TorConnectionStatus get status =>
- (super.noSuchMethod(
- Invocation.getter(#status),
- returnValue: _i22.TorConnectionStatus.disconnected,
- )
- as _i22.TorConnectionStatus);
+ _i22.TorConnectionStatus get status => (super.noSuchMethod(
+ Invocation.getter(#status),
+ returnValue: _i22.TorConnectionStatus.disconnected,
+ ) as _i22.TorConnectionStatus);
@override
- ({_i8.InternetAddress host, int port}) getProxyInfo() =>
- (super.noSuchMethod(
- Invocation.method(#getProxyInfo, []),
- returnValue: (
- host: _FakeInternetAddress_5(
- this,
- Invocation.method(#getProxyInfo, []),
- ),
- port: 0,
- ),
- )
- as ({_i8.InternetAddress host, int port}));
+ ({_i8.InternetAddress host, int port}) getProxyInfo() => (super.noSuchMethod(
+ Invocation.method(#getProxyInfo, []),
+ returnValue: (
+ host: _FakeInternetAddress_5(this, Invocation.method(#getProxyInfo, [])),
+ port: 0,
+ ),
+ ) as ({_i8.InternetAddress host, int port}));
@override
void init({required String? torDataDirPath}) => super.noSuchMethod(
@@ -1096,20 +978,16 @@ class MockTorService extends _i1.Mock implements _i21.TorService {
);
@override
- _i10.Future<void> start() =>
- (super.noSuchMethod(
- Invocation.method(#start, []),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
+ _i10.Future<void> start() => (super.noSuchMethod(
+ Invocation.method(#start, []),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
@override
- _i10.Future<void> disable() =>
- (super.noSuchMethod(
- Invocation.method(#disable, []),
- returnValue: _i10.Future<void>.value(),
- returnValueForMissingStub: _i10.Future<void>.value(),
- )
- as _i10.Future<void>);
+ _i10.Future<void> disable() => (super.noSuchMethod(
+ Invocation.method(#disable, []),
+ returnValue: _i10.Future<void>.value(),
+ returnValueForMissingStub: _i10.Future<void>.value(),
+ ) as _i10.Future<void>);
}
### test/widget_tests/node_tls_trust_test.dart
@@ -0,0 +1,645 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:typed_data';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_riverpod/flutter_riverpod.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:logger/logger.dart' show Level;
+import 'package:mockito/mockito.dart';
+import 'package:mutex/mutex.dart';
+import 'package:platform/platform.dart';
+import 'package:stackwallet/db/hive/db.dart';
+import 'package:stackwallet/models/isar/stack_theme.dart';
+import 'package:stackwallet/models/node_model.dart';
+import 'package:stackwallet/pages/settings_views/global_settings_view/manage_nodes_views/add_edit_node_view.dart';
+import 'package:stackwallet/pages/settings_views/global_settings_view/manage_nodes_views/node_details_view.dart';
+import 'package:stackwallet/providers/providers.dart';
+import 'package:stackwallet/providers/global/secure_store_provider.dart';
+import 'package:stackwallet/services/node_service.dart';
+import 'package:stackwallet/services/wallets.dart';
+import 'package:stackwallet/themes/stack_colors.dart';
+import 'package:stackwallet/themes/theme_providers.dart';
+import 'package:stackwallet/utilities/connection_check/electrum_connection_check.dart';
+import 'package:stackwallet/utilities/enums/sync_type_enum.dart';
+import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart';
+import 'package:stackwallet/utilities/logger.dart';
+import 'package:stackwallet/utilities/prefs.dart';
+import 'package:stackwallet/utilities/test_node_connection.dart';
+import 'package:stackwallet/utilities/util.dart';
+import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart';
+import 'package:stackwallet/wallets/isar/models/wallet_info.dart';
+import 'package:stackwallet/wallets/wallet/wallet.dart';
+import 'package:stackwallet/widgets/desktop/primary_button.dart';
+import 'package:stackwallet/widgets/node_card.dart';
+import 'package:stackwallet/widgets/node_options_sheet.dart';
+
+import '../sample_data/theme_json.dart';
+import '../utilities/tls_test_server.dart';
+
+class _Wallets extends Fake implements Wallets {
+ _Wallets([this.wallets = const []]);
+ @override
+ final List<Wallet> wallets;
+}
+
+/// A loaded wallet that records the node-change calls it receives.
+class _LoadedWallet extends Fake implements Wallet {
+ _LoadedWallet(CryptoCurrency coin, this.walletId)
+ : info = WalletInfo.createNew(
+ coin: coin,
+ name: walletId,
+ walletIdOverride: walletId,
+ );
+ @override
+ final String walletId;
+ @override
+ final WalletInfo info;
+ int updates = 0;
+ int refreshes = 0;
+ @override
+ final refreshMutex = Mutex();
+ @override
+ Future<void> updateNode() async => updates++;
+ @override
+ Future<void> refresh() async => refreshes++;
+}
+
+/// Opens [child] on a route of its own, for views that pop themselves.
+class _Opener extends StatelessWidget {
+ const _Opener(this.child);
+ final Widget child;
+ @override
+ Widget build(BuildContext context) => TextButton(
+ onPressed: () =>
+ Navigator.of(context)
+ .push(MaterialPageRoute<void>(builder: (_) => child)),
+ child: const Text('Open'),
+ );
+}
+
+class _Prefs extends Mock implements Prefs {
+ @override
+ bool get useTor => false;
+ @override
+ SyncingType get syncType => SyncingType.allWalletsOnStartup;
+}
+
+void main() {
+ late CryptoCurrency coin;
+ late NodeService nodes;
+ late FakeSecureStorage storage;
+ late String pem;
+ late Directory logs;
+ String? testedHost, testedCertificate;
+ Completer<void>? testGate;
+ int tests = 0;
+ NodeModel node() => nodes.getNodeById(id: 'custom-node')!;
+ NodeModel makeNode(String id, {bool primary = false}) => NodeModel(
+ host: id == 'custom-node' ? 'node.example' : 'other.example',
+ port: 50002,
+ name: id == 'custom-node' ? 'Node' : 'Other',
+ id: id,
+ useSSL: true,
+ enabled: true,
+ coinName: coin.identifier,
+ isFailover: false,
+ isDown: false,
+ torEnabled: true,
+ clearnetEnabled: true,
+ isPrimary: primary,
+ );
+
+ setUpAll(() async {
+ logs = await Directory.systemTemp.createTemp('minimal_tls_widgets');
+ await Logging.instance.initialize(logs.path, level: Level.off);
+ });
+ tearDownAll(() => logs.delete(recursive: true));
+ setUp(() async {
+ coin = Bitcoin(CryptoCurrencyNetwork.main);
+ DB.instance.hive.init(logs.path);
+ if (!DB.instance.hive.isAdapterRegistered(12)) {
+ DB.instance.hive.registerAdapter(NodeModelAdapter());
+ }
+ final box = await DB.instance.hive.openBox<NodeModel>(
+ DB.boxNameNodeModels,
+ bytes: Uint8List(0),
+ );
+ await box.put('custom-node', makeNode('custom-node'));
+ await box.put('other-node', makeNode('other-node', primary: true));
+ storage = FakeSecureStorage();
+ nodes = NodeService(secureStorageInterface: storage);
+ pem = TlsElectrumServer.certificate('node_a');
+ testedHost = testedCertificate = null;
+ testGate = null;
+ tests = 0;
+ Util.layoutPlatform = FakePlatform(operatingSystem: 'macos');
+ });
+ tearDown(() async {
+ await DB.instance.hive.close();
+ Util.layoutPlatform = const LocalPlatform();
+ });
+
+ Future<void> pump(
+ WidgetTester tester,
+ Widget child, {
+ TestNodeConnectionCallback? testConnection,
+ List<Wallet> wallets = const [],
+ }) async {
+ tester.view.physicalSize = const Size(1200, 1800);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.resetPhysicalSize);
+ addTearDown(tester.view.resetDevicePixelRatio);
+ await tester.pumpWidget(
+ ProviderScope(
+ overrides: [
+ nodeServiceChangeNotifierProvider.overrideWithValue(nodes),
+ secureStoreProvider.overrideWithValue(storage),
+ prefsChangeNotifierProvider.overrideWithValue(_Prefs()),
+ pWallets.overrideWithValue(_Wallets(wallets)),
+ // The mobile layout's background reads the theme from a provider.
+ themeProvider.overrideWithValue(
+ StateController(StackTheme.fromJson(json: lightThemeJsonMap)),
+ ),
+ testNodeConnectionProvider.overrideWithValue(
+ testConnection ??
+ ({
+ required context,
+ required nodeFormData,
+ required cryptoCurrency,
+ onSuccess,
+ }) async {
+ if (!nodes.prepareCertificateTest(nodeFormData)) return false;
+ testedHost = nodeFormData.host;
+ testedCertificate = nodeFormData.trustedCertificatePem;
+ tests++;
+ await testGate?.future;
+ nodeFormData.trustedCertificatePem = pem;
+ onSuccess?.call(nodeFormData);
+ return true;
+ },
+ ),
+ ],
+ child: MaterialApp(
+ theme: ThemeData(
+ extensions: [
+ StackColors.fromStackColorTheme(
+ StackTheme.fromJson(json: lightThemeJsonMap),
+ ),
+ ],
+ ),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: const TextScaler.linear(.8)),
+ child: child!,
+ ),
+ home: child,
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ }
+
+ Widget details() =>
+ NodeDetailsView(coin: coin, nodeId: 'custom-node', popRouteName: '/');
+ Future<void> approveStored() async {
+ final opened = node();
+ await nodes.saveTrustedCertificate(
+ opened,
+ NodeFormData.fromNode(opened)..trustedCertificatePem = pem,
+ );
+ }
+
+ testWidgets(
+ 'Details Test saves approval without rewriting the node password',
+ (tester) async {
+ await storage.write(key: 'custom-node_nodePW', value: 'secret');
+ await pump(tester, details());
+ final writes = storage.writes;
+ final deletes = storage.deletes;
+ await tester.tap(find.text('Test connection'));
+ await tester.pumpAndSettle();
+ expect(node().trustedCertificatePem, pem);
+ expect(testedHost, 'node.example');
+ expect(storage.writes, writes);
+ expect(storage.deletes, deletes);
+ expect(find.textContaining('Trusted TLS certificate'), findsOneWidget);
+ },
+ );
+
+ testWidgets('desktop Test stages an edited endpoint approval until Save', (
+ tester,
+ ) async {
+ await pump(tester, details());
+ await tester.tap(find.text('Edit'));
+ await tester.pumpAndSettle();
+ await tester.enterText(find.byType(TextField).at(1), 'edited.example');
+ await tester.tap(find.text('Test connection'));
+ await tester.pumpAndSettle();
+ expect(testedHost, 'edited.example');
+ expect(node().host, 'node.example');
+ expect(node().trustedCertificatePem, null);
+ await tester.tap(find.text('Save'));
+ await tester.pumpAndSettle();
+ expect(node().host, 'edited.example');
+ expect(node().trustedCertificatePem, pem);
+ });
+
+ testWidgets(
+ 'desktop Save uses its own form after another view refreshes the provider',
+ (tester) async {
+ await pump(tester, details());
+ await tester.tap(find.text('Edit'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Test connection'));
+ await tester.pumpAndSettle();
+ final container = ProviderScope.containerOf(
+ tester.element(find.byType(NodeDetailsView)),
+ );
+ container.refresh(nodeFormDataProvider)
+ ..host = 'different.example'
+ ..port = 60002
+ ..useSSL = true
+ ..trustedCertificatePem = TlsElectrumServer.certificate('node_b');
+ await tester.tap(find.text('Save'));
+ await tester.pumpAndSettle();
+ expect(node().host, 'node.example');
+ expect(node().trustedCertificatePem, pem);
+ },
+ );
+
+ testWidgets('repeated desktop edits keep the saved RPC password', (
+ tester,
+ ) async {
+ coin = Ethereum(CryptoCurrencyNetwork.main);
+ await nodes.save(makeNode('custom-node'), 'secret', false);
+ await pump(tester, details());
+ Finder field(String text) => find.byWidgetPredicate(
+ (widget) => widget is TextField && widget.controller?.text == text,
+ );
+ await tester.tap(find.text('Edit'));
+ await tester.pumpAndSettle();
+ await tester.enterText(field('secret'), 'changed-secret');
+ await tester.tap(find.text('Save'));
+ await tester.pumpAndSettle();
+ expect(await storage.read(key: 'custom-node_nodePW'), 'changed-secret');
+ await tester.tap(find.text('Edit'));
+ await tester.pumpAndSettle();
+ expect(field('changed-secret'), findsOneWidget);
+ await tester.enterText(field('Node'), 'Renamed');
+ await tester.tap(find.text('Save'));
+ await tester.pumpAndSettle();
+ expect(node().name, 'Renamed');
+ expect(await storage.read(key: 'custom-node_nodePW'), 'changed-secret');
+ });
+
+ testWidgets('options Connect commits approval and primary together', (
+ tester,
+ ) async {
+ await pump(
+ tester,
+ NodeOptionsSheet(nodeId: 'custom-node', coin: coin, popBackToRoute: '/'),
+ );
+ await tester.tap(find.text('Connect'));
+ await tester.pumpAndSettle();
+ expect(testedCertificate, null);
+ expect(node().trustedCertificatePem, pem);
+ expect(node().isPrimary, true);
+ expect(nodes.getNodeById(id: 'other-node')!.isPrimary, false);
+ });
+
+ testWidgets('a node change updates every loaded wallet of the coin', (
+ tester,
+ ) async {
+ // Each wallet owns its Electrum connection. Replacing the wallet's client
+ // in updateNode() is what closes the old connection, including one still
+ // finishing requests after a failover.
+ final first = _LoadedWallet(coin, 'first');
+ final second = _LoadedWallet(coin, 'second');
+ final other = _LoadedWallet(Litecoin(CryptoCurrencyNetwork.main), 'ltc');
+ // The second wallet is mid-refresh. That run fails with the replaced
+ // client, so the wallet is refreshed once more afterwards.
+ await second.refreshMutex.acquire();
+ await pump(
+ tester,
+ NodeOptionsSheet(nodeId: 'custom-node', coin: coin, popBackToRoute: '/'),
+ wallets: [first, second, other],
+ );
+ await tester.tap(find.text('Connect'));
+ await tester.pumpAndSettle();
+ second.refreshMutex.release();
+
+ expect([first.updates, second.updates, other.updates], [1, 1, 0]);
+ expect([first.refreshes, second.refreshes, other.refreshes], [1, 2, 0]);
+ });
+
+ // A deleted node's approval must stop being trusted by loaded wallets.
+ testWidgets('desktop Delete node updates the loaded wallets of the coin', (
+ tester,
+ ) async {
+ final loaded = _LoadedWallet(coin, 'loaded');
+ final other = _LoadedWallet(Litecoin(CryptoCurrencyNetwork.main), 'ltc');
+ await pump(tester, _Opener(details()), wallets: [loaded, other]);
+ await tester.tap(find.text('Open'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Edit'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Delete node'));
+ await tester.pumpAndSettle();
+
+ expect(nodes.getNodeById(id: 'custom-node'), isNull);
+ expect([loaded.updates, other.updates], [1, 0]);
+ });
+
+ testWidgets('mobile node delete updates the loaded wallets of the coin', (
+ tester,
+ ) async {
+ Util.layoutPlatform = FakePlatform(operatingSystem: 'android');
+ final loaded = _LoadedWallet(coin, 'loaded');
+ await pump(
+ tester,
+ AddEditNodeView(
+ viewType: AddEditNodeViewType.edit,
+ coin: coin,
+ nodeId: 'custom-node',
+ routeOnSuccessOrDelete: '/',
+ ),
+ wallets: [loaded],
+ );
+ await tester.tap(find.byKey(const Key('deleteNodeAppBarButtonKey')));
+ await tester.pumpAndSettle();
+
+ expect(nodes.getNodeById(id: 'custom-node'), isNull);
+ expect(loaded.updates, 1);
+ });
+
+ testWidgets('node card Connect carries an already approved certificate', (
+ tester,
+ ) async {
+ await approveStored();
+ await pump(
+ tester,
+ NodeCard(nodeId: 'custom-node', coin: coin, popBackToRoute: '/'),
+ );
+ await tester.tap(find.text('Node'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Connect', findRichText: true));
+ await tester.pumpAndSettle();
+ expect(testedCertificate, pem);
+ expect(node().trustedCertificatePem, pem);
+ expect(node().isPrimary, true);
+ });
+
+ testWidgets('add/edit Save includes the tested certificate', (tester) async {
+ await pump(
+ tester,
+ AddEditNodeView(
+ viewType: AddEditNodeViewType.edit,
+ coin: coin,
+ nodeId: 'custom-node',
+ routeOnSuccessOrDelete: '/',
+ ),
+ );
+ await tester.tap(find.text('Save'));
+ await tester.pumpAndSettle();
+ expect(node().trustedCertificatePem, pem);
+ });
+
+ testWidgets(
+ 'Forget in read-only Details is an immediate certificate-only write',
+ (tester) async {
+ await approveStored();
+ await storage.write(key: 'custom-node_nodePW', value: 'secret');
+ await pump(tester, details());
+ final writes = storage.writes;
+ final deletes = storage.deletes;
+ await tester.tap(find.text('Forget certificate'));
+ await tester.pumpAndSettle();
+ expect(node().trustedCertificatePem, null);
+ expect(node().host, 'node.example');
+ expect(storage.writes, writes);
+ expect(storage.deletes, deletes);
+ },
+ );
+
+ testWidgets('an editing Forget is staged until Save', (tester) async {
+ await approveStored();
+ await pump(tester, details());
+ await tester.tap(find.text('Edit'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Forget certificate'));
+ await tester.pumpAndSettle();
+ expect(node().trustedCertificatePem, pem);
+ await tester.tap(find.text('Save'));
+ await tester.pumpAndSettle();
+ expect(node().trustedCertificatePem, null);
+ });
+
+ testWidgets('desktop Save cannot overtake a running Test', (tester) async {
+ await pump(tester, details());
+ await tester.tap(find.text('Edit'));
+ await tester.pumpAndSettle();
+ testGate = Completer<void>();
+ final save = tester
+ .widget<PrimaryButton>(find.widgetWithText(PrimaryButton, 'Save'))
+ .onPressed!;
+ await tester.tap(find.text('Test connection'));
+ await tester.pump();
+ save();
+ await tester.pump();
+ expect(tests, 1);
+ expect(node().trustedCertificatePem, null);
+ expect(
+ tester
+ .widget<PrimaryButton>(find.widgetWithText(PrimaryButton, 'Save'))
+ .onPressed,
+ null,
+ );
+ testGate!.complete();
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Save'));
+ await tester.pumpAndSettle();
+ expect(node().trustedCertificatePem, pem);
+ });
+
+ testWidgets(
+ 'node replaced during Test keeps its endpoint and certificate together',
+ (tester) async {
+ await approveStored();
+ final started = Completer<void>();
+ final release = Completer<void>();
+ await pump(
+ tester,
+ details(),
+ testConnection:
+ ({
+ required context,
+ required nodeFormData,
+ required cryptoCurrency,
+ onSuccess,
+ }) => testElectrumNodeConnection(
+ nodeFormData,
+ isActive: () => context.mounted,
+ requestTrust: (_, _, _) async => false,
+ onSuccess: onSuccess,
+ testConnection:
+ ({
+ required host,
+ required port,
+ required useSSL,
+ trustedCertificatePem,
+ }) async {
+ started.complete();
+ await release.future;
+ return const ElectrumConnectionResult(success: false);
+ },
+ ),
+ );
+ await tester.tap(find.text('Edit'));
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Test connection'));
+ await tester.pump();
+ await tester.pump();
+ expect(started.isCompleted, true);
+
+ final before = node();
+ final replacement = before.copyWith(
+ host: 'replacement.example',
+ port: 60002,
+ loginName: before.loginName,
+ trusted: before.trusted,
+ trustedCertificatePem: TlsElectrumServer.certificate('node_b'),
+ );
+ await nodes.save(replacement, null, true);
+ await tester.pump();
+ await tester.pump();
+
+ final widget = tester.widget<NodeForm>(find.byType(NodeForm));
+ final form = widget.data!;
+ expect(widget.busy, true);
+ expect(form.source, same(replacement));
+ expect(form.host, replacement.host);
+ expect(form.port, replacement.port);
+ expect(form.useSSL, replacement.useSSL);
+ expect(form.trustedCertificatePem, replacement.trustedCertificatePem);
+ expect(
+ tester.widgetList<TextField>(find.byType(TextField)),
+ everyElement(
+ isA<TextField>().having((field) => field.readOnly, 'readOnly', true),
+ ),
+ );
+
+ release.complete();
+ await tester.pumpAndSettle();
+ await tester.tap(find.text('Save'));
+ await tester.pumpAndSettle();
+ expect(node().host, replacement.host);
+ expect(node().port, replacement.port);
+ expect(node().trustedCertificatePem, replacement.trustedCertificatePem);
+ expect(tester.takeException(), isNull);
+ },
+ );
+
+ testWidgets('a readonly test cannot undo an intervening empty Forget', (
+ tester,
+ ) async {
+ await pump(tester, details());
+ testGate = Completer<void>();
+ await tester.tap(find.text('Test connection'));
+ await tester.pump();
+ await nodes.forgetTrustedCertificate(node());
+ testGate!.complete();
+ await tester.pumpAndSettle();
+ expect(node().trustedCertificatePem, null);
+ });
+
+ testWidgets('Connect ignores a node changed during its test', (tester) async {
+ await pump(
+ tester,
+ NodeOptionsSheet(nodeId: 'custom-node', coin: coin, popBackToRoute: '/'),
+ );
+ testGate = Completer<void>();
+ await tester.tap(find.text('Connect'));
+ await tester.pump();
+ final before = node();
+ await DB.instance.put<NodeModel>(
+ boxName: DB.boxNameNodeModels,
+ key: before.id,
+ value: before.copyWith(
+ host: 'new.example',
+ loginName: null,
+ trusted: null,
+ ),
+ );
+ testGate!.complete();
+ await tester.pumpAndSettle();
+ expect(node().isPrimary, false);
+ expect(node().trustedCertificatePem, null);
+ expect(find.text(changedDuringTest), findsOneWidget);
+ });
+
+ testWidgets('node card Connect reports a node changed during its test', (
+ tester,
+ ) async {
+ await pump(
+ tester,
+ NodeCard(nodeId: 'custom-node', coin: coin, popBackToRoute: '/'),
+ );
+ await tester.tap(find.text('Node'));
+ await tester.pumpAndSettle();
+ testGate = Completer<void>();
+ await tester.tap(find.text('Connect', findRichText: true));
+ await tester.pump();
+ final before = node();
+ await DB.instance.put<NodeModel>(
+ boxName: DB.boxNameNodeModels,
+ key: before.id,
+ value: before.copyWith(loginName: null, trusted: null),
+ );
+ testGate!.complete();
+ // Check before settling: the message is only shown for 1.5 seconds.
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.text(changedDuringTest), findsOneWidget);
+ await tester.pumpAndSettle();
+ expect(node().isPrimary, false);
+ });
+
+ testWidgets('node card Connect runs one test at a time', (tester) async {
+ await pump(
+ tester,
+ NodeCard(nodeId: 'custom-node', coin: coin, popBackToRoute: '/'),
+ );
+ await tester.tap(find.text('Node'));
+ await tester.pumpAndSettle();
+ testGate = Completer<void>();
+ await tester.tap(find.text('Connect', findRichText: true));
+ await tester.pump();
+ await tester.tap(find.text('Connect', findRichText: true));
+ await tester.pump();
+ testGate!.complete();
+ await tester.pumpAndSettle();
+ expect(tests, 1);
+ expect(node().isPrimary, true);
+ });
+
+ testWidgets('options Connect runs one test at a time', (tester) async {
+ await pump(
+ tester,
+ NodeOptionsSheet(nodeId: 'custom-node', coin: coin, popBackToRoute: '/'),
+ );
+ testGate = Completer<void>();
+ await tester.tap(find.text('Connect'));
+ await tester.pump();
+ await tester.tap(find.text('Connect'));
+ await tester.pump();
+ testGate!.complete();
+ // Check before settling: a warning is only shown for 1.5 seconds.
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.text(changedDuringTest), findsNothing);
+ await tester.pumpAndSettle();
+ expect(tests, 1);
+ expect(node().isPrimary, true);
+ });
+}
+
+const changedDuringTest = 'The node changed during the test. Please try again.';
### test/widget_tests/tls_certificate_dialog_test.dart
@@ -0,0 +1,132 @@
+import 'dart:io';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:stackwallet/models/isar/stack_theme.dart';
+import 'package:stackwallet/models/node_form_data.dart';
+import 'package:stackwallet/themes/stack_colors.dart';
+import 'package:stackwallet/utilities/connection_check/electrum_connection_check.dart';
+import 'package:stackwallet/utilities/tls_certificate.dart';
+import 'package:stackwallet/widgets/tls_certificate_dialog.dart';
+
+import '../sample_data/theme_json.dart';
+import '../utilities/tls_test_server.dart';
+
+void main() {
+ late X509Certificate certificate;
+ setUpAll(() async {
+ final server = await TlsElectrumServer.start();
+ try {
+ certificate = (await testElectrumConnection(
+ host: '127.0.0.1',
+ port: server.port,
+ useSSL: true,
+ timeout: const Duration(seconds: 2),
+ )).certificate!;
+ } finally {
+ await server.close();
+ }
+ });
+
+ for (final choice in ['Cancel', 'Trust']) {
+ testWidgets('shows certificate details and returns $choice', (
+ tester,
+ ) async {
+ bool? approved;
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: ThemeData(
+ extensions: [
+ StackColors.fromStackColorTheme(
+ StackTheme.fromJson(json: lightThemeJsonMap),
+ ),
+ ],
+ ),
+ home: Builder(
+ builder: (context) => Scaffold(
+ body: TextButton(
+ onPressed: () async {
+ approved = await showBadX509CertificateDialog(
+ certificate,
+ 'node.example',
+ 50002,
+ context,
+ );
+ },
+ child: const Text('Review'),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Review'));
+ await tester.pumpAndSettle();
+ final message = tester
+ .widgetList<SelectableText>(find.byType(SelectableText))
+ .map((text) => text.data)
+ .join('\n');
+ expect(message, contains('node.example:50002'));
+ expect(message, contains(certificate.subject));
+ expect(message, contains(certificate.issuer));
+ expect(message, contains('${certificate.endValidity.toUtc()}'));
+ expect(message, contains(certificateFingerprint(certificate.der)));
+ await tester.tap(find.text(choice));
+ await tester.pumpAndSettle();
+ expect(approved, choice == 'Trust');
+ });
+ }
+ testWidgets('Trust resumes the test on its current route', (tester) async {
+ final data = NodeFormData()
+ ..host = 'node.example'
+ ..port = 50002
+ ..useSSL = true;
+ bool? success;
+ await tester.pumpWidget(
+ MaterialApp(
+ theme: ThemeData(
+ extensions: [
+ StackColors.fromStackColorTheme(
+ StackTheme.fromJson(json: lightThemeJsonMap),
+ ),
+ ],
+ ),
+ home: Builder(
+ builder: (context) => Scaffold(
+ body: TextButton(
+ child: const Text('Test'),
+ onPressed: () async {
+ success = await testElectrumNodeConnection(
+ data,
+ isActive: () =>
+ context.mounted &&
+ ModalRoute.of(context)?.isCurrent != false,
+ requestTrust: (cert, host, port) =>
+ showBadX509CertificateDialog(cert, host, port, context),
+ testConnection:
+ ({
+ required host,
+ required port,
+ required useSSL,
+ trustedCertificatePem,
+ }) async => trustedCertificatePem == null
+ ? ElectrumConnectionResult(
+ success: false,
+ certificate: certificate,
+ )
+ : const ElectrumConnectionResult(success: true),
+ );
+ },
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Test'));
+ await tester.pumpAndSettle();
+ expect(success, null);
+ await tester.tap(find.text('Trust'));
+ await tester.pumpAndSettle();
+ expect(success, true);
+ expect(data.trustedCertificatePem, certificate.pem);
+ });
+}Why this scored 61/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.