diff --git a/docs/building/testing.md b/docs/building/testing.md index a42685662..eaf2940f5 100644 --- a/docs/building/testing.md +++ b/docs/building/testing.md @@ -45,8 +45,9 @@ The unit tests in `test/wallets/zcash_*_test.dart` use fakes and need no node. the app's own `zcash-ffi` library, against a private regtest chain. It starts a `zebrad` and a `lightwalletd` on free local ports, in a temporary directory, and stops them when it ends. It covers a new wallet, receiving, a send with a -memo from broadcast to confirmation, spending received funds, and a restore -from the recovery phrase and birthday. Run it through the wrapper, on a Linux +memo from broadcast to confirmation, spending received funds, a restore from +the recovery phrase and birthday, and a payment to a Sapling address. Run it +through the wrapper, on a Linux or macOS host with an app configured with `ZCASH` enabled: ```sh @@ -61,6 +62,10 @@ lightwalletd 0.6.1. The Linux app links the JsonCPP and libsecret that `scripts/linux/build_secure_storage_deps.sh` run once. A Linux host without a display needs `xvfb-run -a` in front of the command. +The Sapling payment needs the Sapling proving parameters. The wallets download +them (about 52 MB) as the app does, unless `SAPLING_PARAMS_DIR` names a +directory that holds `sapling-spend.params` and `sapling-output.params`. + ## Xelis integration tests Run these on a configured desktop target (`windows`, `linux`, or `macos`) with diff --git a/integration_test/zcash/zcash_regtest_test.dart b/integration_test/zcash/zcash_regtest_test.dart index b43d30576..26b463f26 100644 --- a/integration_test/zcash/zcash_regtest_test.dart +++ b/integration_test/zcash/zcash_regtest_test.dart @@ -28,6 +28,7 @@ import 'package:stackwallet/wallets/models/tx_data.dart'; import 'package:stackwallet/wallets/wallet/impl/zcash_wallet.dart'; import 'package:stackwallet/wallets/wallet/intermediate/zcash_wallet_state_controller.dart'; import 'package:stackwallet/wallets/wallet/wallet.dart'; +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; import '../../test/wallets/support/xelis_test_fakes.dart' show MemorySecrets; import 'zcash_regtest_chain.dart'; @@ -35,6 +36,10 @@ import 'zcash_regtest_chain.dart'; const _zebrad = String.fromEnvironment('ZEBRAD_BIN'); const _lightwalletd = String.fromEnvironment('LIGHTWALLETD_BIN'); +/// A directory that holds sapling-spend.params and sapling-output.params. +/// Without it the wallets download the parameters, as the app does. +const _saplingParameters = String.fromEnvironment('SAPLING_PARAMS_DIR'); + final _coin = Zcash.regtest(); late ZcashRegtestChain chain; @@ -80,6 +85,24 @@ Future wallet( wallet.configureRegtestConsensus( nu63ActivationHeight: ZcashRegtestChain.nu63ActivationHeight, ); + if (_saplingParameters.isNotEmpty) { + wallet.configureSaplingParameterResolver( + () => + zcash.SaplingProvingParameterCache( + cacheRoot: Directory(p.join(root.path, 'sapling_parameters')), + ).resolve( + source: zcash.FileSaplingParameterSource( + manifest: zcash.officialSaplingParameterManifestV1, + spendFile: File( + p.join(_saplingParameters, 'sapling-spend.params'), + ), + outputFile: File( + p.join(_saplingParameters, 'sapling-output.params'), + ), + ), + ), + ); + } await wallet.init(isRestore: restore); if (restore) await wallet.recover(isRescan: false); return wallet; @@ -309,6 +332,28 @@ void main() { expect(restoredSend.type, TransactionType.outgoing); expect(sent(restoredSend), zec(amount + paidFee)); expect(fee(restoredSend), zec(0)); + + // Pay a Sapling address, which is proven with the Sapling parameters. + final bobSapling = + (await MainDB.instance + .getAddresses(bob.walletId) + .filter() + .typeEqualTo(AddressType.zcashSapling) + .findFirst())! + .value; + expect(bobSapling, startsWith('zregtestsapling1')); + final bobBefore = bob.info.cachedBalance; + final toSapling = await alice.prepareSend( + txData: payment(bobSapling, zec(amount ~/ 4)), + ); + final saplingTxid = (await alice.confirmSend(txData: toSapling)).txid!; + await chain.waitForMempool(saplingTxid); + await chain.mine(1); + await sync(bob); + // Sapling funds count towards the total. A send spends Ironwood notes. + expect(bob.info.cachedBalance.total, bobBefore.total + zec(amount ~/ 4)); + expect(bob.info.cachedBalance.spendable, bobBefore.spendable); + expect(received(await row(bob, saplingTxid)), zec(amount ~/ 4)); }); }, timeout: const Timeout(Duration(minutes: 15))); } diff --git a/lib/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart b/lib/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart index 1cd0a14dc..e1680d8d9 100644 --- a/lib/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart +++ b/lib/pages/add_wallet_views/new_wallet_recovery_phrase_warning_view/new_wallet_recovery_phrase_warning_view.dart @@ -22,6 +22,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/zcash_sapling_parameters.dart'; import '../../../themes/stack_colors.dart'; import '../../../utilities/assets.dart'; import '../../../utilities/logger.dart'; @@ -269,6 +270,9 @@ class _NewWalletRecoveryPhraseWarningViewState "Check the connection and the node, then try again.\n\n$e", ); } + // Fetch the Sapling parameters now, so that the first send that needs + // them does not wait for the download. + ZcashSaplingParameters.instance.ensureInBackground(); } else { await wallet.init(); } diff --git a/lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart b/lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart index 27a1c150a..a003cee5b 100644 --- a/lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart +++ b/lib/pages/add_wallet_views/restore_wallet_view/restore_wallet_view.dart @@ -29,6 +29,7 @@ import '../../../providers/global/secure_store_provider.dart'; import '../../../providers/providers.dart'; import '../../../services/transaction_notification_tracker.dart'; import '../../../services/wallets.dart'; +import '../../../services/zcash_sapling_parameters.dart'; import '../../../themes/stack_colors.dart'; import '../../../utilities/address_utils.dart'; import '../../../utilities/assets.dart'; @@ -389,6 +390,7 @@ class _RestoreWalletViewState extends ConsumerState { case ZcashWallet(): await wallet.init(isRestore: true); + ZcashSaplingParameters.instance.ensureInBackground(); break; default: diff --git a/lib/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.dart b/lib/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.dart index 98e73a3ce..0366a011e 100644 --- a/lib/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.dart +++ b/lib/pages/settings_views/global_settings_view/stack_backup_views/helpers/restore_create_backup.dart @@ -42,6 +42,7 @@ import '../../../../../services/trade_notes_service.dart'; import '../../../../../services/trade_sent_from_stack_service.dart'; import '../../../../../services/trade_service.dart'; import '../../../../../services/wallets.dart'; +import '../../../../../services/zcash_sapling_parameters.dart'; import '../../../../../utilities/enums/backup_frequency_type.dart'; import '../../../../../utilities/enums/stack_restoring_status.dart'; import '../../../../../utilities/enums/sync_type_enum.dart'; @@ -501,6 +502,7 @@ abstract class SWB { case ZcashWallet(): await wallet.init(isRestore: true); + ZcashSaplingParameters.instance.ensureInBackground(); break; default: diff --git a/lib/services/zcash_sapling_parameters.dart b/lib/services/zcash_sapling_parameters.dart new file mode 100644 index 000000000..4b595c812 --- /dev/null +++ b/lib/services/zcash_sapling_parameters.dart @@ -0,0 +1,137 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:path/path.dart' as p; +import 'package:socks5_proxy/socks_client.dart'; +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +import '../utilities/logger.dart'; +import '../utilities/prefs.dart'; +import '../utilities/stack_file_system.dart'; +import 'tor_service.dart'; + +/// The Sapling proving parameters: two files of about 52 MB together, the +/// same for every wallet, that a Zcash transaction with a Sapling spend or +/// output is proven with. +/// +/// They are downloaded once, into the app's data directory, and used only +/// after their lengths and SHA-256 digests match the ones the Zcash project +/// publishes (`zcash.officialSaplingParameterManifestV1`). The download goes +/// through Tor when Tor is enabled. +class ZcashSaplingParameters { + ZcashSaplingParameters({ + Future Function()? cacheRoot, + zcash.SaplingParameterSource? source, + this.manifest = zcash.officialSaplingParameterManifestV1, + }) : _cacheRoot = cacheRoot ?? _defaultCacheRoot, + _source = source ?? const _DownloadSource(); + + static final instance = ZcashSaplingParameters(); + + /// Where the Zcash project serves the parameters. + static final downloadBase = Uri.https('download.z.cash', '/downloads/'); + + /// The files to fetch, with the lengths and digests they must have. + final zcash.SaplingParameterManifest manifest; + + final Future Function() _cacheRoot; + final zcash.SaplingParameterSource _source; + + zcash.SaplingProvingParameters? _installed; + + /// The verified parameters, downloaded first if they are not on disk. + /// Callers that arrive during a download share it. + /// + /// A download that makes no progress for 30 seconds fails, and so does one + /// that is not done in an hour: a slow connection, such as Tor, needs more + /// than the cache's default of ten minutes. A failed download starts over. + Future resolve() async => + _installed ??= await zcash.SaplingProvingParameterCache( + cacheRoot: await _cacheRoot(), + manifest: manifest, + totalTimeout: const Duration(hours: 1), + ).resolve(source: _source); + + /// What to tell the user about an [error] of [resolve]. + static String describe(Object error) => switch (error) { + zcash.SaplingParameterException( + failure: zcash.SaplingParameterFailure.wrongSize || + zcash.SaplingParameterFailure.wrongHash, + ) => + 'The download was not the published files. Try again later.', + zcash.SaplingParameterException( + failure: zcash.SaplingParameterFailure.storageFailure || + zcash.SaplingParameterFailure.publishFailed || + zcash.SaplingParameterFailure.untrustedCacheEntry, + ) => + 'They could not be saved on this device.', + _ when Prefs.instance.useTor => + 'They could not be downloaded through Tor. Check that Tor is ' + 'connected and try again.', + _ => 'They could not be downloaded. Check the connection and try again.', + }; + + /// Starts the download if the parameters are not on disk, without waiting + /// for it. A failure is logged: the send that needs the parameters tries + /// again. + void ensureInBackground() { + unawaited( + resolve().then( + (_) {}, + onError: (Object e, StackTrace s) { + Logging.instance.w( + 'The Sapling parameters could not be downloaded', + error: e, + stackTrace: s, + ); + }, + ), + ); + } + + static Future _defaultCacheRoot() async => Directory( + p.join( + (await StackFileSystem.applicationRootDirectory()).path, + 'zcash', + 'sapling_parameters', + ), + ); +} + +class _DownloadSource implements zcash.SaplingParameterSource { + const _DownloadSource(); + + @override + Stream> open(zcash.SaplingParameterArtifact artifact) async* { + final client = HttpClient() + ..connectionTimeout = const Duration(seconds: 30); + try { + if (Prefs.instance.useTor) { + final proxy = TorService.sharedInstance.getProxyInfo(); + SocksTCPClient.assignToHttpClient(client, [ + ProxySettings(proxy.host, proxy.port), + ]); + } + final request = await client.getUrl( + ZcashSaplingParameters.downloadBase.resolve(artifact.fileName), + ); + final response = await request.close(); + if (response.statusCode != HttpStatus.ok) { + throw HttpException( + 'The Sapling parameter server answered ${response.statusCode}', + ); + } + yield* response; + } catch (e, s) { + // The cache reports only that the source failed. + Logging.instance.w( + 'Downloading ${artifact.fileName} failed', + error: e, + stackTrace: s, + ); + rethrow; + } finally { + client.close(force: true); + } + } +} diff --git a/lib/wallets/wallet/impl/zcash_wallet.dart b/lib/wallets/wallet/impl/zcash_wallet.dart index 010a92f8f..e406100cb 100644 --- a/lib/wallets/wallet/impl/zcash_wallet.dart +++ b/lib/wallets/wallet/impl/zcash_wallet.dart @@ -11,6 +11,7 @@ import 'package:zcash_flutter/zcash_flutter.dart' as zcash; import '../../../models/isar/models/blockchain_data/address.dart'; import '../../../models/isar/models/blockchain_data/v2/transaction_v2.dart'; import '../../../models/paymint/fee_object_model.dart'; +import '../../../services/zcash_sapling_parameters.dart'; import '../../../utilities/amount/amount.dart'; import '../../../utilities/logger.dart'; import '../../../utilities/stack_file_system.dart'; @@ -31,15 +32,18 @@ typedef ZcashAccountSessionFactory = ZcashAccountSession Function( typedef ZcashSaplingParameterResolver = Future Function(); -/// A send needs the Sapling proving parameters and the wallet has no source -/// for them. +/// A send needs the Sapling proving parameters and the wallet could not get +/// them, for the [reason] the user is told. class ZcashSaplingParametersUnavailableException implements Exception { - const ZcashSaplingParametersUnavailableException(); + const ZcashSaplingParametersUnavailableException([ + this.reason = 'They are not available.', + ]); + + final String reason; @override String toString() => - 'This Zcash transaction needs the Sapling proving parameters, which ' - 'are not available'; + 'This Zcash transaction needs the Sapling proving parameters. $reason'; } class ZcashWallet extends Bip39Wallet { @@ -57,8 +61,27 @@ class ZcashWallet extends Bip39Wallet { ZcashScanExecutor? _scanExecutor; ZcashWalletSendService _sendService = const ZcashProductionWalletSendService(); - ZcashSaplingParameterResolver _saplingParameterResolver = () => - throw const ZcashSaplingParametersUnavailableException(); + ZcashSaplingParameterResolver _saplingParameterResolver = + _downloadedSaplingParameters; + + /// The parameters from the app's cache, downloaded first when a wallet's + /// creation did not already fetch them (see [ZcashSaplingParameters]). + static Future + _downloadedSaplingParameters() async { + try { + return await ZcashSaplingParameters.instance.resolve(); + } catch (e, s) { + Logging.instance.w( + 'The Sapling parameters are not available', + error: e, + stackTrace: s, + ); + throw ZcashSaplingParametersUnavailableException( + ZcashSaplingParameters.describe(e), + ); + } + } + final _sendMutex = Mutex(); /// Stops the scans of the current [_stateController] at their next step. @@ -271,7 +294,40 @@ class ZcashWallet extends Bip39Wallet { Future checkSaveInitialReceivingAddress() async {} @override - Future prepareSend({required TxData txData}) => _sendMutex.protect( + Future prepareSend({required TxData txData}) async { + await _fetchSaplingParametersFor(txData); + return _prepareSend(txData: txData); + } + + /// Downloads the Sapling parameters when [txData] pays a Sapling address + /// and they are not on disk yet. The download can take minutes, so it + /// happens before the send lock is taken and before the heights of the + /// transaction are chosen. + Future _fetchSaplingParametersFor(TxData txData) async { + for (final recipient in txData.recipients ?? const []) { + final bool sapling; + try { + sapling = ZcashProductionWalletSendService.paysSapling( + network: cryptoCurrency.nativeNetwork, + recipient: _resolveStackPayment( + address: recipient.address, + amount: recipient.amount.raw, + memo: null, + ).address, + targetHeight: info.cachedChainHeight + 1, + ); + } catch (_) { + // The send reports what is wrong with a recipient. + continue; + } + if (sapling) { + await _saplingParameterResolver(); + return; + } + } + } + + Future _prepareSend({required TxData txData}) => _sendMutex.protect( () async { final recipients = txData.recipients; if (recipients == null || recipients.isEmpty) { diff --git a/lib/wallets/wallet/intermediate/zcash_send.dart b/lib/wallets/wallet/intermediate/zcash_send.dart index 71a16c10d..d153e63d1 100644 --- a/lib/wallets/wallet/intermediate/zcash_send.dart +++ b/lib/wallets/wallet/intermediate/zcash_send.dart @@ -441,7 +441,13 @@ final class ZcashProductionWalletSendService implements ZcashWalletSendService { ZcashSendPreparationRequest request, ) async { final outputs = [ - for (final payment in request.payments) _resolveOutput(request, payment), + for (final payment in request.payments) + _resolveOutput( + network: request.network, + payment: payment, + targetHeight: request.targetHeight, + expiryHeight: request.expiryHeight, + ), ]; return _prepareIronwood(request, outputs); } @@ -470,20 +476,37 @@ final class ZcashProductionWalletSendService implements ZcashWalletSendService { return notes.length; } - zcash.ProposalOutput _resolveOutput( - ZcashSendPreparationRequest request, - ZcashSendPayment payment, - ) { - final nativeNetwork = request.network; + /// Whether a payment to [recipient], in a transaction that targets + /// [targetHeight], has a Sapling output. Such a transaction is proven with + /// the Sapling parameters. + static bool paysSapling({ + required zcash.ZcashNetwork network, + required String recipient, + required int targetHeight, + }) => + _resolveOutput( + network: network, + payment: ZcashSendPayment(recipient: recipient, amountZatoshis: 1), + targetHeight: targetHeight, + expiryHeight: targetHeight, + ).actualOutputPool == + zcash.ProposalOutputPool.sapling; + + static zcash.ProposalOutput _resolveOutput({ + required zcash.ZcashNetwork network, + required ZcashSendPayment payment, + required int targetHeight, + required int expiryHeight, + }) { final metadata = zcash.decodeNativeAddress( address: payment.recipient, - network: nativeNetwork, + network: network, ); final inventory = metadata.receiverType == zcash.ZcashAddressReceiverType.unified ? zcash.inventoryUnifiedAddressReceivers( address: payment.recipient, - network: nativeNetwork, + network: network, ) : null; return zcash.resolveProposalOutput( @@ -494,9 +517,9 @@ final class ZcashProductionWalletSendService implements ZcashWalletSendService { ), address: metadata, unifiedReceivers: inventory, - network: _addressNetwork(request.network), - targetHeight: request.targetHeight, - transactionExpiryHeight: request.expiryHeight, + network: _addressNetwork(network), + targetHeight: targetHeight, + transactionExpiryHeight: expiryHeight, currentUnixTime: DateTime.now().toUtc().millisecondsSinceEpoch ~/ 1000, ); } diff --git a/scripts/zcash_e2e_test.sh b/scripts/zcash_e2e_test.sh index 190c61e8a..5d2bbc22a 100755 --- a/scripts/zcash_e2e_test.sh +++ b/scripts/zcash_e2e_test.sh @@ -10,6 +10,10 @@ set -euo pipefail # ZEBRAD_BIN and LIGHTWALLETD_BIN, or from PATH. The suite is tested with # zebrad 7.0.0 and lightwalletd 0.6.1. # +# One payment needs the Sapling proving parameters. The wallets download them +# unless SAPLING_PARAMS_DIR names a directory that holds sapling-spend.params +# and sapling-output.params. +# # Usage: bash scripts/zcash_e2e_test.sh [device] [flutter test options] # The device defaults to the host desktop: linux or macos. A Linux host # without a display needs one, for example @@ -63,4 +67,5 @@ lightwalletd="$(executable "${LIGHTWALLETD_BIN:-}" lightwalletd LIGHTWALLETD_BIN -d "$device" \ --dart-define=ZEBRAD_BIN="$zebrad" \ --dart-define=LIGHTWALLETD_BIN="$lightwalletd" \ + ${SAPLING_PARAMS_DIR:+--dart-define=SAPLING_PARAMS_DIR="$SAPLING_PARAMS_DIR"} \ "$@" diff --git a/test/services/zcash_sapling_parameters_test.dart b/test/services/zcash_sapling_parameters_test.dart new file mode 100644 index 000000000..8fb3508e5 --- /dev/null +++ b/test/services/zcash_sapling_parameters_test.dart @@ -0,0 +1,153 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:crypto/crypto.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/services/zcash_sapling_parameters.dart'; +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +final _spend = utf8.encode('spend parameters'); +final _output = utf8.encode('output parameters'); + +/// A pair small enough to serve from memory, checked as the real one is. +final _manifest = zcash.SaplingParameterManifest( + version: 'test-v1', + spend: zcash.SaplingParameterArtifact( + fileName: 'sapling-spend.params', + expectedBytes: _spend.length, + sha256Hex: sha256.convert(_spend).toString(), + ), + output: zcash.SaplingParameterArtifact( + fileName: 'sapling-output.params', + expectedBytes: _output.length, + sha256Hex: sha256.convert(_output).toString(), + ), +); + +class _Source implements zcash.SaplingParameterSource { + _Source({this.spend, this.gate}); + + /// What is served for the spend file, when not the right bytes. + final List? spend; + final Future? gate; + final opened = []; + + @override + Stream> open(zcash.SaplingParameterArtifact artifact) async* { + opened.add(artifact.fileName); + await gate; + yield artifact.fileName == _manifest.spend.fileName + ? spend ?? _spend + : _output; + } +} + +void main() { + late Directory root; + + setUp(() async { + root = await Directory.systemTemp.createTemp('zcash_sapling_parameters_'); + addTearDown(() => root.delete(recursive: true)); + }); + + ZcashSaplingParameters service(zcash.SaplingParameterSource source) => + ZcashSaplingParameters( + cacheRoot: () async => root, + source: source, + manifest: _manifest, + ); + + test('downloads the parameters once and then uses the files', () async { + final source = _Source(); + final first = service(source); + + final parameters = await first.resolve(); + + expect(source.opened, ['sapling-spend.params', 'sapling-output.params']); + expect(File(parameters.spendParamsPath).readAsBytesSync(), _spend); + expect(File(parameters.outputParamsPath).readAsBytesSync(), _output); + await first.resolve(); + expect(source.opened, hasLength(2)); + + // After a restart the files on disk are used, with no download. + final offline = _Source(spend: const []); + final again = await service(offline).resolve(); + expect(again.spendParamsPath, parameters.spendParamsPath); + expect(offline.opened, isEmpty); + }); + + test('refuses a download that is not the published file', () async { + final tampered = _Source(spend: utf8.encode('spend parameterz')); + + await expectLater( + service(tampered).resolve(), + throwsA( + isA().having( + (error) => error.failure, + 'failure', + zcash.SaplingParameterFailure.wrongHash, + ), + ), + ); + + // Nothing was installed, and a later download of the right file works. + final source = _Source(); + await service(source).resolve(); + expect(source.opened, hasLength(2)); + }); + + test('tells the user what kind of failure a download had', () async { + Object? error; + try { + await service(_Source(spend: utf8.encode('spend parameterz'))).resolve(); + } catch (e) { + error = e; + } + + expect( + ZcashSaplingParameters.describe(error!), + 'The download was not the published files. Try again later.', + ); + expect( + ZcashSaplingParameters.describe( + const zcash.SaplingParameterException( + zcash.SaplingParameterFailure.storageFailure, + 'storage', + ), + ), + 'They could not be saved on this device.', + ); + expect( + ZcashSaplingParameters.describe( + const zcash.SaplingParameterException( + zcash.SaplingParameterFailure.sourceInterrupted, + 'source', + ), + ), + 'They could not be downloaded. Check the connection and try again.', + ); + }); + + test('callers that arrive during a download share it', () async { + final gate = Completer(); + final source = _Source(gate: gate.future); + final parameters = service(source); + + final first = parameters.resolve(); + final second = parameters.resolve(); + parameters.ensureInBackground(); + gate.complete(); + + expect((await first).spendParamsPath, (await second).spendParamsPath); + expect(source.opened, hasLength(2)); + }); + + test('a background download that fails is not an unhandled error', () async { + final parameters = service(_Source(spend: const [1])); + + parameters.ensureInBackground(); + + await expectLater(parameters.resolve(), throwsA(anything)); + }); +} diff --git a/test/wallets/zcash_wallet_send_test.dart b/test/wallets/zcash_wallet_send_test.dart index 821507a51..984d94fed 100644 --- a/test/wallets/zcash_wallet_send_test.dart +++ b/test/wallets/zcash_wallet_send_test.dart @@ -555,6 +555,56 @@ void main() { await wallet.exit(); }); + test('a payment to a Sapling address fetches the Sapling parameters ' + 'before it takes the send lock', () async { + final fetching = Completer(); + final fetched = Completer(); + final wallet = await _wallet( + SendClient(), + RecordingSendService(), + 'sapling-parameters-first', + saplingParameterResolver: () { + fetching.complete(); + return fetched.future; + }, + ); + final seed = zcash.nativeMnemonicToSeed( + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about', + ); + final address = await zcash.deriveAddress( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.mainnet, + ); + TxData payment(String to, AddressType type) => TxData( + recipients: [ + TxRecipient( + address: to, + amount: Amount(rawValue: BigInt.from(40000), fractionDigits: 8), + isChange: false, + addressType: type, + ), + ], + ); + + // A payment to a Unified Address has no Sapling output: no download. + await wallet.prepareSend( + txData: payment(address.ua, AddressType.zcashUnified), + ); + expect(fetching.isCompleted, isFalse); + + final preparing = wallet.prepareSend( + txData: payment(address.saplingAddress!, AddressType.zcashSapling), + ); + await fetching.future; + + // The download can take minutes. It does not hold the send lock, which + // closing the wallet needs. + await wallet.exit().timeout(const Duration(seconds: 1)); + fetched.completeError(StateError('the download failed')); + await expectLater(preparing, throwsStateError); + }); + test('wallet surfaces a missing Sapling parameter source', () async { final wallet = await _wallet( SendClient(),