Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions docs/building/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
45 changes: 45 additions & 0 deletions integration_test/zcash/zcash_regtest_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,18 @@ 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';

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;
Expand Down Expand Up @@ -80,6 +85,24 @@ Future<ZcashWallet> 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;
Expand Down Expand Up @@ -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)));
}
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -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();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -389,6 +390,7 @@ class _RestoreWalletViewState extends ConsumerState<RestoreWalletView> {

case ZcashWallet():
await wallet.init(isRestore: true);
ZcashSaplingParameters.instance.ensureInBackground();
break;

default:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down Expand Up @@ -501,6 +502,7 @@ abstract class SWB {

case ZcashWallet():
await wallet.init(isRestore: true);
ZcashSaplingParameters.instance.ensureInBackground();
break;

default:
Expand Down
137 changes: 137 additions & 0 deletions lib/services/zcash_sapling_parameters.dart
Original file line number Diff line number Diff line change
@@ -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<Directory> 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<Directory> 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<zcash.SaplingProvingParameters> 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<void>(
(_) {},
onError: (Object e, StackTrace s) {
Logging.instance.w(
'The Sapling parameters could not be downloaded',
error: e,
stackTrace: s,
);
},
),
);
}

static Future<Directory> _defaultCacheRoot() async => Directory(
p.join(
(await StackFileSystem.applicationRootDirectory()).path,
'zcash',
'sapling_parameters',
),
);
}

class _DownloadSource implements zcash.SaplingParameterSource {
const _DownloadSource();

@override
Stream<List<int>> 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);
}
}
}
72 changes: 64 additions & 8 deletions lib/wallets/wallet/impl/zcash_wallet.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -31,15 +32,18 @@ typedef ZcashAccountSessionFactory = ZcashAccountSession Function(
typedef ZcashSaplingParameterResolver =
Future<zcash.SaplingProvingParameters> 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<Zcash> {
Expand All @@ -57,8 +61,27 @@ class ZcashWallet extends Bip39Wallet<Zcash> {
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<zcash.SaplingProvingParameters>
_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.
Expand Down Expand Up @@ -271,7 +294,40 @@ class ZcashWallet extends Bip39Wallet<Zcash> {
Future<void> checkSaveInitialReceivingAddress() async {}

@override
Future<TxData> prepareSend({required TxData txData}) => _sendMutex.protect(
Future<TxData> 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<void> _fetchSaplingParametersFor(TxData txData) async {
for (final recipient in txData.recipients ?? const <TxRecipient>[]) {
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<TxData> _prepareSend({required TxData txData}) => _sendMutex.protect(
() async {
final recipients = txData.recipients;
if (recipients == null || recipients.isEmpty) {
Expand Down
Loading