diff --git a/docs/building/native-libraries.md b/docs/building/native-libraries.md index e9f4e38a8..50a645fa1 100644 --- a/docs/building/native-libraries.md +++ b/docs/building/native-libraries.md @@ -61,6 +61,7 @@ to build them in `dev` mode. | Flutter and platform plugins | Target SDKs and the platform's C/C++ build tools in either mode | | OpenAlias / DNSSEC (every app) | Rustup on the Flutter host in both modes; `dnssec_resolver` builds from source with Rust **1.90.0** | | Xelis (Stack Wallet) | Rustup; its hook installs Rust **1.99.1** and the required target; Android needs NDK r28 or newer | +| Zcash (Stack Wallet) | Rustup; the `zcash_flutter` hook builds `zcash-ffi` from crates.io sources with the toolchain its `rust-toolchain.toml` pins (Rust **1.99.1**), which the hook installs when it is missing, so no default toolchain is needed. Every app depends on `zcash_flutter`, because `lib/` uses the API it re-exports, but only an app configured with the `ZCASH` flag builds and bundles `zcash-ffi`; the others turn the hook off with `hooks.user_defines.zcash_flutter.enabled: false` | | Spark (Stack Wallet and Campfire) | CMake and a C++ compiler; its native-assets hook builds from source | | Coinlib secp256k1 | A separate platform build, described in each host guide | | MWEB (Stack Wallet) | Go **1.24.1** or newer; CI uses 1.24.13. The Windows executable has a separate WSL build (Go 1.24.0 or newer) or prebuilt download | diff --git a/lib/app_config.dart b/lib/app_config.dart index d594cf5d9..52ee5e1e3 100644 --- a/lib/app_config.dart +++ b/lib/app_config.dart @@ -1,6 +1,8 @@ // ignore: unused_import import 'dart:io'; +import 'package:meta/meta.dart'; + import 'models/isar/models/ethereum/eth_contract.dart'; import 'utilities/default_eth_tokens.dart'; import 'wallets/crypto_currency/crypto_currency.dart'; @@ -28,7 +30,15 @@ abstract class AppConfig { static ({String light, String dark})? get appIconAsset => _appIconAsset; - static List get coins => _supportedCoins; + static List get coins => _coinsOverride ?? _supportedCoins; + + static List? _coinsOverride; + + /// Replaces [coins] for tests of a coin this app config does not list. + /// Null restores the configured list. + @visibleForTesting + static set coinsOverride(List? coins) => + _coinsOverride = coins == null ? null : List.unmodifiable(coins); static List get defaultEthTokens => _defaultEthTokens; diff --git a/lib/models/isar/models/blockchain_data/address.dart b/lib/models/isar/models/blockchain_data/address.dart index 3366eb52c..605cdedd7 100644 --- a/lib/models/isar/models/blockchain_data/address.dart +++ b/lib/models/isar/models/blockchain_data/address.dart @@ -135,8 +135,9 @@ class Address extends CryptoCurrencyAddress { final json = jsonDecode(jsonString); final derivationPathString = json["derivationPath"] as String?; - final DerivationPath? derivationPath = - derivationPathString == null ? null : DerivationPath(); + final DerivationPath? derivationPath = derivationPathString == null + ? null + : DerivationPath(); if (derivationPath != null) { derivationPath.value = derivationPathString!; } @@ -176,7 +177,9 @@ enum AddressType { cardanoShelley, xelis, fact0rn, - mweb; + mweb, + zcashUnified, + zcashSapling; String get readableName { switch (this) { @@ -220,6 +223,10 @@ enum AddressType { return "FACT0RN"; case AddressType.mweb: return "MWEB"; + case AddressType.zcashUnified: + return "Zcash Unified"; + case AddressType.zcashSapling: + return "Zcash Sapling"; } } } diff --git a/lib/models/isar/models/blockchain_data/address.g.dart b/lib/models/isar/models/blockchain_data/address.g.dart index 48017f56b..342cc9c76 100644 --- a/lib/models/isar/models/blockchain_data/address.g.dart +++ b/lib/models/isar/models/blockchain_data/address.g.dart @@ -289,6 +289,8 @@ const _AddresstypeEnumValueMap = { 'xelis': 17, 'fact0rn': 18, 'mweb': 19, + 'zcashUnified': 20, + 'zcashSapling': 21, }; const _AddresstypeValueEnumMap = { 0: AddressType.p2pkh, @@ -311,6 +313,8 @@ const _AddresstypeValueEnumMap = { 17: AddressType.xelis, 18: AddressType.fact0rn, 19: AddressType.mweb, + 20: AddressType.zcashUnified, + 21: AddressType.zcashSapling, }; Id _addressGetId(Address object) { diff --git a/lib/services/price.dart b/lib/services/price.dart index ab47c8ebc..1ff999b01 100644 --- a/lib/services/price.dart +++ b/lib/services/price.dart @@ -50,6 +50,7 @@ class PriceAPI { Nano: "nano", Banano: "banano", Xelis: "xelis", + Zcash: "zcash", Salvium: "salvium", }; diff --git a/lib/services/wallets.dart b/lib/services/wallets.dart index 4f6448555..1d17b3a77 100644 --- a/lib/services/wallets.dart +++ b/lib/services/wallets.dart @@ -32,6 +32,7 @@ import '../wallets/wallet/impl/epiccash_wallet.dart'; 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/intermediate/zcash_wallet_persistence.dart'; import '../wallets/wallet/wallet.dart'; import '../wallets/wallet/wallet_mixin_interfaces/electrumx_interface.dart'; import 'event_bus/events/wallet_added_event.dart'; @@ -143,6 +144,13 @@ class Wallets { ); if (await directory.exists()) await directory.delete(recursive: true); } + if (info.coin is Zcash) { + await deleteZcashWalletPersistence( + applicationRoot: await StackFileSystem.applicationRootDirectory(), + walletId: walletId, + secureStorage: secureStorage, + ); + } await secureStorage.delete(key: Wallet.mnemonicKey(walletId: walletId)); await secureStorage.delete( diff --git a/lib/utilities/desktop_startup_and_reset.dart b/lib/utilities/desktop_startup_and_reset.dart index 41db48fb3..e2c21f692 100644 --- a/lib/utilities/desktop_startup_and_reset.dart +++ b/lib/utilities/desktop_startup_and_reset.dart @@ -32,6 +32,7 @@ abstract final class DesktopStartupAndReset { 'epiccash', 'mimblewimblecoin', 'xelis', + 'zcash', 'drift', 'sqlite', 'mwebd', diff --git a/lib/utilities/native_library_check.dart b/lib/utilities/native_library_check.dart index 1bd621976..c686c0577 100644 --- a/lib/utilities/native_library_check.dart +++ b/lib/utilities/native_library_check.dart @@ -56,6 +56,7 @@ bool _always() => true; bool _hasMonero() => AppConfig.coins.whereType().isNotEmpty; bool _hasWownero() => AppConfig.coins.whereType().isNotEmpty; bool _hasSalvium() => AppConfig.coins.whereType().isNotEmpty; +bool _hasZcash() => AppConfig.coins.whereType().isNotEmpty; /// coinlib's secp256k1, named as in its secp256k1_io.dart. Every non /// cryptonote wallet needs it. @@ -91,6 +92,13 @@ const nativeLibraries = [ macos: "SalviumWallet.framework/SalviumWallet", isBundled: _hasSalvium, ), + NativeLibrary( + displayName: "Zcash wallets", + windows: "zcash_ffi.dll", + linux: "libzcash_ffi.so", + macos: "zcash_ffi.framework/zcash_ffi", + isBundled: _hasZcash, + ), secp256k1NativeLibrary, ]; diff --git a/lib/wallets/crypto_currency/coins/zcash.dart b/lib/wallets/crypto_currency/coins/zcash.dart new file mode 100644 index 000000000..f889c09fc --- /dev/null +++ b/lib/wallets/crypto_currency/coins/zcash.dart @@ -0,0 +1,176 @@ +import 'package:meta/meta.dart'; +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +import '../../../models/isar/models/blockchain_data/address.dart'; +import '../../../models/node_model.dart'; +import '../../../utilities/default_nodes.dart'; +import '../../../utilities/enums/derive_path_type_enum.dart'; +import '../crypto_currency.dart'; +import '../intermediate/bip39_currency.dart'; + +class Zcash extends Bip39Currency { + Zcash(super.network) { + switch (network) { + case CryptoCurrencyNetwork.main: + _identifier = 'zcash'; + _prettyName = 'Zcash'; + _ticker = 'ZEC'; + nativeNetwork = zcash.ZcashNetwork.mainnet; + case CryptoCurrencyNetwork.test: + _identifier = 'zcashTestNet'; + _prettyName = 'tZcash'; + _ticker = 'tZEC'; + nativeNetwork = zcash.ZcashNetwork.testnet; + default: + throw ArgumentError.value(network, 'network', 'Unsupported network'); + } + } + + /// A local regtest chain, for tests that drive a real node. Stack Wallet + /// has no regtest network of its own, so this is a test network with + /// regtest's address encodings and consensus rules. + @visibleForTesting + Zcash.regtest() : super(CryptoCurrencyNetwork.test) { + _identifier = 'zcashRegtest'; + _prettyName = 'Zcash Regtest'; + _ticker = 'rZEC'; + nativeNetwork = zcash.ZcashNetwork.regtest; + } + + late final String _identifier; + late final String _prettyName; + late final String _ticker; + + /// The network as the Zcash backend names it. + late final zcash.ZcashNetwork nativeNetwork; + + // Regtest shares Stack Wallet's test network with testnet, so the base + // comparison by type and network would make the two equal. + @override + bool operator ==(Object other) => + other is Zcash && other.nativeNetwork == nativeNetwork; + + @override + int get hashCode => Object.hash(Zcash, nativeNetwork); + + @override + String get identifier => _identifier; + + @override + String get mainNetId => 'zcash'; + + @override + String get prettyName => _prettyName; + + @override + String get ticker => _ticker; + + @override + String get uriScheme => 'zcash'; + + @override + int get minConfirms => 1; + + @override + int get minCoinbaseConfirms => 100; + + @override + String get genesisHash => throw UnimplementedError('Not used for Zcash'); + + /// Whether [address] is one this wallet can pay: a Unified, Sapling or + /// transparent address of this network. Sprout and TEX addresses decode, + /// but a shielded payment cannot go to them. + @override + bool validateAddress(String address) => getAddressType(address) != null; + + @override + AddressType? getAddressType(String address) { + try { + return switch (zcash + .decodeNativeAddress(address: address, network: nativeNetwork) + .receiverType) { + zcash.ZcashAddressReceiverType.unified => AddressType.zcashUnified, + zcash.ZcashAddressReceiverType.sapling => AddressType.zcashSapling, + zcash.ZcashAddressReceiverType.p2pkh => AddressType.p2pkh, + zcash.ZcashAddressReceiverType.p2sh => AddressType.p2sh, + _ => null, + }; + } on StateError { + return null; + } on FormatException { + return null; + } + } + + @override + NodeModel defaultNode({required bool isPrimary}) { + final (host, port, useSSL) = switch (nativeNetwork) { + zcash.ZcashNetwork.mainnet => ('zec.rocks', 443, true), + zcash.ZcashNetwork.testnet => ('testnet.zec.rocks', 443, true), + zcash.ZcashNetwork.regtest => ('127.0.0.1', 9067, false), + }; + return NodeModel( + host: host, + port: port, + name: DefaultNodes.defaultName, + id: DefaultNodes.buildId(this), + useSSL: useSSL, + enabled: true, + coinName: identifier, + isFailover: true, + isDown: false, + torEnabled: false, + clearnetEnabled: true, + isPrimary: isPrimary, + ); + } + + // The lightwalletd connection is gRPC over a direct socket and is not + // routed through Tor. + @override + bool get torSupport => false; + + @override + int get defaultSeedPhraseLength => 24; + + @override + int get fractionDigits => 8; + + @override + bool get hasBuySupport => false; + + @override + bool get hasMnemonicPassphraseSupport => true; + + @override + List get possibleMnemonicLengths => const [12, 15, 18, 21, 24]; + + @override + AddressType get defaultAddressType => AddressType.zcashUnified; + + @override + BigInt get satsPerCoin => BigInt.from(100000000); + + @override + int get targetBlockTimeSeconds => 75; + + @override + DerivePathType get defaultDerivePathType => throw UnsupportedError( + 'Zcash does not use a Bitcoin-style derivation path selector', + ); + + @override + Uri defaultBlockExplorer(String txid) => switch (nativeNetwork) { + zcash.ZcashNetwork.mainnet => Uri.https( + 'mainnet.zcashexplorer.app', + '/transactions/$txid', + ), + zcash.ZcashNetwork.testnet => Uri.https( + 'testnet.zcashexplorer.app', + '/transactions/$txid', + ), + zcash.ZcashNetwork.regtest => throw UnsupportedError( + 'Zcash regtest transactions do not have a public block explorer', + ), + }; +} diff --git a/lib/wallets/crypto_currency/crypto_currency.dart b/lib/wallets/crypto_currency/crypto_currency.dart index d46382ea0..3072535a4 100644 --- a/lib/wallets/crypto_currency/crypto_currency.dart +++ b/lib/wallets/crypto_currency/crypto_currency.dart @@ -27,6 +27,7 @@ export 'coins/stellar.dart'; export 'coins/tezos.dart'; export 'coins/wownero.dart'; export 'coins/xelis.dart'; +export 'coins/zcash.dart'; enum CryptoCurrencyNetwork { main, diff --git a/lib/wallets/isar/models/wallet_info.g.dart b/lib/wallets/isar/models/wallet_info.g.dart index 0667a4feb..8a6dd75b3 100644 --- a/lib/wallets/isar/models/wallet_info.g.dart +++ b/lib/wallets/isar/models/wallet_info.g.dart @@ -274,6 +274,8 @@ const _WalletInfomainAddressTypeEnumValueMap = { 'xelis': 17, 'fact0rn': 18, 'mweb': 19, + 'zcashUnified': 20, + 'zcashSapling': 21, }; const _WalletInfomainAddressTypeValueEnumMap = { 0: AddressType.p2pkh, @@ -296,6 +298,8 @@ const _WalletInfomainAddressTypeValueEnumMap = { 17: AddressType.xelis, 18: AddressType.fact0rn, 19: AddressType.mweb, + 20: AddressType.zcashUnified, + 21: AddressType.zcashSapling, }; Id _walletInfoGetId(WalletInfo object) { diff --git a/lib/wallets/wallet/impl/zcash_wallet.dart b/lib/wallets/wallet/impl/zcash_wallet.dart new file mode 100644 index 000000000..010a92f8f --- /dev/null +++ b/lib/wallets/wallet/impl/zcash_wallet.dart @@ -0,0 +1,1212 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:crypto/crypto.dart'; +import 'package:isar_community/isar.dart'; +import 'package:meta/meta.dart'; +import 'package:mutex/mutex.dart'; +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 '../../../utilities/amount/amount.dart'; +import '../../../utilities/logger.dart'; +import '../../../utilities/stack_file_system.dart'; +import '../../crypto_currency/crypto_currency.dart'; +import '../../models/tx_data.dart'; +import '../intermediate/bip39_wallet.dart'; +import '../intermediate/zcash_account_session.dart'; +import '../intermediate/zcash_pending_send_store.dart'; +import '../intermediate/zcash_send.dart'; +import '../intermediate/zcash_transparent_receiver_discovery.dart'; +import '../intermediate/zcash_wallet_persistence.dart'; +import '../intermediate/zcash_wallet_state.dart'; +import '../intermediate/zcash_wallet_state_controller.dart'; + +typedef ZcashAccountSessionFactory = ZcashAccountSession Function( + zcash.ZcashNetwork network, +); +typedef ZcashSaplingParameterResolver = + Future Function(); + +/// A send needs the Sapling proving parameters and the wallet has no source +/// for them. +class ZcashSaplingParametersUnavailableException implements Exception { + const ZcashSaplingParametersUnavailableException(); + + @override + String toString() => + 'This Zcash transaction needs the Sapling proving parameters, which ' + 'are not available'; +} + +class ZcashWallet extends Bip39Wallet { + /// Takes the coin where other wallets take its network: regtest is a + /// [Zcash] on the test network, which the network alone does not identify. + ZcashWallet(super.cryptoCurrency); + + ZcashAccountSessionFactory _accountSessionFactory = (network) => + ZcashAccountSession(network: network); + ZcashAccountSession? _accountSession; + ZcashWalletStateController? _stateController; + Future? _openingStateController; + ZcashEncryptedWalletStateStore? _stateStore; + ZcashPendingSendStore? _pendingSendStore; + ZcashScanExecutor? _scanExecutor; + ZcashWalletSendService _sendService = + const ZcashProductionWalletSendService(); + ZcashSaplingParameterResolver _saplingParameterResolver = () => + throw const ZcashSaplingParametersUnavailableException(); + final _sendMutex = Mutex(); + + /// Stops the scans of the current [_stateController] at their next step. + ZcashRecoveryCancellationToken? _scanCancellation; + ZcashPreparedWalletSend? _preparedSend; + + /// The connection [_preparedSend] was prepared over. + ZcashAccountSession? _preparedSession; + int? _regtestNu63ActivationHeight; + String? _ufvk; + String? _accountFingerprint; + zcash.ZcashAccountMetadata? _accountMetadata; + zcash.ZcashViewingKeys? _viewingKeys; + List _additionalTransparentReceivers = + const []; + ZcashTransparentReceiverDiscovery? _transparentReceiverDiscovery; + bool _exited = false; + Future? _exiting; + + /// The sync of the refresh in progress. [updateChainHeight] starts each + /// refresh (see [Wallet.refresh]) and syncs. The transaction and balance + /// updates that follow use its result and do not sync again. + ZcashWalletSnapshot? _refreshSnapshot; + + @override + int get isarTransactionVersion => 2; + + @override + bool get supportsMultiRecipient => true; + + @visibleForTesting + int get accountSessionGeneration => _accountSession?.generation ?? 0; + + void configureAccountSessionFactory(ZcashAccountSessionFactory factory) { + if (_accountSession != null) { + throw StateError('The Zcash account session is already initialized'); + } + _accountSessionFactory = factory; + } + + void configureSendService(ZcashWalletSendService service) { + if (_stateController != null || _preparedSend != null) { + throw StateError('The Zcash send service is already in use'); + } + _sendService = service; + } + + void configureSaplingParameterResolver( + ZcashSaplingParameterResolver resolver, + ) { + if (_stateController != null || _preparedSend != null) { + throw StateError( + 'The Zcash Sapling parameter resolver is already in use', + ); + } + _saplingParameterResolver = resolver; + } + + void configureRegtestConsensus({required int nu63ActivationHeight}) { + if (cryptoCurrency.nativeNetwork != zcash.ZcashNetwork.regtest) { + throw StateError('Custom Zcash activation heights are regtest-only'); + } + if (nu63ActivationHeight < 2) { + throw ArgumentError.value( + nu63ActivationHeight, + 'nu63ActivationHeight', + 'must stage NU6.3 above genesis', + ); + } + if (_stateController != null || _preparedSend != null) { + throw StateError('Configure Zcash regtest consensus before sync or send'); + } + _regtestNu63ActivationHeight = nu63ActivationHeight; + } + + @override + FilterOperation? get changeAddressFilterOperation => null; + + @override + FilterOperation get receivingAddressFilterOperation => + FilterGroup.and(standardReceivingAddressFilters); + + @override + Future init({bool? isRestore}) async { + // An exit that is still closing the connection finishes first, so that it + // cannot close what this opens. The wallet views do not wait for the exit + // they start. + try { + await _exiting; + } catch (_) { + // The exit reports its own failure. + } + // Opening a wallet that was closed with [exit] makes it usable again. + _exited = false; + if (info.restoreHeight < 1 && isRestore == true) { + throw StateError( + 'Restoring Zcash requires an explicit positive block height; ' + 'a missing birthday must not skip wallet history', + ); + } + zcash.requireProductionWalletNativeCapabilities(zcash.nativeCapabilities()); + final seed = zcash.nativeMnemonicToSeed( + await getMnemonic(), + passphrase: await getMnemonicPassphrase(), + ); + final derived = await zcash.deriveAddress( + seedHex: seed.seedHex, + network: cryptoCurrency.nativeNetwork, + ); + final metadata = zcash.deriveNativeAccountMetadata( + seedHex: seed.seedHex, + network: cryptoCurrency.nativeNetwork, + ); + final viewingKeys = zcash.deriveNativeViewingKeys( + seedHex: seed.seedHex, + network: cryptoCurrency.nativeNetwork, + ); + _ufvk = metadata.ufvk; + _accountFingerprint = metadata.fingerprint; + _accountMetadata = metadata; + _viewingKeys = viewingKeys; + final transparentDiscovery = ZcashTransparentReceiverDiscovery( + network: cryptoCurrency.nativeNetwork, + viewingKeys: viewingKeys, + ); + _transparentReceiverDiscovery = transparentDiscovery; + final transparentAddress = derived.transparentAddress; + if (metadata.hasTransparent && transparentAddress == null) { + throw StateError('Zcash account has no transparent UA receiver'); + } + if (transparentAddress case final address?) { + final externalViewingKey = viewingKeys.transparent.externalIvk; + if (externalViewingKey == null || externalViewingKey.isEmpty) { + throw StateError('Zcash account has no external transparent IVK'); + } + final derivedAddress = zcash.deriveNativeTransparentAddressFromViewingKey( + viewingKeyHex: externalViewingKey, + network: cryptoCurrency.nativeNetwork, + childIndex: derived.nextValidIndex, + scope: zcash.ZcashTransparentKeyScope.external, + ); + if (derivedAddress != address) { + throw StateError( + 'Zcash UA transparent receiver does not match its viewing key', + ); + } + final defaultAddress = viewingKeys.transparent.defaultExternalAddress; + final receivers = { + for (final receiver in transparentDiscovery.initialReceivers()) + if (receiver.address != defaultAddress) receiver.address: receiver, + }; + if (address != defaultAddress) { + receivers[address] = zcash.ZcashTransparentReceiver( + address: address, + scope: zcash.ZcashTransparentReceiverScope.external, + childIndex: derived.nextValidIndex, + ); + } + _additionalTransparentReceivers = receivers.values.toList(); + } + final existing = await getCurrentReceivingAddress(); + final cached = info.cachedReceivingAddress; + if ((existing != null && existing.value != derived.ua) || + (cached.isNotEmpty && cached != derived.ua)) { + throw StateError('Zcash wallet address does not match the saved wallet'); + } + final receiverRows = _receiverRows(derived); + final persisted = await mainDB.getAddresses(walletId).findAll(); + for (final expected in receiverRows) { + final sameSlot = persisted.where( + (address) => + address.type == expected.type && + address.subType == expected.subType && + address.derivationIndex == expected.derivationIndex, + ); + if (sameSlot.isNotEmpty && + sameSlot.every((address) => address.value != expected.value)) { + throw StateError( + 'Zcash wallet receiver does not match the saved wallet', + ); + } + } + await mainDB.updateOrPutAddresses(receiverRows); + if (info.restoreHeight < 1 && isRestore == false) { + // A new wallet has no history to find, so it scans from the block after + // the current tip. This is the only network use in init: a wallet that + // already has a birthday opens offline and connects on its first sync. + try { + final readiness = await _replaceConfiguredNode(); + if (readiness.tipHeight >= ZcashAccountSession.maximumBlockHeight) { + throw StateError( + 'The Zcash lightwalletd tip cannot produce a bounded wallet ' + 'birthday', + ); + } + await info.updateRestoreHeight( + newRestoreHeight: readiness.tipHeight + 1, + isar: mainDB.isar, + ); + await _initializeStateController(_requireAccountSession()); + } catch (_) { + await _closeAccountSession(); + rethrow; + } + } + await super.init(); + } + + @override + Future checkSaveInitialReceivingAddress() async {} + + @override + Future prepareSend({required TxData txData}) => _sendMutex.protect( + () async { + final recipients = txData.recipients; + if (recipients == null || recipients.isEmpty) { + throw ArgumentError('Zcash requires at least one recipient'); + } + if (recipients.length > 1 && (txData.memo ?? '').isNotEmpty) { + // One memo cannot be assigned to several recipients. + throw ArgumentError('A Zcash memo needs a single recipient'); + } + var total = BigInt.zero; + final resolved = <({String address, BigInt amount, Uint8List? memo})>[]; + for (final requested in recipients) { + if (requested.isChange || + requested.amount.fractionDigits != cryptoCurrency.fractionDigits || + requested.amount.raw <= BigInt.zero || + requested.amount.raw > BigInt.from(zcash.maxMoneyZatoshis)) { + throw ArgumentError('Invalid Zcash recipient amount'); + } + total += requested.amount.raw; + if (total > BigInt.from(zcash.maxMoneyZatoshis)) { + throw ArgumentError('Zcash recipient total exceeds MAX_MONEY'); + } + resolved.add( + _resolveStackPayment( + address: requested.address, + amount: requested.amount.raw, + memo: txData.memo, + ), + ); + } + final snapshot = await (await _synchronizer()).refresh(); + final session = _requireAccountSession(); + final syncClient = session.syncClient; + final stateStore = _stateStore; + final pendingStore = _pendingSendStore; + final scanExecutor = _scanExecutor; + if (syncClient == null || + stateStore == null || + pendingStore == null || + scanExecutor == null) { + throw StateError('Zcash send requires an initialized sync session'); + } + final persisted = await stateStore.load(); + if (persisted == null || + persisted.observedChainHeight != snapshot.chainHeight) { + throw StateError('Zcash sync state is unavailable or not current'); + } + final ironwoodChange = await _ironwoodChangeAddress(); + final seed = zcash.nativeMnemonicToSeed( + await getMnemonic(), + passphrase: await getMnemonicPassphrase(), + ); + await _releaseCurrentPrepared(); + final pending = await pendingStore.load(); + reconcileLeftoverSends(pending, snapshot); + final prepared = await _sendService.prepare( + ZcashSendPreparationRequest( + network: cryptoCurrency.nativeNetwork, + sessionGeneration: session.generation, + state: persisted.syncState, + pendingSends: pending, + syncClient: syncClient, + scanExecutor: scanExecutor, + seedHex: seed.seedHex, + ironwoodChangeAddress: ironwoodChange, + payments: [ + for (final payment in resolved) + ZcashSendPayment( + recipient: payment.address, + amountZatoshis: payment.amount.toInt(), + memo: payment.memo, + ), + ], + targetHeight: snapshot.chainHeight + 1, + expiryHeight: snapshot.chainHeight + 41, + resolveSaplingProvingParameters: _saplingParameterResolver, + regtestNu63ActivationHeight: _regtestNu63ActivationHeight, + ), + ); + // This is the durability boundary: no prepared transaction is exposed + // to review until its selected nullifiers are committed on disk. + await pendingStore.save(pending); + _preparedSend = prepared; + _preparedSession = session; + final outputs = _preparedPaymentOutputs(prepared); + if (outputs.length != recipients.length) { + throw StateError('Prepared Zcash output count changed unexpectedly'); + } + return txData.copyWith( + raw: prepared.transactionHex, + txid: prepared.txid, + fee: _amount(prepared.feeZatoshis), + memo: txData.memo, + recipients: [ + for (var index = 0; index < outputs.length; index++) + recipients[index].copyWith( + address: outputs[index].encodedRecipient, + amount: _amount(outputs[index].amountZatoshis), + ), + ], + vExtraData: _preparedDigest(prepared), + ); + }, + ); + + /// Rebuilds the one send that was prepared, or submitted with an unknown + /// outcome, before the wallet last closed, so it can be confirmed or + /// cancelled. Null when there is none. + Future recoverPreparedSend() => _sendMutex.protect(() async { + if (_preparedSend != null) { + throw StateError('another Zcash transaction is already prepared'); + } + final snapshot = await (await _synchronizer()).refresh(); + final stateStore = _stateStore; + final pendingStore = _pendingSendStore; + final session = _requireAccountSession(); + if (stateStore == null || pendingStore == null) { + throw StateError('Zcash send state is not initialized'); + } + final persisted = await stateStore.load(); + if (persisted == null) return null; + final pending = await pendingStore.load(); + pending.recoverInterruptedSubmissions(); + await pendingStore.save(pending); + final mined = { + for (final entry in snapshot.history.entries) entry.txid.toLowerCase(), + }; + final resumable = pending.records + .where( + (record) => + !mined.contains(record.txid.toLowerCase()) && + !record.isExpiredAt(snapshot.chainHeight) && + (record.broadcastState == + zcash.IronwoodPendingBroadcastState.prepared || + record.broadcastState == + zcash.IronwoodPendingBroadcastState.indeterminate), + ) + .toList(growable: false); + if (resumable.isEmpty) return null; + if (resumable.length != 1) { + throw StateError('multiple Zcash sends need reconciliation'); + } + final record = resumable.single; + final notes = [ + if (record.sourcePool == zcash.ShieldedPendingSourcePool.ironwood) + for (final note in persisted.syncState.ironwood.notes) + if (note.nullifier != null && + record.selectedNullifiers.contains(note.nullifier)) + note, + ]; + if (notes.length != record.selectedNullifiers.length) { + throw StateError( + 'reserved Zcash inputs are missing from canonical wallet state', + ); + } + final artifact = ZcashRecoveredPreparedSend( + record: record, + notes: notes, + sessionGeneration: session.generation, + ); + _preparedSend = artifact; + _preparedSession = session; + final outputs = artifact.paymentOutputs; + return TxData( + raw: artifact.transactionHex, + txid: artifact.txid, + fee: _amount(artifact.feeZatoshis), + memo: outputs.length == 1 ? _memoText(outputs.single.memo) : null, + recipients: [ + for (final output in outputs) + TxRecipient( + address: output.encodedRecipient, + amount: _amount(output.amountZatoshis), + isChange: false, + addressType: + cryptoCurrency.getAddressType(output.encodedRecipient) ?? + AddressType.zcashUnified, + ), + ], + vExtraData: _preparedDigest(artifact), + ); + }); + + @override + Future confirmSend({required TxData txData}) => _sendMutex.protect( + () async { + final prepared = _preparedSend; + if (prepared == null || !_matchesPrepared(txData, prepared)) { + throw StateError( + 'Zcash confirmation must use the exact prepared transaction artifact', + ); + } + final session = _requireAccountSession(); + _requirePreparedSession(prepared, session); + // Revalidate expiry against a freshly synchronized tip. A prepared + // artifact can cross its consensus expiry boundary while the review UI + // is open or while a recovered send is waiting after restart. + final int chainHeight; + try { + chainHeight = (await (await _synchronizer()).refresh()).chainHeight; + } catch (_) { + // A node change stops the sync it interrupts: report the change. + _requirePreparedSession(prepared, session); + rethrow; + } + // updateNode intentionally remains usable during a potentially long scan. + // Recheck after that await, and again in each submit callback, so bytes + // can never cross an endpoint-generation boundary. + _requirePreparedSession(prepared, session); + final store = _pendingSendStore!; + final pending = await store.load(); + try { + await _sendService.broadcast( + prepared: prepared, + pendingSends: pending, + chainHeight: chainHeight, + persist: () => store.save(pending), + submit: (transactionHex) { + _requirePreparedSession(prepared, session); + return session.submitTransactionHex(transactionHex); + }, + ); + } catch (_) { + // A send that can never be submitted again is no longer prepared: + // the node refused it and its notes were released, or it expired + // before it left. One without a known outcome stays, so that + // confirming it again submits the same transaction. + final left = pending.records + .where( + (record) => + record.txid.toLowerCase() == prepared.txid.toLowerCase(), + ) + .firstOrNull; + if (left == null) { + _preparedSend = null; + } else if (left.broadcastState == + zcash.IronwoodPendingBroadcastState.prepared && + left.isExpiredAt(chainHeight)) { + pending.releaseRejected(prepared.txid); + _preparedSend = null; + } + rethrow; + } finally { + await store.save(pending); + } + _preparedSend = null; + return txData; + }, + ); + + @override + Future cancelSend({required TxData txData}) => + _sendMutex.protect(() async { + final prepared = _preparedSend; + if (prepared == null || !_matchesPrepared(txData, prepared)) return; + await _releaseCurrentPrepared(); + }); + + /// Connects to the node and checks the birthday against it, and for a + /// rescan forgets what was scanned. The scan itself is the next refresh, + /// which this starts and does not wait for: from an old birthday it takes + /// a long time, saves its progress as it goes and continues after a + /// restart. + @override + Future recover({required bool isRescan}) async { + await _sendMutex.protect( + () => refreshMutex.protect(() async { + if (isRescan) { + await _synchronizer(); + final store = _stateStore; + if (store == null) { + throw StateError( + 'Zcash rescan requires an initialized sync checkpoint', + ); + } + await _releaseCurrentPrepared(); + + final persisted = await store.load(); + if (persisted != null) { + final defaultAddress = + _viewingKeys?.transparent.defaultExternalAddress; + final retained = { + for (final receiver in _additionalTransparentReceivers) + receiver.address: receiver, + for (final receiver in persisted.syncState.transparent.receivers) + if (receiver.address != defaultAddress) + receiver.address: receiver, + }; + _additionalTransparentReceivers = retained.values.toList(); + } + + // Reset only the encrypted chain checkpoint. Receiver rows, + // wallet identity, and durable reservations survive a rescan. + await store.reset(); + _dropStateController(); + await _initializeStateController(_requireAccountSession()); + } + await _synchronizer(); + }), + ); + unawaited(refresh()); + } + + @override + Future updateNode() async { + if (_exited) return; + try { + final readiness = await _replaceConfiguredNode(); + _validateBirthdayAgainst(readiness); + await _initializeStateController(_requireAccountSession()); + } catch (e, s) { + // Do not keep syncing against the node that was replaced. The next sync + // tries the configured node again and reports what is wrong with it. + await _closeAccountSession(); + unawaited(_releaseOrphanedPrepared()); + Logging.instance.w( + '$runtimeType.updateNode() could not open the configured node', + error: e, + stackTrace: s, + ); + } + } + + /// The sync state, connecting to the configured node the first time it is + /// needed and again after a connection that failed. + Future _synchronizer() { + if (_exited) throw StateError('This Zcash wallet is closed'); + final controller = _stateController; + if (controller != null) return Future.value(controller); + return _openingStateController ??= _openStateController().whenComplete( + () => _openingStateController = null, + ); + } + + Future _openStateController() async { + final readiness = await _replaceConfiguredNode(); + _validateBirthdayAgainst(readiness); + await _initializeStateController(_requireAccountSession()); + if (_exited) { + // The wallet closed while this was connecting. + await _closeAccountSession(); + throw StateError('This Zcash wallet is closed'); + } + return _stateController ?? + (throw StateError('The Zcash node does not support wallet sync')); + } + + @override + Future pingCheck() async { + try { + if (_stateController == null) { + await _synchronizer(); + return true; + } + return await _requireAccountSession().ping(); + } catch (_) { + return false; + } + } + + /// Closes the connection and the sync over it. The wallet's keys and its + /// stores stay, so a later sync can connect again. + /// + /// This runs outside [_sendMutex], so it leaves the send state alone: a + /// send that was prepared over the connection can no longer be confirmed + /// (see [_requirePreparedSession]) and [_releaseOrphanedPrepared] frees + /// its notes. + Future _closeAccountSession() async { + _refreshSnapshot = null; + _dropStateController(); + final session = _accountSession; + _accountSession = null; + await session?.close(); + } + + /// A sync that is still running over the old controller must not save + /// over the state of its replacement, or after its wallet was deleted. + void _dropStateController() { + _scanCancellation?.cancel(); + _scanCancellation = null; + _stateController?.close(); + _stateController = null; + } + + /// Frees the notes of a prepared send whose connection is gone. It waits + /// for [_sendMutex], so that it cannot run into a confirmation. + Future _releaseOrphanedPrepared() => + _sendMutex.protect(_releaseOrphanedPreparedLocked); + + Future _releaseOrphanedPreparedLocked() async { + final prepared = _preparedSend; + if (prepared == null) return; + final session = _accountSession; + if (session != null && + identical(session, _preparedSession) && + session.generation == prepared.sessionGeneration) { + return; + } + try { + await _releaseCurrentPrepared(); + } catch (e, s) { + // The reservation then lasts until the transaction expires. + Logging.instance.w( + '$runtimeType could not release a prepared send', + error: e, + stackTrace: s, + ); + } + _preparedSend = null; + } + + /// Settles what a wallet that closed in the middle of a send left behind. + /// Call under [_sendMutex], after [_preparedSend] was released: then no + /// send of this wallet is prepared or being submitted. A send that was + /// only prepared never left the wallet, so its notes are free. One that + /// was being submitted may have reached the node. + /// + /// Also drops the records of sends that no block of [snapshot] holds and + /// none can hold any more: nothing reads them. The record of a mined send + /// stays, for the fee and the recipients of its history row. + @visibleForTesting + static void reconcileLeftoverSends( + zcash.IronwoodPendingSendState pending, + ZcashWalletSnapshot snapshot, + ) { + final mined = { + for (final entry in snapshot.history.entries) entry.txid.toLowerCase(), + }; + for (final record in pending.records) { + if (record.broadcastState == + zcash.IronwoodPendingBroadcastState.prepared || + (record.isExpiredAt(snapshot.chainHeight) && + !mined.contains(record.txid.toLowerCase()))) { + pending.releaseRejected(record.txid); + } + } + pending.recoverInterruptedSubmissions(); + } + + Future _replaceConfiguredNode() async { + final node = getCurrentNode(); + final session = _accountSession ??= _accountSessionFactory( + cryptoCurrency.nativeNetwork, + ); + final readiness = await session.replaceNode(node); + _dropStateController(); + return readiness; + } + + void _validateBirthdayAgainst(ZcashSessionReadiness readiness) { + final birthdayHeight = info.restoreHeight; + if (birthdayHeight < 1 || + birthdayHeight > ZcashAccountSession.maximumBlockHeight) { + throw StateError( + 'Zcash restore height must be between 1 and ' + '${ZcashAccountSession.maximumBlockHeight}', + ); + } + if (birthdayHeight > readiness.tipHeight + 1) { + throw StateError( + 'Zcash restore height $birthdayHeight is above the validated ' + 'lightwalletd tip ${readiness.tipHeight}', + ); + } + } + + @override + Future updateTransactions() async { + await _storeHistory(_refreshSnapshot ?? await _sync()); + } + + Future _sync() async { + final controller = await _synchronizer(); + return controller.refresh(cancellation: _scanCancellation); + } + + /// Makes the stored transactions those of [snapshot], which holds the whole + /// history since the wallet's birthday. A transaction that a reorg removed, + /// or a send that expired before it was mined, goes with the rest. + Future _storeHistory(ZcashWalletSnapshot snapshot) async { + final stored = { + for (final row + in await mainDB.isar.transactionV2s + .where() + .walletIdEqualTo(walletId) + .findAll()) + row.txid: row, + }; + final pending = await _pendingSendStore?.load(); + final timestamps = zcashHistoryTimestamps( + snapshot: snapshot, + pendingSends: pending, + stored: stored, + now: DateTime.now().millisecondsSinceEpoch ~/ 1000, + ); + final transactions = ZcashStackStateMapper(walletId: walletId).transactions( + snapshot.history, + pendingSends: pending, + timestamps: timestamps, + chainHeight: snapshot.chainHeight, + ); + final current = {}; + for (final transaction in transactions) { + current.add(transaction.txid); + final row = stored[transaction.txid]; + if (row != null) transaction.id = row.id; + } + await mainDB.isar.writeTxn(() async { + await mainDB.isar.transactionV2s.deleteAll([ + for (final row in stored.values) + if (!current.contains(row.txid)) row.id, + ]); + await mainDB.isar.transactionV2s.putAll(transactions); + }); + } + + @override + Future updateBalance() async { + final snapshot = _refreshSnapshot ?? await _sync(); + // The balance is the last update of a refresh. + _refreshSnapshot = null; + await _storeBalance(snapshot); + } + + Future _storeBalance(ZcashWalletSnapshot snapshot) async => + info.updateBalance( + newBalance: ZcashStackStateMapper(walletId: walletId).balance( + snapshot, + pendingSends: await _pendingSendStore?.load(), + ownAddresses: {await _ironwoodChangeAddress()}, + ), + isar: mainDB.isar, + ); + + @override + // Transparent outputs remain in the authenticated Zcash state. Mirroring + // them into Stack's generic UTXO rows would expose coin-control toggles that + // the shielded send planner does not honor, so report no generic UTXO work. + Future updateUTXOs() async => false; + + @override + Future updateChainHeight() async { + _refreshSnapshot = null; + final snapshot = await _sync(); + _refreshSnapshot = snapshot; + await info.updateCachedChainHeight( + newHeight: snapshot.chainHeight, + isar: mainDB.isar, + ); + } + + @override + Future estimateFeeFor(Amount amount, BigInt feeRate) async { + final notes = {...?_stateController?.spendableNotes}; + // A note above the anchor of a send cannot be spent yet. + _stateController?.unanchoredNotes.forEach(notes.remove); + // As in the balance, the notes of a send that is not mined yet are not + // free to spend. + final pending = await _pendingSendStore?.load(); + for (final record + in pending?.records ?? const []) { + if (record.broadcastState != + zcash.IronwoodPendingBroadcastState.prepared && + !record.isExpiredAt(info.cachedChainHeight)) { + record.selectedNullifiers.forEach(notes.remove); + } + } + return _amount(estimateZip317Fee(notes.values, amount.raw)); + } + + /// The ZIP 317 fee of paying [amount] to one shielded recipient from notes + /// of [noteValues], spending the largest first as a send does: 5000 + /// zatoshis for each action, and a payment has as many actions as it + /// spends notes, with a minimum of two. The fee of a prepared send is + /// exact. This is what the send form shows before that. + @visibleForTesting + static int estimateZip317Fee(Iterable noteValues, BigInt amount) { + final values = noteValues.toList()..sort((a, b) => b.compareTo(a)); + var actions = 2; + var value = BigInt.zero; + for (final (index, note) in values.indexed) { + value += BigInt.from(note); + if (index >= 2) actions = index + 1; + if (value >= amount + BigInt.from(5000 * actions)) break; + } + return 5000 * actions; + } + + @override + Future get fees async => FeeObject( + numberOfBlocksFast: 1, + numberOfBlocksAverage: 1, + numberOfBlocksSlow: 1, + fast: BigInt.from(10000), + medium: BigInt.from(10000), + slow: BigInt.from(10000), + ); + + @override + Future exit() => + _exiting ??= _exit().whenComplete(() => _exiting = null); + + Future _exit() async { + // From here no sync opens a connection or writes wallet state, until + // [init] opens the wallet again. + _exited = true; + try { + // A scan stops at its next step, without waiting for the send lock. + _scanCancellation?.cancel(); + // A send that is being submitted finishes first. + await _sendMutex.protect(() async { + await _closeAccountSession(); + await _releaseOrphanedPreparedLocked(); + }); + } finally { + await super.exit(); + } + } + + Future _initializeStateController(ZcashAccountSession session) async { + final client = session.syncClient; + if (client == null) return; + final ufvk = _ufvk; + final fingerprint = _accountFingerprint; + final accountMetadata = _accountMetadata; + final viewingKeys = _viewingKeys; + if (ufvk == null || + fingerprint == null || + accountMetadata == null || + viewingKeys == null) { + throw StateError('Zcash account identity is not initialized'); + } + final birthdayHeight = info.restoreHeight; + if (birthdayHeight < 1) { + throw StateError( + 'Zcash requires a validated positive restore height before syncing', + ); + } + final root = await StackFileSystem.applicationRootDirectory(); + final network = cryptoCurrency.nativeNetwork.ffiLabel; + final source = _ZcashSessionSyncDataSource(client); + final scanExecutor = ZcashNativeIsolateScanExecutor( + ufvk: ufvk, + network: network, + ); + final blockTimes = ZcashBlockTimes(); + final cancellation = ZcashRecoveryCancellationToken(); + final stateStore = ZcashEncryptedWalletStateStore( + path: zcashWalletPersistencePath( + applicationRoot: root, + walletId: walletId, + suffix: zcashWalletStateSuffix, + ), + walletId: walletId, + network: network, + accountFingerprint: fingerprint, + secureStorage: secureStorageInterface, + ); + final pendingStore = ZcashEncryptedPendingSendStore( + path: zcashWalletPersistencePath( + applicationRoot: root, + walletId: walletId, + suffix: zcashPendingSendSuffix, + ), + walletId: walletId, + network: network, + accountFingerprint: fingerprint, + secureStorage: secureStorageInterface, + ); + final controller = await ZcashWalletStateController.open( + store: stateStore, + accountFingerprint: fingerprint, + network: network, + birthdayHeight: birthdayHeight, + loadBirthdayTreeState: source.getTreeState, + scanExecutor: scanExecutor, + openSync: (state, executor) => openZcashSyncSession( + state: state, + source: source, + scanExecutor: executor, + network: network, + checkCancellation: cancellation.throwIfCancelled, + blockTimes: blockTimes, + ), + blockTimes: blockTimes, + accountMetadata: accountMetadata, + viewingKeys: viewingKeys, + additionalTransparentReceivers: _additionalTransparentReceivers, + transparentDiscovery: _transparentReceiverDiscovery, + transparentActivity: client is ZcashLightwalletdTransparentClient + ? (addresses, startHeight, chainHeight) => + (client as ZcashLightwalletdTransparentClient) + .getTransparentAddressActivity( + addresses, + startHeight: startHeight, + chainHeight: chainHeight, + ) + : null, + refreshTransparent: client is ZcashLightwalletdTransparentClient + ? (state) => (client as ZcashLightwalletdTransparentClient) + .getTransparentRefresh( + state, + maxRangeSize: 1000, + maxUtxos: 10000, + ) + : null, + ); + if (!identical(_accountSession, session)) { + // The connection was closed or replaced while the state loaded. + controller.close(); + throw StateError('The Zcash node changed while the wallet was opening'); + } + _dropStateController(); + _stateController = controller; + _scanCancellation = cancellation; + _stateStore = stateStore; + _scanExecutor = scanExecutor; + _pendingSendStore = pendingStore; + } + + Amount _amount(int zatoshis) => Amount( + rawValue: BigInt.from(zatoshis), + fractionDigits: cryptoCurrency.fractionDigits, + ); + + ZcashAccountSession _requireAccountSession() => + _accountSession ?? + (throw StateError('Zcash requires an initialized account session')); + + Future _ironwoodChangeAddress() async { + final rows = await mainDB.getAddresses(walletId).findAll(); + final matches = rows.where((row) => row.type == AddressType.zcashUnified); + if (matches.length != 1) { + throw StateError( + 'Zcash wallet has no unambiguous Unified Address for Ironwood change', + ); + } + return matches.single.value; + } + + void _requirePreparedSession( + ZcashPreparedWalletSend prepared, + ZcashAccountSession session, + ) { + final active = _requireAccountSession(); + if (!identical(active, session) || + !identical(active, _preparedSession) || + active.generation != prepared.sessionGeneration) { + throw StateError( + 'The Zcash node changed after preparation; prepare again', + ); + } + } + + Future _releaseCurrentPrepared() async { + final prepared = _preparedSend; + if (prepared == null) return; + final store = _pendingSendStore; + if (store != null) { + await _releaseUnbroadcastPrepared( + store: store, + pending: await store.load(), + ); + } + } + + Future _releaseUnbroadcastPrepared({ + required ZcashPendingSendStore store, + required zcash.IronwoodPendingSendState pending, + }) async { + final prepared = _preparedSend; + if (prepared == null) return; + final records = pending.records.where( + (record) => record.txid.toLowerCase() == prepared.txid.toLowerCase(), + ); + if (records.length == 1 && + records.single.broadcastState == + zcash.IronwoodPendingBroadcastState.prepared) { + pending.releaseRejected(prepared.txid); + await store.save(pending); + } + _preparedSend = null; + } + + ({String address, BigInt amount, Uint8List? memo}) _resolveStackPayment({ + required String address, + required BigInt amount, + required String? memo, + }) { + final suppliedMemo = memo == null || memo.isEmpty + ? null + : Uint8List.fromList(utf8.encode(memo)); + if (suppliedMemo != null && suppliedMemo.length > 512) { + throw ArgumentError('Zcash memo exceeds 512 bytes'); + } + if (!address.toLowerCase().startsWith('zcash:')) { + return (address: address, amount: amount, memo: suppliedMemo); + } + final request = zcash.parseZcashUri(address); + if (request == null) throw ArgumentError('Invalid ZIP-321 payment request'); + if (request.payments.length != 1) { + throw UnsupportedError( + 'Multi-recipient ZIP-321 requires backend multi-output reservations', + ); + } + final payment = request.payments.single; + if (payment.amountZatoshis != null && payment.amountZatoshis != amount) { + throw ArgumentError( + 'ZIP-321 amount conflicts with the Stack send amount', + ); + } + if (payment.memo != null && + suppliedMemo != null && + !_bytesEqual(payment.memo!, suppliedMemo)) { + throw ArgumentError('ZIP-321 memo conflicts with the Stack send memo'); + } + return ( + address: payment.address, + amount: payment.amountZatoshis ?? amount, + memo: payment.memo ?? suppliedMemo, + ); + } + + /// A memo as text, when it is text. + String? _memoText(Uint8List? memo) { + if (memo == null || memo.isEmpty) return null; + try { + return utf8.decode(memo); + } on FormatException { + return null; + } + } + + List<({String encodedRecipient, int amountZatoshis, Uint8List? memo})> + _preparedPaymentOutputs(ZcashPreparedWalletSend prepared) => + prepared.paymentOutputs; + + Uint8List _preparedDigest(ZcashPreparedWalletSend prepared) { + final outputCommitment = _preparedPaymentOutputs(prepared) + .map( + (output) => + '${output.encodedRecipient}:${output.amountZatoshis}:' + '${output.memo == null ? '' : base64Url.encode(output.memo!)}', + ) + .join('|'); + return Uint8List.fromList( + sha256 + .convert( + utf8.encode( + '${prepared.txid}|${prepared.transactionHex}|' + '$outputCommitment|' + '${prepared.feeZatoshis}', + ), + ) + .bytes, + ); + } + + bool _matchesPrepared(TxData txData, ZcashPreparedWalletSend prepared) { + final recipients = txData.recipients; + final outputs = _preparedPaymentOutputs(prepared); + if (txData.txid != prepared.txid || + txData.raw != prepared.transactionHex || + txData.fee?.raw != BigInt.from(prepared.feeZatoshis) || + recipients == null || + recipients.length != outputs.length || + !_bytesEqual(txData.vExtraData, _preparedDigest(prepared))) { + return false; + } + for (var index = 0; index < outputs.length; index++) { + if (recipients[index].address != outputs[index].encodedRecipient || + recipients[index].amount.raw != + BigInt.from(outputs[index].amountZatoshis)) { + return false; + } + } + return true; + } + + List
_receiverRows(zcash.UnifiedAddressSet derived) { + final values = <(String, AddressType)>[ + (derived.ua, AddressType.zcashUnified), + if (derived.saplingAddress case final address?) + (address, AddressType.zcashSapling), + if (derived.transparentAddress case final address?) + ( + address, + cryptoCurrency.getAddressType(address) ?? + (throw StateError( + 'Derived Zcash transparent receiver has no address type', + )), + ), + ]; + return [ + for (final (value, type) in values) + Address( + walletId: walletId, + value: value, + publicKey: const [], + derivationIndex: 0, + derivationPath: null, + type: type, + subType: AddressSubType.receiving, + ), + ]; + } +} + +class _ZcashSessionSyncDataSource implements ZcashSyncDataSource { + const _ZcashSessionSyncDataSource(this.client); + + final ZcashLightwalletdSyncClient client; + + @override + Future getBlockHash(int height) => client.getBlockHash(height); + + @override + Future getBlockRange(int start, int end) => + client.getBlockRange(start, end); + + @override + Future getTipHeight() => client.getTipHeight(); + + @override + Future getTreeState(int height) => + client.getTreeState(height); +} + +bool _bytesEqual(List? left, List? right) { + if (identical(left, right)) return true; + if (left == null || right == null || left.length != right.length) { + return false; + } + for (var i = 0; i < left.length; i++) { + if (left[i] != right[i]) return false; + } + return true; +} diff --git a/lib/wallets/wallet/intermediate/zcash_account_session.dart b/lib/wallets/wallet/intermediate/zcash_account_session.dart new file mode 100644 index 000000000..f796f4789 --- /dev/null +++ b/lib/wallets/wallet/intermediate/zcash_account_session.dart @@ -0,0 +1,713 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:fixnum/fixnum.dart'; +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +import '../../../models/node_model.dart'; + +typedef ZcashLightwalletdClientFactory = ZcashLightwalletdClient Function( + ZcashEndpoint endpoint, +); + +abstract interface class ZcashLightwalletdClient { + Future getInfo(); + + Future getTipHeight(); + + Future close(); +} + +abstract interface class ZcashLightwalletdSyncClient + implements ZcashLightwalletdClient { + Future getBlockRange(int start, int end); + + Future getTreeState(int height); + + Future getBlockHash(int height); +} + +abstract interface class ZcashLightwalletdTransparentClient { + Future getTransparentAddressActivity( + List addresses, { + required int startHeight, + required int chainHeight, + }); + + Future getTransparentRefresh( + zcash.ZcashTransparentState state, { + int maxRangeSize = 1000, + int maxUtxos = 10000, + }); +} + +class ZcashAuthenticatedTransparentTransaction { + const ZcashAuthenticatedTransparentTransaction({ + required this.summary, + required this.height, + required this.blockHash, + required this.blockTime, + }); + + final zcash.ZcashTransactionSummary summary; + final int height; + final String blockHash; + final int? blockTime; +} + +class ZcashTransparentActivityResult { + ZcashTransparentActivityResult({ + required Set activeAddresses, + Iterable transactions = const [], + }) : activeAddresses = Set.unmodifiable(activeAddresses), + transactions = List.unmodifiable(transactions); + + final Set activeAddresses; + final List transactions; + + static final empty = ZcashTransparentActivityResult( + activeAddresses: const {}, + ); +} + +class ZcashDecodedTransparentTransactionCandidate { + const ZcashDecodedTransparentTransactionCandidate({ + required this.summary, + required this.computedTxid, + required this.height, + required this.rawTransactionHex, + }); + + final zcash.ZcashTransactionSummary summary; + final String computedTxid; + final int height; + final String rawTransactionHex; +} + +String normalizeZcashTransactionId(String value) { + if (!RegExp(r'^[0-9a-fA-F]{64}$').hasMatch(value)) { + throw const FormatException( + 'Zcash transaction ids must be exactly 64 hexadecimal characters', + ); + } + return value.toLowerCase(); +} + +ZcashDecodedTransparentTransactionCandidate _normalizeCandidate( + ZcashDecodedTransparentTransactionCandidate candidate, +) { + final decoded = normalizeZcashTransactionId(candidate.summary.txid); + final computed = normalizeZcashTransactionId(candidate.computedTxid); + if (decoded != computed) { + throw StateError( + 'decoded transparent transaction id does not match its raw bytes', + ); + } + final json = candidate.summary.toJson()..['txid'] = decoded; + return ZcashDecodedTransparentTransactionCandidate( + summary: zcash.ZcashTransactionSummary.fromJson(json), + computedTxid: computed, + height: candidate.height, + rawTransactionHex: candidate.rawTransactionHex.toLowerCase(), + ); +} + +Future collectZcashTransparentTransactionStream({ + required Stream stream, + required Map into, + int maxTransactions = 10000, +}) async { + var active = false; + await for (final value in stream) { + active = true; + final candidate = _normalizeCandidate(value); + final txid = candidate.computedTxid; + final existing = into[txid]; + if (existing != null && + (existing.height != candidate.height || + existing.rawTransactionHex != candidate.rawTransactionHex)) { + throw StateError( + 'lightwalletd returned conflicting transparent transaction data', + ); + } + if (existing == null && into.length >= maxTransactions) { + throw StateError( + 'transparent history exceeds the bounded ' + '$maxTransactions-transaction limit', + ); + } + into[txid] = candidate; + } + return active; +} + +Future> +authenticateZcashTransparentTransactions({ + required Iterable candidates, + required int startHeight, + required int chainHeight, + required Future Function(int height) loadBlock, + int maxTransactions = 10000, +}) async { + final unique = {}; + for (final value in candidates) { + final candidate = _normalizeCandidate(value); + if (candidate.height < startHeight || candidate.height > chainHeight) { + throw StateError( + 'transparent transaction height is outside the requested range', + ); + } + final existing = unique[candidate.computedTxid]; + if (existing != null && + (existing.height != candidate.height || + existing.rawTransactionHex != candidate.rawTransactionHex)) { + throw StateError( + 'one transparent transaction was returned with conflicting data', + ); + } + unique[candidate.computedTxid] = candidate; + if (unique.length > maxTransactions) { + throw StateError( + 'transparent history exceeds the bounded ' + '$maxTransactions-transaction limit', + ); + } + } + + final blocks = {}; + for (final height in unique.values.map((value) => value.height).toSet()) { + final block = await loadBlock(height); + if (block.height.toInt() != height || block.hash.length != 32) { + throw StateError( + 'lightwalletd returned an invalid block for transparent history', + ); + } + blocks[height] = block; + } + final authenticated = []; + for (final candidate in unique.values) { + final block = blocks[candidate.height]!; + final protocolTxid = zcash.reverseTxidByteOrder(candidate.computedTxid); + if (!block.vtx.any( + (transaction) => _hex(transaction.txid) == protocolTxid, + )) { + throw StateError( + 'transparent transaction is absent from its claimed canonical block', + ); + } + authenticated.add( + ZcashAuthenticatedTransparentTransaction( + summary: candidate.summary, + height: candidate.height, + blockHash: _hex(block.hash), + blockTime: block.hasTime() && block.time > 0 ? block.time : null, + ), + ); + } + return authenticated; +} + +abstract interface class ZcashLightwalletdSendClient { + Future submitTransaction( + Uint8List transaction, + ); +} + +class ZcashSubmissionAcknowledgement { + const ZcashSubmissionAcknowledgement({ + required this.errorCode, + required this.errorMessage, + }); + + final int errorCode; + final String errorMessage; + + bool get accepted => errorCode == 0; +} + +class ZcashBroadcastRejectedException implements Exception { + const ZcashBroadcastRejectedException({ + required this.errorCode, + required this.message, + }); + + final int errorCode; + final String message; + + @override + String toString() => 'ZcashBroadcastRejectedException($errorCode): $message'; +} + +class ZcashEndpoint { + const ZcashEndpoint({ + required this.host, + required this.port, + required this.useTls, + required this.network, + }); + + factory ZcashEndpoint.fromNode(NodeModel node, zcash.ZcashNetwork network) { + final value = node.host.trim(); + if (value.isEmpty) { + throw ArgumentError('Zcash node host must not be empty'); + } + if (node.port < 1 || node.port > 65535) { + throw ArgumentError('Zcash node port must be between 1 and 65535'); + } + + final hasScheme = value.contains('://'); + final uri = Uri.tryParse( + hasScheme ? value : '${node.useSSL ? 'https' : 'http'}://$value', + ); + if (uri == null || + uri.host.isEmpty || + uri.userInfo.isNotEmpty || + uri.path.isNotEmpty || + uri.hasQuery || + uri.hasFragment) { + throw ArgumentError('Invalid Zcash node host'); + } + if (uri.scheme != 'http' && uri.scheme != 'https') { + throw ArgumentError('Zcash nodes require an HTTP or HTTPS endpoint'); + } + if ((uri.scheme == 'https') != node.useSSL) { + throw ArgumentError('Zcash node scheme conflicts with its TLS setting'); + } + if (uri.hasPort && uri.port != node.port) { + throw ArgumentError('Zcash node URI port conflicts with its node port'); + } + + return ZcashEndpoint( + host: uri.host, + port: node.port, + useTls: node.useSSL, + network: network, + ); + } + + final String host; + final int port; + final bool useTls; + final zcash.ZcashNetwork network; + + @override + bool operator ==(Object other) => + other is ZcashEndpoint && + other.host == host && + other.port == port && + other.useTls == useTls && + other.network == network; + + @override + int get hashCode => Object.hash(host, port, useTls, network); +} + +class ZcashSessionReadiness { + const ZcashSessionReadiness({required this.info, required this.tipHeight}); + + final zcash.LightdInfo info; + final int tipHeight; +} + +class ZcashNetworkMismatchException implements Exception { + const ZcashNetworkMismatchException({ + required this.expected, + required this.actual, + }); + + final String expected; + final String actual; + + @override + String toString() => + 'ZcashNetworkMismatchException: expected $expected, got $actual'; +} + +class ZcashReadinessTimeoutException implements Exception { + const ZcashReadinessTimeoutException({ + required this.phase, + required this.timeout, + }); + + final String phase; + final Duration timeout; + + @override + String toString() => + 'ZcashReadinessTimeoutException: $phase exceeded $timeout'; +} + +class ZcashAccountSession { + static const int maximumBlockHeight = 0xffffffff; + + ZcashAccountSession({ + required this.network, + ZcashLightwalletdClientFactory? clientFactory, + this.requestTimeout = const Duration(seconds: 5), + this.broadcastTimeout = const Duration(seconds: 30), + }) : _clientFactory = clientFactory ?? _productionClient; + + final zcash.ZcashNetwork network; + final Duration requestTimeout; + + /// How long to wait for a node to answer a submitted transaction. A node + /// validates the transaction before it answers, and a wait that ends early + /// leaves the wallet not knowing whether the transaction was accepted. + final Duration broadcastTimeout; + final ZcashLightwalletdClientFactory _clientFactory; + + ZcashLightwalletdClient? _client; + int _generation = 0; + int _replacementRequest = 0; + bool _closed = false; + + /// Changes whenever the active endpoint changes or closes, invalidating work + /// prepared against an earlier account session. + int get generation => _generation; + + ZcashLightwalletdSyncClient? get syncClient { + final client = _client; + return client is ZcashLightwalletdSyncClient ? client : null; + } + + Future replaceNode(NodeModel node) async { + if (_closed) { + throw StateError('The Zcash account session is closed'); + } + final replacementRequest = ++_replacementRequest; + final replacement = _clientFactory(ZcashEndpoint.fromNode(node, network)); + late final ZcashSessionReadiness readiness; + try { + readiness = await _readiness(replacement); + } catch (_) { + await _closeClient(replacement); + rethrow; + } + if (_closed || replacementRequest != _replacementRequest) { + await _closeClient(replacement); + throw StateError('The Zcash account session replacement was superseded'); + } + + final previous = _client; + _client = replacement; + _generation++; + await _closeClient(previous); + return readiness; + } + + Future ping() async { + if (_closed) return false; + final client = _client; + if (client == null) return false; + try { + await _readiness(client); + return true; + } catch (_) { + return false; + } + } + + Future submitTransactionHex( + String transactionHex, + ) async { + if (_closed) throw StateError('The Zcash account session is closed'); + final client = _client; + if (client is! ZcashLightwalletdSendClient) { + throw StateError('The active Zcash session cannot submit transactions'); + } + final submitter = client as ZcashLightwalletdSendClient; + final bytes = _decodeTransactionHex(transactionHex); + late final ZcashSubmissionAcknowledgement acknowledgement; + try { + acknowledgement = await submitter + .submitTransaction(bytes) + .timeout(broadcastTimeout); + } on TimeoutException { + throw ZcashReadinessTimeoutException( + phase: 'sendTransaction', + timeout: broadcastTimeout, + ); + } + if (!acknowledgement.accepted) { + throw ZcashBroadcastRejectedException( + errorCode: acknowledgement.errorCode, + message: acknowledgement.errorMessage, + ); + } + return acknowledgement; + } + + Future _readiness( + ZcashLightwalletdClient client, + ) async { + late final zcash.LightdInfo info; + try { + info = await client.getInfo().timeout(requestTimeout); + } on TimeoutException { + throw ZcashReadinessTimeoutException( + phase: 'getLightdInfo', + timeout: requestTimeout, + ); + } + final expectedChainName = switch (network) { + zcash.ZcashNetwork.mainnet => 'main', + // Lightwalletd's protocol exposes only `main` and `test`. Regtest uses + // the `test` identity, so chainName alone cannot distinguish those two. + zcash.ZcashNetwork.testnet || zcash.ZcashNetwork.regtest => 'test', + }; + if (info.chainName != expectedChainName) { + throw ZcashNetworkMismatchException( + expected: expectedChainName, + actual: info.chainName, + ); + } + late final int tipHeight; + try { + tipHeight = await client.getTipHeight().timeout(requestTimeout); + } on TimeoutException { + throw ZcashReadinessTimeoutException( + phase: 'getTipHeight', + timeout: requestTimeout, + ); + } + if (tipHeight < 0 || tipHeight > maximumBlockHeight) { + throw StateError( + 'Zcash lightwalletd tip must be between 0 and $maximumBlockHeight', + ); + } + return ZcashSessionReadiness(info: info, tipHeight: tipHeight); + } + + Future close() async { + if (_closed) return; + _closed = true; + _replacementRequest++; + final client = _client; + _client = null; + if (client != null) _generation++; + await _closeClient(client); + } + + Future _closeClient(ZcashLightwalletdClient? client) async { + if (client == null) return; + try { + await client.close().timeout(requestTimeout); + } catch (_) { + // Closing is best effort after the active reference has been removed. + } + } + + static ZcashLightwalletdClient _productionClient(ZcashEndpoint endpoint) => + _ProductionZcashLightwalletdClient( + zcash.LightwalletdClient( + host: endpoint.host, + port: endpoint.port, + useTls: endpoint.useTls, + ), + endpoint.network, + ); +} + +class _ProductionZcashLightwalletdClient + implements + ZcashLightwalletdSyncClient, + ZcashLightwalletdTransparentClient, + ZcashLightwalletdSendClient { + _ProductionZcashLightwalletdClient(this._client, this.endpointNetwork); + + final zcash.LightwalletdClient _client; + final zcash.ZcashNetwork endpointNetwork; + + @override + Future getTransparentAddressActivity( + List addresses, { + required int startHeight, + required int chainHeight, + }) async { + if (startHeight < 1 || chainHeight < startHeight) { + throw ArgumentError( + 'transparent activity range must be positive and ordered', + ); + } + if (addresses.isEmpty || addresses.any((address) => address.isEmpty)) { + throw ArgumentError.value( + addresses, + 'addresses', + 'must contain non-empty transparent addresses', + ); + } + final active = {}; + final rawByTxid = {}; + // Each address is intentionally queried separately because lightwalletd's + // transaction-history filter has a single-address contract. This reveals + // the registered window's common ownership to the configured endpoint; + // cap discovery and limit concurrency to gap-sized batches. The resulting + // transactions are authenticated against their claimed + // canonical blocks below before they can enter restored wallet state. + for (var start = 0; start < addresses.length; start += 20) { + final end = start + 20 < addresses.length ? start + 20 : addresses.length; + final batch = addresses.sublist(start, end); + final results = await Future.wait([ + for (final address in batch) + collectZcashTransparentTransactionStream( + stream: _transparentTransactions( + address, + startHeight: startHeight, + chainHeight: chainHeight, + ), + into: rawByTxid, + ), + ]); + for (var i = 0; i < batch.length; i++) { + if (results[i]) active.add(batch[i]); + } + } + final authenticated = await authenticateZcashTransparentTransactions( + candidates: rawByTxid.values, + startHeight: startHeight, + chainHeight: chainHeight, + loadBlock: (height) => _client + .getBlockRangeByHeight( + height, + height, + poolTypes: const [zcash.PoolType.TRANSPARENT], + ) + .single, + ); + return ZcashTransparentActivityResult( + activeAddresses: active, + transactions: authenticated, + ); + } + + Stream _transparentTransactions( + String address, { + required int startHeight, + required int chainHeight, + }) async* { + final stream = _client.getTaddressTxids( + zcash.TransparentAddressBlockFilter( + address: address, + range: zcash.BlockRange( + start: zcash.BlockID(height: Int64(startHeight)), + end: zcash.BlockID(height: Int64(chainHeight)), + ), + ), + ); + await for (final raw in stream.timeout(_answerTimeout)) { + final height = raw.height.toInt(); + if (height < startHeight || height > chainHeight) { + throw StateError( + 'transparent transaction height is outside the requested range', + ); + } + if (raw.data.isEmpty || raw.data.length > 2000000) { + throw StateError('transparent transaction has an invalid byte length'); + } + final txHex = _hex(raw.data); + yield ZcashDecodedTransparentTransactionCandidate( + summary: zcash.decodeNativeTransaction( + txHex: txHex, + network: endpointNetwork, + ), + computedTxid: zcash.transactionTxid(txHex: txHex).txid, + height: height, + rawTransactionHex: txHex, + ); + } + } + + @override + Future getInfo() => _client.getInfo(); + + @override + Future getTipHeight() => _client.getTipHeight(); + + /// The most blocks asked for in one request. Each request has the client's + /// deadline, which a long range would not meet. + static const _blocksPerRequest = 1000; + + @override + Future getBlockRange( + int start, + int end, + ) async { + final blocks = []; + for (var from = start; from <= end; from += _blocksPerRequest) { + final to = from + _blocksPerRequest - 1; + blocks.addAll( + await _client.getBlockRangeByHeight(from, to < end ? to : end).toList(), + ); + } + return zcash.ZcashLightwalletdScanSource(blocks); + } + + /// The wait for an answer to a request the client sets no deadline on. A + /// connection that stalls would otherwise hold a refresh for good. + static const _answerTimeout = Duration(seconds: 30); + + @override + Future getTreeState(int height) async => + zcash.treeStateFromLightwalletd( + await _client.getTreeStateAtHeight(height).timeout(_answerTimeout), + ); + + @override + Future getBlockHash(int height) async { + try { + return (await getBlockRange(height, height)).lastBlockHash; + } on Object { + // The server answers with an error for a height it has no block at, and + // null says so. A request that failed for another reason must not read + // as that: the sync would take it for a reorganization. + if (height <= await _client.getTipHeight()) rethrow; + return null; + } + } + + @override + Future getTransparentRefresh( + zcash.ZcashTransparentState state, { + int maxRangeSize = 1000, + int maxUtxos = 10000, + }) => zcash.fetchTransparentRefreshFromLightwalletd( + state: state, + client: _client, + maxRangeSize: maxRangeSize, + maxUtxos: maxUtxos, + ); + + @override + Future submitTransaction( + Uint8List transaction, + ) async { + final response = await _client.sendTransaction(transaction); + return ZcashSubmissionAcknowledgement( + errorCode: response.errorCode, + errorMessage: response.errorMessage, + ); + } + + @override + Future close() => _client.close(); +} + +String _hex(List bytes) => + [for (final byte in bytes) byte.toRadixString(16).padLeft(2, '0')].join(); + +Uint8List _decodeTransactionHex(String value) { + if (value.isEmpty || value.length.isOdd) { + throw const FormatException( + 'A Zcash transaction must be nonempty, even-length hexadecimal', + ); + } + final bytes = Uint8List(value.length ~/ 2); + for (var i = 0; i < bytes.length; i++) { + final byte = int.tryParse(value.substring(i * 2, i * 2 + 2), radix: 16); + if (byte == null) { + throw const FormatException('A Zcash transaction must be hexadecimal'); + } + bytes[i] = byte; + } + return bytes; +} diff --git a/lib/wallets/wallet/intermediate/zcash_pending_send_store.dart b/lib/wallets/wallet/intermediate/zcash_pending_send_store.dart new file mode 100644 index 000000000..020904d8b --- /dev/null +++ b/lib/wallets/wallet/intermediate/zcash_pending_send_store.dart @@ -0,0 +1,161 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:cryptography/cryptography.dart'; +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +import '../../../utilities/flutter_secure_storage_interface.dart'; +import 'zcash_wallet_state.dart'; +import 'zcash_wallet_persistence.dart'; + +abstract interface class ZcashPendingSendStore { + Future load(); + + Future save(zcash.IronwoodPendingSendState state); +} + +/// An account-bound store kept separate from the sync checkpoint. +/// +/// Sync checkpoints and send reservations have different commit points. A +/// separate authenticated file prevents a later sync save from erasing a +/// reservation that was durably recorded immediately before broadcast. +final class ZcashEncryptedPendingSendStore implements ZcashPendingSendStore { + ZcashEncryptedPendingSendStore({ + required this.path, + required this.walletId, + required this.network, + required this.accountFingerprint, + required this.secureStorage, + }); + + static const _envelopeVersion = 1; + static const _payloadVersion = 1; + static final _cipher = AesGcm.with256bits(); + + final String path; + final String walletId; + final String network; + final String accountFingerprint; + final SecureStorageInterface secureStorage; + + String get _keyName => zcashPendingSendKey(walletId); + + List get _aad => utf8.encode( + 'stack-wallet-zcash-pending|$_envelopeVersion|$walletId|$network|' + '$accountFingerprint', + ); + + @override + Future load() => + withZcashFileLock(path, _load); + + @override + Future save(zcash.IronwoodPendingSendState state) => + withZcashFileLock(path, () => _save(state)); + + Future _load() async { + await _refuseSymlink(path); + await _removeInterruptedWrite(); + final file = File(path); + if (!await file.exists()) return zcash.IronwoodPendingSendState(); + final encodedKey = await secureStorage.read(key: _keyName); + if (encodedKey == null) { + throw const ZcashStatePersistenceException( + 'encrypted pending-send state exists but its key is missing', + ); + } + try { + final envelope = (jsonDecode(await file.readAsString()) as Map) + .cast(); + if (envelope['version'] != _envelopeVersion) { + throw const ZcashStatePersistenceException( + 'unsupported encrypted pending-send envelope version', + ); + } + final clear = await _cipher.decrypt( + SecretBox( + base64Decode(envelope['ciphertext'] as String), + nonce: base64Decode(envelope['nonce'] as String), + mac: Mac(base64Decode(envelope['mac'] as String)), + ), + secretKey: SecretKey(base64Decode(encodedKey)), + aad: _aad, + ); + final payload = (jsonDecode(utf8.decode(clear)) as Map) + .cast(); + if (payload['version'] != _payloadVersion || + payload['network'] != network || + payload['account_fingerprint'] != accountFingerprint || + payload['pending'] is! Map) { + throw const ZcashStatePersistenceException( + 'pending-send payload belongs to another wallet or is malformed', + ); + } + return zcash.IronwoodPendingSendState.fromJson( + (payload['pending'] as Map).cast(), + ); + } on ZcashStatePersistenceException { + rethrow; + } on Object { + // The cause is left out: a decoding error quotes what it decoded. + throw const ZcashStatePersistenceException( + 'pending-send state failed authentication or is corrupt', + ); + } + } + + Future _save(zcash.IronwoodPendingSendState state) async { + await _refuseSymlink(path); + await _refuseSymlink('$path.tmp'); + var encodedKey = await secureStorage.read(key: _keyName); + if (encodedKey == null) { + encodedKey = base64Encode( + await (await _cipher.newSecretKey()).extractBytes(), + ); + await secureStorage.write(key: _keyName, value: encodedKey); + } + final clear = utf8.encode( + jsonEncode({ + 'version': _payloadVersion, + 'network': network, + 'account_fingerprint': accountFingerprint, + 'pending': state.toJson(), + }), + ); + final box = await _cipher.encrypt( + clear, + secretKey: SecretKey(base64Decode(encodedKey)), + nonce: _cipher.newNonce(), + aad: _aad, + ); + final envelope = jsonEncode({ + 'version': _envelopeVersion, + 'nonce': base64Encode(box.nonce), + 'ciphertext': base64Encode(box.cipherText), + 'mac': base64Encode(box.mac.bytes), + }); + final temporary = File('$path.tmp'); + await temporary.parent.create(recursive: true); + try { + await temporary.writeAsString(envelope, flush: true); + await temporary.rename(path); + } finally { + if (await temporary.exists()) await temporary.delete(); + } + } + + Future _removeInterruptedWrite() async { + await _refuseSymlink('$path.tmp'); + final temporary = File('$path.tmp'); + if (await temporary.exists()) await temporary.delete(); + } + + Future _refuseSymlink(String candidate) async { + if (await FileSystemEntity.type(candidate, followLinks: false) == + FileSystemEntityType.link) { + throw const ZcashStatePersistenceException( + 'refusing to access pending-send state through a symbolic link', + ); + } + } +} diff --git a/lib/wallets/wallet/intermediate/zcash_send.dart b/lib/wallets/wallet/intermediate/zcash_send.dart new file mode 100644 index 000000000..71a16c10d --- /dev/null +++ b/lib/wallets/wallet/intermediate/zcash_send.dart @@ -0,0 +1,650 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +import 'zcash_account_session.dart'; +import 'zcash_wallet_state_controller.dart'; + +typedef ZcashPreparedPaymentOutput = ({ + String encodedRecipient, + int amountZatoshis, + Uint8List? memo, +}); + +abstract class ZcashPreparedWalletSend { + const ZcashPreparedWalletSend({ + required this.sessionGeneration, + required this.encodedRecipient, + required this.selectedReceiver, + required this.selectedReceiverAddress, + required this.actualOutputPool, + required this.memo, + }); + + final int sessionGeneration; + final String encodedRecipient; + final zcash.ZcashAddressReceiverType selectedReceiver; + final String selectedReceiverAddress; + final zcash.ProposalOutputPool actualOutputPool; + final Uint8List? memo; + + String get transactionHex; + String get txid; + int get amountZatoshis; + int get feeZatoshis; + int get inputZatoshis; + int get changeZatoshis; + int get expiryHeight; + + List get selectedNotes; + + List get paymentOutputs => [ + ( + encodedRecipient: encodedRecipient, + amountZatoshis: amountZatoshis, + memo: memo, + ), + ]; + + void requireValueConservation() { + if (inputZatoshis != amountZatoshis + feeZatoshis + changeZatoshis) { + throw StateError( + 'Prepared Zcash transaction does not conserve value: ' + '$inputZatoshis != $amountZatoshis + $feeZatoshis + $changeZatoshis', + ); + } + } +} + +final class ZcashPreparedIronwoodSend extends ZcashPreparedWalletSend { + ZcashPreparedIronwoodSend({ + required this.prepared, + required super.sessionGeneration, + required super.encodedRecipient, + required super.selectedReceiver, + required super.selectedReceiverAddress, + required super.actualOutputPool, + required super.memo, + }) { + requireValueConservation(); + } + + final zcash.IronwoodPreparedPayment prepared; + + @override + String get transactionHex => prepared.transactionHex; + @override + String get txid => prepared.txid; + @override + int get amountZatoshis => prepared.plan.amountZatoshis; + @override + int get feeZatoshis => prepared.plan.feeZatoshis; + @override + int get inputZatoshis => prepared.plan.inputZatoshis; + @override + int get changeZatoshis => prepared.plan.changeZatoshis; + @override + int get expiryHeight => prepared.expiryHeight; + @override + List get selectedNotes => + List.unmodifiable(prepared.plan.notes); +} + +final class ZcashPreparedIronwoodBatch extends ZcashPreparedWalletSend { + ZcashPreparedIronwoodBatch({ + required this.prepared, + required super.sessionGeneration, + }) : outputs = List.unmodifiable(prepared.plan.outputs), + super( + encodedRecipient: prepared.plan.outputs.first.encodedAddress, + selectedReceiver: prepared.plan.outputs.first.selectedReceiver, + selectedReceiverAddress: prepared.plan.outputs.first.receiverAddress, + actualOutputPool: prepared.plan.outputs.first.actualOutputPool, + memo: prepared.plan.outputs.first.memo, + ) { + requireValueConservation(); + } + + final zcash.IronwoodPreparedPayments prepared; + final List outputs; + + @override + List get paymentOutputs => [ + for (final output in outputs) + ( + encodedRecipient: output.encodedAddress, + amountZatoshis: output.amountZatoshis, + memo: output.memo, + ), + ]; + + @override + String get transactionHex => prepared.transactionHex; + @override + String get txid => prepared.txid; + @override + int get amountZatoshis => prepared.plan.amountZatoshis; + @override + int get feeZatoshis => prepared.plan.feeZatoshis; + @override + int get inputZatoshis => prepared.plan.inputZatoshis; + @override + int get changeZatoshis => prepared.plan.changeZatoshis; + @override + int get expiryHeight => prepared.expiryHeight; + @override + List get selectedNotes => + List.unmodifiable(prepared.plan.notes); +} + +final class ZcashRecoveredPreparedSend extends ZcashPreparedWalletSend { + ZcashRecoveredPreparedSend({ + required this.record, + required List notes, + required super.sessionGeneration, + }) : _notes = List.unmodifiable(notes), + _outputs = List.unmodifiable([ + for (final output in record.paymentOutputs) + ( + encodedRecipient: output.encodedRecipient, + amountZatoshis: output.amountZatoshis, + memo: output.memoHex == null + ? null + : Uint8List.fromList([ + for (var i = 0; i < output.memoHex!.length; i += 2) + int.parse( + output.memoHex!.substring(i, i + 2), + radix: 16, + ), + ]), + ), + ]), + super( + encodedRecipient: record.paymentOutputs.first.encodedRecipient, + selectedReceiver: _receiverType( + record.paymentOutputs.first.actualDestinationPool, + ), + selectedReceiverAddress: record.paymentOutputs.first.receiverAddress, + actualOutputPool: _proposalPool( + record.paymentOutputs.first.actualDestinationPool, + ), + memo: record.paymentOutputs.first.memoHex == null + ? null + : Uint8List.fromList([ + for ( + var i = 0; + i < record.paymentOutputs.first.memoHex!.length; + i += 2 + ) + int.parse( + record.paymentOutputs.first.memoHex!.substring(i, i + 2), + radix: 16, + ), + ]), + ) { + // The change is not recorded: it is what the notes leave. + if (changeZatoshis < 0) { + throw StateError( + 'The notes of the recovered Zcash send do not cover its ' + '$amountZatoshis payment and $feeZatoshis fee', + ); + } + } + + final zcash.IronwoodPendingSendRecord record; + final List _notes; + final List _outputs; + + @override + List get paymentOutputs => _outputs; + @override + String get transactionHex => record.transactionHex; + @override + String get txid => record.txid; + @override + int get amountZatoshis => record.amountZatoshis; + @override + int get feeZatoshis => record.feeZatoshis; + @override + int get inputZatoshis => _notes.fold(0, (sum, note) => sum + note.value); + @override + int get changeZatoshis => inputZatoshis - amountZatoshis - feeZatoshis; + @override + int get expiryHeight => record.expiryHeight; + @override + List get selectedNotes => _notes; +} + +zcash.ZcashAddressReceiverType _receiverType( + zcash.IronwoodDestinationPool pool, +) => switch (pool) { + zcash.IronwoodDestinationPool.transparent => + zcash.ZcashAddressReceiverType.p2pkh, + zcash.IronwoodDestinationPool.sapling => + zcash.ZcashAddressReceiverType.sapling, + zcash.IronwoodDestinationPool.orchard => + zcash.ZcashAddressReceiverType.orchard, + zcash.IronwoodDestinationPool.ironwood => + zcash.ZcashAddressReceiverType.unified, +}; + +zcash.ProposalOutputPool _proposalPool(zcash.IronwoodDestinationPool pool) => + switch (pool) { + zcash.IronwoodDestinationPool.transparent => + zcash.ProposalOutputPool.transparent, + zcash.IronwoodDestinationPool.sapling => zcash.ProposalOutputPool.sapling, + zcash.IronwoodDestinationPool.orchard => zcash.ProposalOutputPool.orchard, + zcash.IronwoodDestinationPool.ironwood => + zcash.ProposalOutputPool.ironwood, + }; + +class ZcashSendPayment { + const ZcashSendPayment({ + required this.recipient, + required this.amountZatoshis, + this.memo, + }); + + final String recipient; + final int amountZatoshis; + final Uint8List? memo; +} + +class ZcashSendPreparationRequest { + const ZcashSendPreparationRequest({ + required this.network, + required this.sessionGeneration, + required this.state, + required this.pendingSends, + required this.syncClient, + required this.scanExecutor, + required this.seedHex, + required this.ironwoodChangeAddress, + required this.payments, + required this.targetHeight, + required this.expiryHeight, + required this.resolveSaplingProvingParameters, + this.regtestNu63ActivationHeight, + }); + + final zcash.ZcashNetwork network; + final int sessionGeneration; + final zcash.ZcashWalletSyncState state; + final zcash.IronwoodPendingSendState pendingSends; + final ZcashLightwalletdSyncClient syncClient; + final ZcashScanExecutor scanExecutor; + final String seedHex; + final String ironwoodChangeAddress; + final List payments; + final int targetHeight; + final int expiryHeight; + final Future Function() + resolveSaplingProvingParameters; + final int? regtestNu63ActivationHeight; +} + +abstract interface class ZcashIronwoodSpendMaterialProvider { + /// The witnesses of [candidates] at [anchorHeight]. + Future acquire({ + required ZcashSendPreparationRequest request, + required List candidates, + required int anchorHeight, + }); +} + +final class ZcashNativeIronwoodSpendMaterialProvider + implements ZcashIronwoodSpendMaterialProvider { + const ZcashNativeIronwoodSpendMaterialProvider(); + + @override + Future acquire({ + required ZcashSendPreparationRequest request, + required List candidates, + required int anchorHeight, + }) => zcash.acquireNativeSpendMaterial( + wallet: request.state, + request: zcash.ZcashSpendMaterialRequest.ironwood( + accountFingerprint: request.state.accountFingerprint, + notes: candidates, + anchorHeight: anchorHeight, + ), + source: _StackSpendMaterialSource( + network: request.network.ffiLabel, + client: request.syncClient, + scanExecutor: request.scanExecutor, + ), + ); +} + +abstract interface class ZcashWalletSendService { + Future prepare(ZcashSendPreparationRequest request); + + Future broadcast({ + required ZcashPreparedWalletSend prepared, + required zcash.IronwoodPendingSendState pendingSends, + required int chainHeight, + required Future Function() persist, + required Future Function( + String transactionHex, + ) + submit, + }); +} + +final class ZcashProductionWalletSendService implements ZcashWalletSendService { + const ZcashProductionWalletSendService({ + this.maxSpendNotes = 50, + this.anchorDepth = zcashAnchorDepth, + this.spendMaterialProvider = + const ZcashNativeIronwoodSpendMaterialProvider(), + this.ironwoodPaymentBackend, + }); + + final int maxSpendNotes; + + /// See [zcashAnchorDepth]. + final int anchorDepth; + final ZcashIronwoodSpendMaterialProvider spendMaterialProvider; + final zcash.IronwoodPaymentBackend? ironwoodPaymentBackend; + + @override + Future broadcast({ + required ZcashPreparedWalletSend prepared, + required zcash.IronwoodPendingSendState pendingSends, + required int chainHeight, + required Future Function() persist, + required Future Function( + String transactionHex, + ) + submit, + }) async { + // A send whose earlier submission has no known outcome may already be in + // the node's mempool or in a block, and the node then refuses the copy. + // Only the refusal of a first submission says the notes are free. + final resubmission = pendingSends.records.any( + (record) => + record.txid.toLowerCase() == prepared.txid.toLowerCase() && + record.broadcastState == + zcash.IronwoodPendingBroadcastState.indeterminate, + ); + void refused() => resubmission + ? pendingSends.markIndeterminate(prepared.txid) + : pendingSends.releaseRejected(prepared.txid); + switch (prepared) { + case ZcashPreparedIronwoodSend(): + await zcash.broadcastIronwoodPayment( + payment: prepared.prepared, + chainHeight: chainHeight, + pendingSends: pendingSends, + isRejection: (error) => + !resubmission && error is ZcashBroadcastRejectedException, + submit: (transactionHex) async { + await persist(); + await submit(transactionHex); + return ''; + }, + ); + case ZcashPreparedIronwoodBatch(): + pendingSends.requireBroadcastablePayments( + prepared.prepared, + chainHeight: chainHeight, + ); + pendingSends.markSubmitting(prepared.txid); + await persist(); + try { + await submit(prepared.transactionHex); + pendingSends.markAcknowledged(prepared.txid); + } on ZcashBroadcastRejectedException { + refused(); + rethrow; + } on Object { + pendingSends.markIndeterminate(prepared.txid); + rethrow; + } + case ZcashRecoveredPreparedSend(): + // The stored record must still be the one that was reviewed, apart + // from its broadcast state, which changes with each attempt. + final stored = pendingSends.records.where( + (record) => record.txid.toLowerCase() == prepared.txid.toLowerCase(), + ); + if (stored.length != 1 || + _withoutBroadcastState(stored.single) != + _withoutBroadcastState(prepared.record)) { + throw StateError( + 'recovered Zcash artifact no longer matches durable state', + ); + } + pendingSends.requireBroadcastableRecord( + prepared.record, + chainHeight: chainHeight, + ); + pendingSends.markSubmitting(prepared.txid); + await persist(); + try { + await submit(prepared.transactionHex); + pendingSends.markAcknowledged(prepared.txid); + } on ZcashBroadcastRejectedException { + refused(); + rethrow; + } on Object { + pendingSends.markIndeterminate(prepared.txid); + rethrow; + } + default: + throw StateError('Unknown Zcash prepared-send artifact'); + } + } + + @override + Future prepare( + ZcashSendPreparationRequest request, + ) async { + final outputs = [ + for (final payment in request.payments) _resolveOutput(request, payment), + ]; + return _prepareIronwood(request, outputs); + } + + static String _withoutBroadcastState( + zcash.IronwoodPendingSendRecord record, + ) => jsonEncode(record.toJson()..remove('broadcast_state')); + + /// How many of [notes], largest first, cover [paymentZatoshis] to + /// [outputCount] recipients and the fee of spending that many notes. All of + /// them when they do not: the planner then reports what is missing. + static int _notesCovering( + List notes, + int paymentZatoshis, + int outputCount, + ) { + var value = 0; + for (var count = 1; count <= notes.length; count++) { + value += notes[count - 1].value; + // ZIP 317 charges 5000 zatoshis for each action. An upper bound: an + // action for each note, for each recipient and for the change, and two + // more for the padding a bundle may add. + final feeBound = 5000 * (count + outputCount + 3); + if (value >= paymentZatoshis + feeBound) return count; + } + return notes.length; + } + + zcash.ProposalOutput _resolveOutput( + ZcashSendPreparationRequest request, + ZcashSendPayment payment, + ) { + final nativeNetwork = request.network; + final metadata = zcash.decodeNativeAddress( + address: payment.recipient, + network: nativeNetwork, + ); + final inventory = + metadata.receiverType == zcash.ZcashAddressReceiverType.unified + ? zcash.inventoryUnifiedAddressReceivers( + address: payment.recipient, + network: nativeNetwork, + ) + : null; + return zcash.resolveProposalOutput( + recipient: zcash.ProposalRecipient( + address: payment.recipient, + amountZatoshis: payment.amountZatoshis, + memo: payment.memo, + ), + address: metadata, + unifiedReceivers: inventory, + network: _addressNetwork(request.network), + targetHeight: request.targetHeight, + transactionExpiryHeight: request.expiryHeight, + currentUnixTime: DateTime.now().toUtc().millisecondsSinceEpoch ~/ 1000, + ); + } + + /// Funds [outputs] from the wallet's Ironwood notes, the one pool this + /// wallet spends from. + Future _prepareIronwood( + ZcashSendPreparationRequest request, + List outputs, + ) async { + final spent = { + for (final spend in request.state.ironwood.spends) spend.nullifier, + }; + // A reservation lasts while its transaction can still be mined, which + // includes the block being built on the current tip. + final reserved = request.pendingSends.reservedNullifiersAt( + request.targetHeight - 1, + ); + // The tree the notes are spent from is the one some blocks below the + // tip, and holds the notes up to there. + final anchorHeight = request.targetHeight - 1 - anchorDepth; + final candidates = [ + for (final note in request.state.ironwood.notes) + if (note.nullifier != null && + note.commitmentPosition != null && + note.height <= anchorHeight && + !spent.contains(note.nullifier) && + !reserved.contains(note.nullifier)) + note, + ]..sort((left, right) => right.value.compareTo(left.value)); + if (candidates.length > maxSpendNotes) { + candidates.removeRange(maxSpendNotes, candidates.length); + } + if (candidates.isEmpty) { + throw zcash.IronwoodSelectionException( + zcash.IronwoodSelectionRefusal.insufficientFunds, + 'this wallet has no Ironwood notes that are free to spend', + ); + } + // Spending a note needs the blocks since it was received, so offer the + // planner the largest notes that cover the payment, not every note. + final needed = _notesCovering( + candidates, + outputs.fold(0, (total, output) => total + output.amountZatoshis), + outputs.length, + ); + candidates.removeRange(needed, candidates.length); + + final material = await spendMaterialProvider.acquire( + request: request, + candidates: candidates, + anchorHeight: anchorHeight, + ); + final provingParameters = + outputs.any( + (output) => + output.actualOutputPool == zcash.ProposalOutputPool.sapling, + ) + ? await request.resolveSaplingProvingParameters() + : null; + if (outputs.length > 1) { + final prepared = zcash.prepareNativeIronwoodPayments( + network: request.network, + scan: material.scan, + outputs: outputs, + ironwoodChangeAddress: request.ironwoodChangeAddress, + targetHeight: request.targetHeight, + expiryHeight: request.expiryHeight, + seedHex: request.seedHex, + reservations: request.pendingSends, + maxNotes: maxSpendNotes, + provingParameters: provingParameters, + regtestNu63ActivationHeight: request.regtestNu63ActivationHeight, + now: DateTime.now().toUtc(), + allowExperimentalIronwoodBuild: true, + backend: ironwoodPaymentBackend, + ); + request.pendingSends.addPreparedPayments( + prepared, + createdHeight: request.targetHeight - 1, + ); + return ZcashPreparedIronwoodBatch( + prepared: prepared, + sessionGeneration: request.sessionGeneration, + ); + } + final output = outputs.single; + final prepared = zcash.prepareNativeIronwoodPayment( + network: request.network, + scan: material.scan, + output: output, + ironwoodChangeAddress: request.ironwoodChangeAddress, + targetHeight: request.targetHeight, + expiryHeight: request.expiryHeight, + seedHex: request.seedHex, + reservations: request.pendingSends, + maxNotes: maxSpendNotes, + provingParameters: provingParameters, + regtestNu63ActivationHeight: request.regtestNu63ActivationHeight, + now: DateTime.now().toUtc(), + allowExperimentalIronwoodBuild: true, + backend: ironwoodPaymentBackend, + ); + request.pendingSends.addPreparedPayment( + prepared, + createdHeight: request.targetHeight - 1, + ); + return ZcashPreparedIronwoodSend( + prepared: prepared, + sessionGeneration: request.sessionGeneration, + encodedRecipient: output.encodedAddress, + selectedReceiver: output.selectedReceiver, + selectedReceiverAddress: output.receiverAddress, + actualOutputPool: output.actualOutputPool, + memo: output.memo, + ); + } +} + +final class _StackSpendMaterialSource + implements zcash.ZcashSpendMaterialSource { + const _StackSpendMaterialSource({ + required this.network, + required this.client, + required this.scanExecutor, + }); + + @override + final String network; + final ZcashLightwalletdSyncClient client; + final ZcashScanExecutor scanExecutor; + + @override + Future fetchRange(int start, int end) => + client.getBlockRange(start, end); + + @override + Future fetchTreeState(int height) => + client.getTreeState(height); + + @override + Future scan(zcash.ScanInputEnvelope input) => + scanExecutor.scan(input); +} + +zcash.ZcashAddressNetwork _addressNetwork(zcash.ZcashNetwork network) => + switch (network) { + zcash.ZcashNetwork.mainnet => zcash.ZcashAddressNetwork.mainnet, + zcash.ZcashNetwork.testnet => zcash.ZcashAddressNetwork.testnet, + zcash.ZcashNetwork.regtest => zcash.ZcashAddressNetwork.regtest, + }; diff --git a/lib/wallets/wallet/intermediate/zcash_transparent_receiver_discovery.dart b/lib/wallets/wallet/intermediate/zcash_transparent_receiver_discovery.dart new file mode 100644 index 000000000..cdab601b1 --- /dev/null +++ b/lib/wallets/wallet/intermediate/zcash_transparent_receiver_discovery.dart @@ -0,0 +1,85 @@ +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +/// Public-key-only BIP-44 transparent receiver discovery. +/// +/// Lightwalletd's transparent transaction RPC accepts one address at a time, +/// so discovery registers and queries bounded batches. A scope stops after +/// [gapLimit] consecutive child indexes without transaction activity. The +/// registered inventory is persisted by [ZcashWalletStateController], making +/// its highest contiguous child the durable discovery frontier. +final class ZcashTransparentReceiverDiscovery { + ZcashTransparentReceiverDiscovery({ + required this.network, + required this.viewingKeys, + this.gapLimit = 20, + this.hardChildLimit = 1000, + }) { + if (gapLimit < 1) { + throw ArgumentError.value(gapLimit, 'gapLimit', 'must be positive'); + } + if (hardChildLimit < gapLimit) { + throw ArgumentError.value( + hardChildLimit, + 'hardChildLimit', + 'must be at least the gap limit', + ); + } + } + + final zcash.ZcashNetwork network; + final zcash.ZcashViewingKeys viewingKeys; + final int gapLimit; + + /// Exclusive child-index ceiling. This bounds server queries, startup time, + /// and the address linkage disclosed to one lightwalletd endpoint. + final int hardChildLimit; + + List initialReceivers() => [ + ...deriveRange(zcash.ZcashTransparentReceiverScope.external, 0, gapLimit), + ...deriveRange(zcash.ZcashTransparentReceiverScope.internal, 0, gapLimit), + ]; + + List deriveRange( + zcash.ZcashTransparentReceiverScope scope, + int start, + int endExclusive, + ) { + if (start < 0 || endExclusive < start || endExclusive > hardChildLimit) { + throw RangeError.range( + endExclusive, + start, + hardChildLimit, + 'endExclusive', + ); + } + final transparent = viewingKeys.transparent; + final viewingKey = switch (scope) { + zcash.ZcashTransparentReceiverScope.external => transparent.externalIvk, + zcash.ZcashTransparentReceiverScope.internal => transparent.internalIvk, + }; + if (!transparent.available || viewingKey == null || viewingKey.isEmpty) { + throw StateError( + 'Transparent receiver discovery requires public viewing material', + ); + } + final keyScope = switch (scope) { + zcash.ZcashTransparentReceiverScope.external => + zcash.ZcashTransparentKeyScope.external, + zcash.ZcashTransparentReceiverScope.internal => + zcash.ZcashTransparentKeyScope.internal, + }; + return [ + for (var child = start; child < endExclusive; child++) + zcash.ZcashTransparentReceiver( + address: zcash.deriveNativeTransparentAddressFromViewingKey( + viewingKeyHex: viewingKey, + network: network, + childIndex: child, + scope: keyScope, + ), + scope: scope, + childIndex: child, + ), + ]; + } +} diff --git a/lib/wallets/wallet/intermediate/zcash_wallet_persistence.dart b/lib/wallets/wallet/intermediate/zcash_wallet_persistence.dart new file mode 100644 index 000000000..cace120d6 --- /dev/null +++ b/lib/wallets/wallet/intermediate/zcash_wallet_persistence.dart @@ -0,0 +1,124 @@ +import 'dart:io'; + +import 'package:mutex/mutex.dart'; +import 'package:path/path.dart' as path; + +import '../../../utilities/flutter_secure_storage_interface.dart'; + +const zcashWalletStateSuffix = 'state'; +const zcashPendingSendSuffix = 'pending'; +const zcashWalletPersistenceSuffixes = [ + zcashWalletStateSuffix, + zcashPendingSendSuffix, +]; + +/// The directory under the application root that holds Zcash wallet files. +const zcashPersistenceDirectory = 'zcash'; + +/// The file that holds one wallet's Zcash data of the kind [suffix] names. +String zcashWalletPersistencePath({ + required Directory applicationRoot, + required String walletId, + required String suffix, +}) { + if (walletId.isEmpty || + walletId == '.' || + walletId == '..' || + walletId.contains('/') || + walletId.contains(r'\')) { + throw ArgumentError.value( + walletId, + 'walletId', + 'must be one path-safe segment', + ); + } + return path.join( + applicationRoot.path, + zcashPersistenceDirectory, + '$walletId.$suffix', + ); +} + +final _fileLocks = {}; + +/// Runs [operation] alone among the operations on the file at [filePath]. +/// +/// A save writes a temporary file and renames it, and a load removes a +/// temporary file an interrupted save left. Without this a load during a save +/// would remove the file the save is about to rename. Refreshes and sends use +/// separate store objects for the same file, so the lock is per path. +Future withZcashFileLock( + String filePath, + Future Function() operation, +) => (_fileLocks[filePath] ??= Mutex()).protect(operation); + +String zcashWalletStateKey(String walletId) => + 'zcash_wallet_state_key_v1_$walletId'; + +String zcashPendingSendKey(String walletId) => + 'zcash_pending_send_key_v1_$walletId'; + +List zcashWalletPersistenceKeys(String walletId) => [ + zcashWalletStateKey(walletId), + zcashPendingSendKey(walletId), +]; + +/// Removes exactly one wallet's Zcash checkpoints and their encryption keys. +/// Other wallets' files are never traversed. +Future deleteZcashWalletPersistence({ + required Directory applicationRoot, + required String walletId, + required SecureStorageInterface secureStorage, +}) async { + Object? firstError; + StackTrace? firstStackTrace; + + Future attempt(Future Function() operation) async { + try { + await operation(); + } catch (error, stackTrace) { + firstError ??= error; + firstStackTrace ??= stackTrace; + } + } + + for (final suffix in zcashWalletPersistenceSuffixes) { + final persistedPath = zcashWalletPersistencePath( + applicationRoot: applicationRoot, + walletId: walletId, + suffix: suffix, + ); + await attempt( + () => withZcashFileLock(persistedPath, () async { + await _deleteExactFile(persistedPath); + await _deleteExactFile('$persistedPath.tmp'); + }), + ); + } + if (firstError != null) { + Error.throwWithStackTrace(firstError!, firstStackTrace!); + } + for (final key in zcashWalletPersistenceKeys(walletId)) { + await attempt(() => secureStorage.delete(key: key)); + } + + if (firstError != null) { + Error.throwWithStackTrace(firstError!, firstStackTrace!); + } +} + +Future _deleteExactFile(String candidate) async { + switch (await FileSystemEntity.type(candidate, followLinks: false)) { + case FileSystemEntityType.notFound: + return; + case FileSystemEntityType.file: + await File(candidate).delete(); + case FileSystemEntityType.link: + await Link(candidate).delete(); + default: + throw FileSystemException( + 'refusing to delete a non-file Zcash persistence path', + candidate, + ); + } +} diff --git a/lib/wallets/wallet/intermediate/zcash_wallet_state.dart b/lib/wallets/wallet/intermediate/zcash_wallet_state.dart new file mode 100644 index 000000000..1d120f900 --- /dev/null +++ b/lib/wallets/wallet/intermediate/zcash_wallet_state.dart @@ -0,0 +1,271 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:cryptography/cryptography.dart'; +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +import '../../../utilities/flutter_secure_storage_interface.dart'; +import 'zcash_wallet_persistence.dart'; + +class ZcashStatePersistenceException implements Exception { + const ZcashStatePersistenceException(this.message); + + final String message; + + @override + String toString() => 'ZcashStatePersistenceException: $message'; +} + +class ZcashPersistedWalletState { + ZcashPersistedWalletState({ + required this.syncState, + required this.observedChainHeight, + Map transparentHistoryFrontiers = const {}, + Map blockTimes = const {}, + }) : transparentHistoryFrontiers = Map.unmodifiable( + transparentHistoryFrontiers, + ), + blockTimes = Map.unmodifiable(blockTimes); + + static const version = 1; + + final zcash.ZcashWalletSyncState syncState; + final int observedChainHeight; + final Map transparentHistoryFrontiers; + + /// The header time, in seconds, of each block that holds one of the + /// wallet's shielded transactions, by height. A scan result does not carry + /// it, so it is kept from the blocks as they are scanned. + final Map blockTimes; + + Map toJson() => { + 'version': version, + 'observed_chain_height': observedChainHeight, + 'sync_state': syncState.toJson(), + 'transparent_history_frontiers': transparentHistoryFrontiers, + 'block_times': { + for (final entry in blockTimes.entries) '${entry.key}': entry.value, + }, + }; + + factory ZcashPersistedWalletState.fromJson(Map json) { + if (json['version'] != version) { + throw const ZcashStatePersistenceException( + 'unsupported wallet-state payload version', + ); + } + final height = json['observed_chain_height']; + final state = json['sync_state']; + final rawFrontiers = json['transparent_history_frontiers']; + if (height is! num || state is! Map) { + throw const ZcashStatePersistenceException( + 'wallet-state payload is malformed', + ); + } + final frontiers = {}; + if (rawFrontiers != null) { + if (rawFrontiers is! Map) { + throw const ZcashStatePersistenceException( + 'transparent history frontiers are malformed', + ); + } + for (final entry in rawFrontiers.entries) { + if (entry.key is! String || + (entry.key as String).isEmpty || + entry.value is! num || + (entry.value as num).toInt() < 0) { + throw const ZcashStatePersistenceException( + 'transparent history frontiers are malformed', + ); + } + frontiers[entry.key as String] = (entry.value as num).toInt(); + } + } + final blockTimes = {}; + final rawBlockTimes = json['block_times']; + if (rawBlockTimes != null) { + if (rawBlockTimes is! Map) { + throw const ZcashStatePersistenceException('block times are malformed'); + } + for (final entry in rawBlockTimes.entries) { + final blockHeight = entry.key is String + ? int.tryParse(entry.key as String) + : null; + final time = entry.value; + if (blockHeight == null || blockHeight < 0 || time is! int) { + throw const ZcashStatePersistenceException( + 'block times are malformed', + ); + } + blockTimes[blockHeight] = time; + } + } + return ZcashPersistedWalletState( + syncState: zcash.ZcashWalletSyncState.fromJson( + state.cast(), + ), + observedChainHeight: height.toInt(), + transparentHistoryFrontiers: frontiers, + blockTimes: blockTimes, + ); + } +} + +class ZcashEncryptedWalletStateStore { + ZcashEncryptedWalletStateStore({ + required this.path, + required this.walletId, + required this.network, + required this.accountFingerprint, + required this.secureStorage, + }); + + static const envelopeVersion = 1; + static final _cipher = AesGcm.with256bits(); + + final String path; + final String walletId; + final String network; + final String accountFingerprint; + final SecureStorageInterface secureStorage; + + String get _keyName => zcashWalletStateKey(walletId); + + List get _aad => utf8.encode( + 'stack-wallet-zcash-state|$envelopeVersion|$walletId|$network|' + '$accountFingerprint', + ); + + Future load() => withZcashFileLock(path, _load); + + Future save(ZcashPersistedWalletState state) => + withZcashFileLock(path, () => _save(state)); + + /// Removes the local chain checkpoint so the next open starts from the + /// validated wallet birthday. The per-wallet encryption key is retained so + /// a newly scanned checkpoint can be authenticated with the same wallet + /// identity. + Future reset() => withZcashFileLock(path, _reset); + + Future _load() async { + await _refuseSymlink(path); + await _removeInterruptedWrite(); + final file = File(path); + if (!await file.exists()) return null; + final encodedKey = await secureStorage.read(key: _keyName); + if (encodedKey == null) { + throw const ZcashStatePersistenceException( + 'encrypted wallet state exists but its key is missing', + ); + } + try { + final envelope = (jsonDecode(await file.readAsString()) as Map) + .cast(); + if (envelope['version'] != envelopeVersion) { + throw const ZcashStatePersistenceException( + 'unsupported encrypted wallet-state envelope version', + ); + } + final clear = await _cipher.decrypt( + SecretBox( + base64Decode(envelope['ciphertext'] as String), + nonce: base64Decode(envelope['nonce'] as String), + mac: Mac(base64Decode(envelope['mac'] as String)), + ), + secretKey: SecretKey(base64Decode(encodedKey)), + aad: _aad, + ); + final payload = (jsonDecode(utf8.decode(clear)) as Map) + .cast(); + final restored = ZcashPersistedWalletState.fromJson(payload); + if (restored.syncState.accountFingerprint != accountFingerprint) { + throw const ZcashStatePersistenceException( + 'wallet state belongs to a different account', + ); + } + _validateNetwork(restored.syncState); + return restored; + } on ZcashStatePersistenceException { + rethrow; + } on Object { + // The cause is left out: a decoding error quotes what it decoded. + throw const ZcashStatePersistenceException( + 'wallet state failed authentication or is corrupt', + ); + } + } + + Future _save(ZcashPersistedWalletState state) async { + await _refuseSymlink(path); + await _refuseSymlink('$path.tmp'); + if (state.syncState.accountFingerprint != accountFingerprint) { + throw const ZcashStatePersistenceException( + 'refusing to save state for a different account', + ); + } + _validateNetwork(state.syncState); + var encodedKey = await secureStorage.read(key: _keyName); + if (encodedKey == null) { + encodedKey = base64Encode( + await (await _cipher.newSecretKey()).extractBytes(), + ); + await secureStorage.write(key: _keyName, value: encodedKey); + } + final box = await _cipher.encrypt( + utf8.encode(jsonEncode(state.toJson())), + secretKey: SecretKey(base64Decode(encodedKey)), + nonce: _cipher.newNonce(), + aad: _aad, + ); + final envelope = jsonEncode({ + 'version': envelopeVersion, + 'nonce': base64Encode(box.nonce), + 'ciphertext': base64Encode(box.cipherText), + 'mac': base64Encode(box.mac.bytes), + }); + final temporary = File('$path.tmp'); + await temporary.parent.create(recursive: true); + try { + await temporary.writeAsString(envelope, flush: true); + await temporary.rename(path); + } finally { + if (await temporary.exists()) await temporary.delete(); + } + } + + Future _reset() async { + final temporaryPath = '$path.tmp'; + await _refuseSymlink(path); + await _refuseSymlink(temporaryPath); + + final file = File(path); + final temporary = File(temporaryPath); + if (await file.exists()) await file.delete(); + if (await temporary.exists()) await temporary.delete(); + } + + Future _removeInterruptedWrite() async { + final temporaryPath = '$path.tmp'; + await _refuseSymlink(temporaryPath); + final temporary = File(temporaryPath); + if (await temporary.exists()) await temporary.delete(); + } + + Future _refuseSymlink(String candidate) async { + if (await FileSystemEntity.type(candidate, followLinks: false) == + FileSystemEntityType.link) { + throw const ZcashStatePersistenceException( + 'refusing to access wallet state through a symbolic link', + ); + } + } + + void _validateNetwork(zcash.ZcashWalletSyncState state) { + final expected = zcash.ZcashAddressNetwork.fromJson(network); + if (state.network != expected) { + throw const ZcashStatePersistenceException( + 'wallet state belongs to a different consensus network', + ); + } + } +} diff --git a/lib/wallets/wallet/intermediate/zcash_wallet_state_controller.dart b/lib/wallets/wallet/intermediate/zcash_wallet_state_controller.dart new file mode 100644 index 000000000..043054e34 --- /dev/null +++ b/lib/wallets/wallet/intermediate/zcash_wallet_state_controller.dart @@ -0,0 +1,1344 @@ +import 'dart:convert'; +import 'dart:isolate'; + +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +import '../../../models/balance.dart'; +import '../../../models/isar/models/blockchain_data/transaction.dart'; +import '../../../models/isar/models/blockchain_data/v2/input_v2.dart'; +import '../../../models/isar/models/blockchain_data/v2/output_v2.dart'; +import '../../../models/isar/models/blockchain_data/v2/transaction_v2.dart'; +import '../../../utilities/amount/amount.dart'; +import 'zcash_account_session.dart'; +import 'zcash_transparent_receiver_discovery.dart'; +import 'zcash_wallet_state.dart'; + +abstract interface class ZcashScanExecutor { + Future scan(zcash.ScanInputEnvelope envelope); +} + +typedef ZcashNativeScanRequest = (String ufvk, String network, String envelope); +typedef ZcashNativeScanWorker = Future Function( + ZcashNativeScanRequest request, +); + +/// Runs the synchronous native compact-block scanner outside Flutter's owner +/// isolate. Only strings cross the isolate boundary; native bindings are +/// opened in the worker and the result is parsed back on the owner isolate. +class ZcashNativeIsolateScanExecutor implements ZcashScanExecutor { + const ZcashNativeIsolateScanExecutor({ + required this.ufvk, + required this.network, + this.worker = _runNativeScanIsolate, + }); + + final String ufvk; + final String network; + final ZcashNativeScanWorker worker; + + @override + Future scan(zcash.ScanInputEnvelope envelope) async { + final raw = await worker((ufvk, network, envelope.encode())); + return zcash.ZcashScanResult.fromRawJson( + raw, + context: 'scan_compact_blocks/stack_wallet_isolate', + redactSensitive: [ufvk], + // The scanner reports the account's Orchard notes on every network. + // The backend parses them only on request, and a scan that refused + // one would stop the wallet at that block for good. They count + // towards the total and cannot be spent. + allowExperimentalOrchardNotes: true, + ); + } +} + +Future _runNativeScanIsolate(ZcashNativeScanRequest request) => + Isolate.run(() => _scanNativeRaw(request)); + +String _scanNativeRaw(ZcashNativeScanRequest request) => zcash + .ZcashFfiBindings + .instance + .scanCompactBlocksRaw(request.$1, request.$2, request.$3); + +abstract interface class ZcashSyncSession { + /// Scans to the chain tip, or to a reorganization. [onAdvanced] is awaited + /// after each scanned range that leaves more to scan. + Future syncToTip({ + Future Function()? onAdvanced, + }); +} + +/// The header time, in seconds, of scanned blocks by height. +/// +/// A scan result does not carry block times, and asking a server for the +/// blocks of the wallet's transactions would tell it which those are. The +/// sync records the time of every block it scans here, and the wallet state +/// keeps those of the blocks that hold its transactions. +final class ZcashBlockTimes { + final _times = {}; + + int? operator [](int height) => _times[height]; + + void record(zcash.ZcashLightwalletdScanSource range) { + for (final block in range.blocks) { + _times[block.height.toInt()] = block.time; + } + } + + void restore(Map times) => _times.addAll(times); + + void retainHeights(Set heights) => + _times.removeWhere((height, _) => !heights.contains(height)); + + void clear() => _times.clear(); + + Map toMap() => Map.of(_times); +} + +abstract interface class ZcashReorgRecoverableSyncSession + implements ZcashSyncSession { + Future resumeFrom(zcash.ZcashReorgRecovery recovery); +} + +typedef ZcashSyncSessionFactory = ZcashSyncSession Function( + zcash.ZcashWalletSyncState state, + ZcashScanExecutor scanExecutor, +); + +typedef ZcashTransparentRefreshCallback = + Future Function( + zcash.ZcashTransparentState state, + ); + +typedef ZcashTransparentActivityCallback = + Future Function( + List addresses, + int startHeight, + int chainHeight, + ); + +class ZcashReorgDetectedException implements Exception { + const ZcashReorgDetectedException(this.outcome); + + final zcash.ZcashSyncReorged outcome; + + @override + String toString() => + 'ZcashReorgDetectedException: chain reorganized; persisted state was not ' + 'advanced'; +} + +class ZcashRecoveryLimitException implements Exception { + const ZcashRecoveryLimitException({ + required this.attempts, + required this.cause, + }); + + final int attempts; + final Object cause; + + @override + String toString() => + 'ZcashRecoveryLimitException: refused another recovery after ' + '$attempts attempts in one refresh: $cause'; +} + +class ZcashRecoveryCancelledException implements Exception { + const ZcashRecoveryCancelledException(); + + @override + String toString() => 'Zcash wallet recovery was cancelled'; +} + +/// Cooperative cancellation checked after external async boundaries in a +/// recovery refresh. Native scanning may finish off-isolate, but its result is +/// rejected before it can be persisted or projected into Stack. +final class ZcashRecoveryCancellationToken { + var _cancelled = false; + + bool get isCancelled => _cancelled; + + void cancel() => _cancelled = true; + + void throwIfCancelled() { + if (_cancelled) throw const ZcashRecoveryCancelledException(); + } +} + +/// How many blocks below the tip a send takes its anchor from. A +/// transaction built on the tree of the tip block can never be mined once +/// that block is replaced, and its notes then stay held until it expires. +/// A note is spendable once it is this many blocks below the tip. +const zcashAnchorDepth = 3; + +class ZcashWalletSnapshot { + const ZcashWalletSnapshot({ + required this.chainHeight, + required this.balance, + required this.history, + this.blockTimes = const {}, + this.spendableNotes = const {}, + this.unanchoredNotes = const {}, + }); + + /// The [spendableNotes] of [state]. + static Map spendableNotesOf(zcash.ZcashWalletSyncState state) { + final spent = {for (final spend in state.ironwood.spends) spend.nullifier}; + return { + for (final note in state.ironwood.notes) + if (note.nullifier != null && + note.commitmentPosition != null && + !spent.contains(note.nullifier)) + note.nullifier!: note.value, + }; + } + + final int chainHeight; + final zcash.ZcashAccountBalance balance; + final zcash.ZcashTransactionHistory history; + + /// The header time, in seconds, of the blocks that hold the wallet's + /// shielded transactions, by height. + final Map blockTimes; + + /// The value of each note a send can spend, by nullifier: the unspent + /// Ironwood notes. Funds of the other pools count towards the total only. + /// + /// The backend's own spendable count is not used. It wants each note's + /// witness in the scan, which the sync does not ask for: a send fetches + /// the witnesses of the notes it spends. + final Map spendableNotes; + + /// The nullifiers of the [spendableNotes] that are above the anchor of a + /// send prepared now, see [zcashAnchorDepth]. They are pending until the + /// chain has grown past them. + final Set unanchoredNotes; + + /// The [unanchoredNotes] of [state] at [chainHeight]. + static Set unanchoredNotesOf( + zcash.ZcashWalletSyncState state, + int chainHeight, { + int anchorDepth = zcashAnchorDepth, + }) => { + for (final note in state.ironwood.notes) + if (note.nullifier != null && note.height > chainHeight - anchorDepth) + note.nullifier!, + }; +} + +class ZcashStackStateMapper { + const ZcashStackStateMapper({required this.walletId}); + + static const _fractionDigits = 8; + static const unknownTimestampSentinel = 0; + static const unknownVersionSentinel = -1; + + /// [TransactionV2.otherData] key: the value pools a transaction touched. + static const poolsKey = 'zcashPools'; + + final String walletId; + + /// The balance of [snapshot] after the wallet's own sends that are not + /// mined, see [unminedSends]. + /// + /// The scanned state still counts the notes such a send spends. They leave + /// the spendable balance, the fee and what is paid to others leave the + /// total, and the rest is pending until a block holds it: the change, and + /// what the send pays to [ownAddresses], the wallet's own. + /// + /// A note above the anchor of a send, see [zcashAnchorDepth], is pending + /// too. + Balance balance( + ZcashWalletSnapshot snapshot, { + zcash.IronwoodPendingSendState? pendingSends, + Set ownAddresses = const {}, + }) { + Amount amount(int value) => + Amount(rawValue: BigInt.from(value), fractionDigits: _fractionDigits); + + var total = snapshot.balance.totalZatoshis; + var spendable = snapshot.spendableNotes.values.fold( + 0, + (sum, value) => sum + value, + ); + var pendingChange = 0; + for (final nullifier in snapshot.unanchoredNotes) { + final young = snapshot.spendableNotes[nullifier] ?? 0; + spendable -= young; + pendingChange += young; + } + final unmined = unminedSends( + snapshot.history, + pendingSends, + snapshot.chainHeight, + ); + for (final record in unmined) { + var notes = 0; + // Those of its notes that are still counted as spendable. A note that + // a reorganisation moved above the anchor is pending already. + var held = 0; + for (final nullifier in record.selectedNullifiers) { + final value = snapshot.spendableNotes[nullifier] ?? 0; + notes += value; + if (!snapshot.unanchoredNotes.contains(nullifier)) held += value; + } + // Its notes are spent or unknown to this state: nothing to adjust. + if (notes < _paymentTotal(record) + record.feeZatoshis) continue; + final leaving = + record.feeZatoshis + + record.paymentOutputs + .where( + (output) => !ownAddresses.contains(output.encodedRecipient), + ) + .fold(0, (sum, output) => sum + output.amountZatoshis); + total -= leaving; + spendable -= held; + pendingChange += held - leaving; + } + return Balance( + total: amount(total), + spendable: amount(spendable), + blockedTotal: amount(total - spendable - pendingChange), + pendingSpendable: amount(pendingChange), + ); + } + + /// The wallet's own sends that were submitted and that no block of + /// [history] holds, as long as one still could at [chainHeight]. + static List unminedSends( + zcash.ZcashTransactionHistory history, + zcash.IronwoodPendingSendState? pendingSends, + int chainHeight, + ) { + if (pendingSends == null) return const []; + final mined = { + for (final entry in history.entries) entry.txid.toLowerCase(), + }; + return [ + for (final record in pendingSends.records) + if (!mined.contains(record.txid.toLowerCase()) && + !record.isExpiredAt(chainHeight) && + record.broadcastState != + zcash.IronwoodPendingBroadcastState.prepared) + record, + ]; + } + + /// The scanned [history] as Stack transactions, followed by the wallet's + /// own sends that were submitted and are neither mined nor expired at + /// [chainHeight]. + /// + /// [timestamps] is keyed by txid. Shielded history carries no block time, + /// and a send that is not mined has none: the caller supplies both. + List transactions( + zcash.ZcashTransactionHistory history, { + zcash.IronwoodPendingSendState? pendingSends, + Map timestamps = const {}, + int? chainHeight, + }) { + final pendingByTxid = { + for (final record + in pendingSends?.records ?? const []) + record.txid.toLowerCase(): record, + }; + return [ + for (final entry in history.entries) + _transaction( + entry, + pendingByTxid[entry.txid.toLowerCase()], + timestamps[entry.txid], + ), + if (chainHeight != null) + for (final record in unminedSends(history, pendingSends, chainHeight)) + _unminedSend(record, timestamps[record.txid]), + ]; + } + + TransactionV2 _transaction( + zcash.ZcashHistoryEntry entry, + zcash.IronwoodPendingSendRecord? pending, + int? timestamp, + ) { + // The scan reports a fee only for transparent activity, and the wallet's + // own sends record theirs. When neither does, the amount of a send + // includes its fee. + final feeZatoshis = entry.feeZatoshis ?? pending?.feeZatoshis; + final externalZatoshis = pending == null + ? entry.spentZatoshis - entry.receivedZatoshis - (feeZatoshis ?? 0) + : _paymentTotal(pending); + return TransactionV2( + walletId: walletId, + blockHash: entry.blockHash, + hash: entry.txid, + txid: entry.txid, + timestamp: entry.timestamp ?? timestamp ?? unknownTimestampSentinel, + height: entry.height, + inputs: [if (entry.spentZatoshis > 0) _input(entry.spentZatoshis)], + // Exact shielded recipients, per-output values, and memos remain only in + // the authenticated encrypted pending-send store. MainDB is not + // encrypted, so its durable history contains one address-free aggregate + // output instead of privacy-sensitive ZIP-321 payment details. + outputs: [ + if (entry.isOutgoing && externalZatoshis > 0) + _output(externalZatoshis, walletOwns: false), + if (entry.receivedZatoshis > 0) + _output(entry.receivedZatoshis, walletOwns: true), + ], + version: unknownVersionSentinel, + type: entry.isOutgoing + ? TransactionType.outgoing + : TransactionType.incoming, + subType: TransactionSubType.none, + otherData: _otherData( + feeZatoshis: feeZatoshis, + pools: entry.pools.toList()..sort(), + ), + ); + } + + /// A submitted send that no block contains yet. Its change is not known + /// until it is mined, so the row carries the payment and the fee only. + TransactionV2 _unminedSend( + zcash.IronwoodPendingSendRecord record, + int? timestamp, + ) { + final paymentZatoshis = _paymentTotal(record); + return TransactionV2( + walletId: walletId, + blockHash: null, + hash: record.txid, + txid: record.txid, + timestamp: timestamp ?? unknownTimestampSentinel, + height: null, + inputs: [_input(paymentZatoshis + record.feeZatoshis)], + outputs: [_output(paymentZatoshis, walletOwns: false)], + version: unknownVersionSentinel, + type: TransactionType.outgoing, + subType: TransactionSubType.none, + otherData: _otherData( + feeZatoshis: record.feeZatoshis, + pools: [record.sourcePool.name], + ), + ); + } + + static int _paymentTotal(zcash.IronwoodPendingSendRecord record) => record + .paymentOutputs + .fold(0, (total, output) => total + output.amountZatoshis); + + static InputV2 _input(int zatoshis) => + InputV2.isarCantDoRequiredInDefaultConstructor( + scriptSigHex: null, + scriptSigAsm: null, + sequence: null, + outpoint: null, + addresses: const [], + valueStringSats: zatoshis.toString(), + witness: null, + innerRedeemScriptAsm: null, + coinbase: null, + walletOwns: true, + ); + + static OutputV2 _output(int zatoshis, {required bool walletOwns}) => + OutputV2.isarCantDoRequiredInDefaultConstructor( + scriptPubKeyHex: '', + valueStringSats: zatoshis.toString(), + addresses: const [], + walletOwns: walletOwns, + ); + + static String _otherData({ + required int? feeZatoshis, + required List pools, + }) => jsonEncode({ + // Always set: without it TransactionV2 derives the fee from inputs and + // outputs, which a received transaction does not have. + TxV2OdKeys.overrideFee: Amount( + rawValue: BigInt.from(feeZatoshis ?? 0), + fractionDigits: _fractionDigits, + ).toJsonString(), + poolsKey: pools, + }); +} + +/// The times to store for the history of [snapshot] and for sends that are +/// not mined, by txid, for [ZcashStackStateMapper.transactions]. +/// +/// Shielded history carries no block time: it comes from the block times the +/// scan kept. A send that is not mined keeps the time [stored] for it, which +/// is [now] the first time it is listed. +Map zcashHistoryTimestamps({ + required ZcashWalletSnapshot snapshot, + required zcash.IronwoodPendingSendState? pendingSends, + required Map stored, + required int now, +}) { + final timestamps = {}; + final unmined = ZcashStackStateMapper.unminedSends( + snapshot.history, + pendingSends, + snapshot.chainHeight, + ); + for (final record in unmined) { + final row = stored[record.txid]; + timestamps[record.txid] = row != null && row.height == null + ? row.timestamp + : now; + } + for (final entry in snapshot.history.entries) { + final time = entry.timestamp ?? snapshot.blockTimes[entry.height]; + if (time != null) timestamps[entry.txid] = time; + } + return timestamps; +} + +class _ZcashTransparentHistoryDiscovery { + const _ZcashTransparentHistoryDiscovery({ + required this.transactions, + required this.frontiers, + }); + + final List transactions; + final Map frontiers; +} + +class ZcashWalletStateController { + static const maximumRecoveryCyclesPerRefresh = 2; + + /// How many times one refresh syncs to the tip while blocks keep arriving + /// between its shielded and its transparent pass. + static const maximumTipRounds = 4; + + ZcashWalletStateController._( + this._store, + this._state, + this._sync, + this._observedChainHeight, + this._refreshTransparent, + this._transparentActivity, + this._transparentDiscovery, + this._accountMetadata, + this._viewingKeys, + this._birthdayHeight, + Map transparentHistoryFrontiers, + this._loadBirthdayTreeState, + this._scanExecutor, + this._openSync, + this._blockTimes, + ) : _transparentHistoryFrontiers = Map.of(transparentHistoryFrontiers); + + /// How many scanned ranges pass between saves of a sync in progress, so + /// that a long scan that is interrupted resumes near where it stopped. + static const checkpointRanges = 10; + + final ZcashEncryptedWalletStateStore _store; + zcash.ZcashWalletSyncState _state; + ZcashSyncSession _sync; + int _observedChainHeight; + final ZcashTransparentRefreshCallback? _refreshTransparent; + final ZcashTransparentActivityCallback? _transparentActivity; + final ZcashTransparentReceiverDiscovery? _transparentDiscovery; + final zcash.ZcashAccountMetadata? _accountMetadata; + final zcash.ZcashViewingKeys? _viewingKeys; + final int _birthdayHeight; + final Future Function(int height) _loadBirthdayTreeState; + final ZcashScanExecutor _scanExecutor; + final ZcashSyncSessionFactory _openSync; + final ZcashBlockTimes _blockTimes; + Map _transparentHistoryFrontiers; + Future? _refreshInFlight; + + static Future open({ + required ZcashEncryptedWalletStateStore store, + required String accountFingerprint, + required String network, + required int birthdayHeight, + required Future Function(int height) loadBirthdayTreeState, + required ZcashScanExecutor scanExecutor, + required ZcashSyncSessionFactory openSync, + zcash.ZcashAccountMetadata? accountMetadata, + zcash.ZcashViewingKeys? viewingKeys, + Iterable additionalTransparentReceivers = + const [], + ZcashTransparentRefreshCallback? refreshTransparent, + ZcashTransparentActivityCallback? transparentActivity, + ZcashTransparentReceiverDiscovery? transparentDiscovery, + ZcashBlockTimes? blockTimes, + }) async { + if (birthdayHeight < 1) { + throw ArgumentError.value( + birthdayHeight, + 'birthdayHeight', + 'must leave a preceding tree-state height', + ); + } + if ((accountMetadata == null) != (viewingKeys == null)) { + throw ArgumentError( + 'accountMetadata and viewingKeys must be supplied together', + ); + } + if (transparentDiscovery != null && + (accountMetadata == null || + viewingKeys == null || + transparentActivity == null)) { + throw ArgumentError( + 'transparent discovery requires account viewing material and an ' + 'activity source', + ); + } + if (store.accountFingerprint != accountFingerprint || + store.network != network) { + throw const ZcashStatePersistenceException( + 'wallet-state store context does not match the requested account', + ); + } + + var persisted = await store.load(); + if (persisted == null) { + final treeState = await loadBirthdayTreeState(birthdayHeight - 1); + if (treeState.height != birthdayHeight - 1) { + throw StateError( + 'birthday tree state height ${treeState.height} does not precede ' + 'restore height $birthdayHeight', + ); + } + final state = zcash.ZcashWalletSyncState.atBirthday( + cursor: zcash.ZcashLightwalletdSyncCursor.fromTreeState(treeState), + network: zcash.ZcashAddressNetwork.fromJson(network), + accountFingerprint: accountFingerprint, + transparent: accountMetadata == null || viewingKeys == null + ? null + : zcash.ZcashTransparentState.fromAccount( + account: accountMetadata, + viewingKeys: viewingKeys, + additionalReceivers: additionalTransparentReceivers, + ), + ); + persisted = ZcashPersistedWalletState( + syncState: state, + observedChainHeight: treeState.height, + ); + await store.save(persisted); + } + if (persisted.syncState.accountFingerprint != accountFingerprint) { + throw const ZcashStatePersistenceException( + 'wallet state belongs to a different account', + ); + } + if (persisted.syncState.cursor.nextHeight < birthdayHeight) { + throw const ZcashStatePersistenceException( + 'wallet state precedes the validated restore height', + ); + } + if (accountMetadata != null && viewingKeys != null) { + if (accountMetadata.fingerprint != accountFingerprint) { + throw const ZcashStatePersistenceException( + 'native account metadata does not match the wallet fingerprint', + ); + } + persisted.syncState.transparent.registerAccountReceivers( + account: accountMetadata, + viewingKeys: viewingKeys, + additionalReceivers: additionalTransparentReceivers, + ); + await store.save(persisted); + } + final sync = openSync(persisted.syncState, scanExecutor); + final times = (blockTimes ?? ZcashBlockTimes()) + ..clear() + ..restore(persisted.blockTimes); + return ZcashWalletStateController._( + store, + persisted.syncState, + sync, + persisted.observedChainHeight, + refreshTransparent, + transparentActivity, + transparentDiscovery, + accountMetadata, + viewingKeys, + birthdayHeight, + persisted.transparentHistoryFrontiers, + loadBirthdayTreeState, + scanExecutor, + openSync, + times, + ); + } + + ZcashWalletSnapshot get snapshot => ZcashWalletSnapshot( + chainHeight: _observedChainHeight, + balance: _state.balance(), + history: _state.history(), + blockTimes: _blockTimes.toMap(), + spendableNotes: spendableNotes, + unanchoredNotes: unanchoredNotes, + ); + + /// See [ZcashWalletSnapshot.spendableNotes]. + Map get spendableNotes => + ZcashWalletSnapshot.spendableNotesOf(_state); + + /// See [ZcashWalletSnapshot.unanchoredNotes]. + Set get unanchoredNotes => + ZcashWalletSnapshot.unanchoredNotesOf(_state, _observedChainHeight); + + Future refresh({ + ZcashRecoveryCancellationToken? cancellation, + }) { + final active = _refreshInFlight; + if (active != null) return active; + final future = _refresh(cancellation); + _refreshInFlight = future; + future.whenComplete(() { + if (identical(_refreshInFlight, future)) _refreshInFlight = null; + }).ignore(); + return future; + } + + Future _refresh( + ZcashRecoveryCancellationToken? cancellation, + ) async { + cancellation?.throwIfCancelled(); + late int caughtUpHeight; + var recoveryCycles = 0; + var restartedFromBirthday = false; + var ranges = 0; + // The shielded and the transparent pass each ask the node for its tip. + // A block that arrives between them sends the sync round again. + tipLoop: + for (var round = 1; ; round++) { + syncLoop: + while (true) { + final zcash.ZcashSyncOutcome outcome; + try { + outcome = await _sync.syncToTip( + onAdvanced: () async { + if (++ranges % checkpointRanges == 0) { + await _saveState(cancellation); + } + }, + ); + cancellation?.throwIfCancelled(); + } on zcash.ZcashReorgTooDeepException catch (error) { + if (restartedFromBirthday || + recoveryCycles >= maximumRecoveryCyclesPerRefresh) { + throw ZcashRecoveryLimitException( + attempts: recoveryCycles, + cause: error, + ); + } + recoveryCycles++; + restartedFromBirthday = true; + await _restartFromBirthday(cancellation); + cancellation?.throwIfCancelled(); + continue syncLoop; + } + switch (outcome) { + case zcash.ZcashSyncCaughtUp(:final chainHeight): + final scannedThrough = _state.cursor.nextHeight - 1; + if (chainHeight < scannedThrough) { + throw StateError( + 'lightwalletd tip $chainHeight is behind persisted scan ' + 'position $scannedThrough', + ); + } + caughtUpHeight = chainHeight; + break syncLoop; + case zcash.ZcashSyncReorged(:final recovery): + if (recoveryCycles >= maximumRecoveryCyclesPerRefresh) { + throw ZcashRecoveryLimitException( + attempts: recoveryCycles, + cause: outcome, + ); + } + recoveryCycles++; + if (recovery.forkHeight < _birthdayHeight - 1) { + if (restartedFromBirthday) { + throw ZcashRecoveryLimitException( + attempts: recoveryCycles, + cause: outcome, + ); + } + restartedFromBirthday = true; + await _restartFromBirthday(cancellation); + cancellation?.throwIfCancelled(); + continue syncLoop; + } + final sync = _sync; + if (sync is! ZcashReorgRecoverableSyncSession) { + throw ZcashReorgDetectedException(outcome); + } + _state.sapling.rollbackTo(recovery.forkHeight); + _state.orchard.rollbackTo(recovery.forkHeight); + _state.ironwood.rollbackTo(recovery.forkHeight); + final transparentHeight = _state.transparent.refreshedThroughHeight; + if (transparentHeight != null && + transparentHeight > recovery.forkHeight) { + _state.transparent.rollbackTo( + height: recovery.forkHeight, + blockHash: recovery.forkBlockHash, + ); + } else if (transparentHeight == recovery.forkHeight && + _state.transparent.refreshedThroughBlockHash != + recovery.forkBlockHash) { + throw StateError( + 'transparent state disagrees with the authenticated reorg ' + 'fork', + ); + } + cancellation?.throwIfCancelled(); + await sync.resumeFrom(recovery); + cancellation?.throwIfCancelled(); + _observedChainHeight = recovery.forkHeight; + final rewindHeight = recovery.forkHeight; + _transparentHistoryFrontiers = { + for (final entry in _transparentHistoryFrontiers.entries) + entry.key: entry.value > rewindHeight + ? rewindHeight + : entry.value, + }; + await _saveState(cancellation); + continue syncLoop; + case zcash.ZcashSyncAdvanced(): + throw StateError( + 'syncToTip returned before reaching a terminal state', + ); + } + } + final refreshTransparent = _refreshTransparent; + if (_state.transparent.addresses.isNotEmpty) { + if (refreshTransparent == null) { + throw StateError( + 'transparent receivers require lightwalletd transparent refresh', + ); + } + final transparentHistory = await _discoverTransparentReceivers( + caughtUpHeight, + cancellation, + ); + cancellation?.throwIfCancelled(); + var refresh = await refreshTransparent(_state.transparent); + cancellation?.throwIfCancelled(); + refresh = mergeAuthenticatedTransparentHistory( + state: _state.transparent, + refresh: refresh, + transactions: transparentHistory.transactions, + ); + if (refresh.chainHeight != caughtUpHeight) { + if (refresh.chainHeight > caughtUpHeight && + round < maximumTipRounds) { + continue tipLoop; + } + throw StateError( + 'shielded sync reached $caughtUpHeight while transparent refresh ' + 'reached ${refresh.chainHeight}', + ); + } + _state.transparent.applyRefresh(refresh); + // The queried ranges become durable only after their transactions and + // canonical blocks have passed merge validation and state application. + _transparentHistoryFrontiers = transparentHistory.frontiers; + } + break tipLoop; + } + cancellation?.throwIfCancelled(); + _observedChainHeight = caughtUpHeight; + await _saveState(cancellation); + cancellation?.throwIfCancelled(); + return snapshot; + } + + Future _restartFromBirthday( + ZcashRecoveryCancellationToken? cancellation, + ) async { + final retainedReceivers = _state.transparent.receivers; + final treeState = await _loadBirthdayTreeState(_birthdayHeight - 1); + cancellation?.throwIfCancelled(); + if (treeState.height != _birthdayHeight - 1) { + throw StateError( + 'birthday tree state height ${treeState.height} does not precede ' + 'restore height $_birthdayHeight', + ); + } + final account = _accountMetadata; + final viewingKeys = _viewingKeys; + final defaultAddress = viewingKeys?.transparent.defaultExternalAddress; + final state = zcash.ZcashWalletSyncState.atBirthday( + cursor: zcash.ZcashLightwalletdSyncCursor.fromTreeState(treeState), + network: zcash.ZcashAddressNetwork.fromJson(_store.network), + accountFingerprint: _store.accountFingerprint, + transparent: account == null || viewingKeys == null + ? null + : zcash.ZcashTransparentState.fromAccount( + account: account, + viewingKeys: viewingKeys, + additionalReceivers: retainedReceivers.where( + (receiver) => receiver.address != defaultAddress, + ), + ), + ); + final sync = _openSync(state, _scanExecutor); + final replacement = ZcashPersistedWalletState( + syncState: state, + observedChainHeight: treeState.height, + ); + // The encrypted store replaces its file by atomic rename. Keep both the + // durable and in-memory checkpoints on the old chain until the complete + // birthday state and its new sync session have been validated and saved. + cancellation?.throwIfCancelled(); + _requireOpen(); + await _store.save(replacement); + cancellation?.throwIfCancelled(); + _state = state; + _sync = sync; + _observedChainHeight = treeState.height; + _transparentHistoryFrontiers = {}; + _blockTimes.clear(); + } + + Future<_ZcashTransparentHistoryDiscovery> _discoverTransparentReceivers( + int chainHeight, + ZcashRecoveryCancellationToken? cancellation, + ) async { + final discover = _transparentDiscovery; + final activity = _transparentActivity; + final account = _accountMetadata; + final viewingKeys = _viewingKeys; + if (discover == null || + activity == null || + account == null || + viewingKeys == null) { + return _ZcashTransparentHistoryDiscovery( + transactions: const [], + frontiers: _transparentHistoryFrontiers, + ); + } + + // Keep progress speculative until the enclosing refresh authenticates and + // applies every result, then persist it atomically with the wallet state. + final nextFrontiers = Map.of(_transparentHistoryFrontiers); + + final knownByAddress = { + for (final receiver in _state.transparent.receivers) + receiver.address: receiver, + }; + final initialActivity = await _loadTransparentActivity( + activity, + knownByAddress.keys.toList(growable: false), + chainHeight, + nextFrontiers, + cancellation, + ); + cancellation?.throwIfCancelled(); + _validateTransparentActivity( + initialActivity.activeAddresses, + knownByAddress.keys.toSet(), + ); + final activeAddresses = initialActivity.activeAddresses.toSet(); + final transactions = {}; + void recordTransactions( + Iterable additions, + ) { + for (final transaction in additions) { + final existing = transactions[transaction.summary.txid]; + if (existing != null && + (existing.height != transaction.height || + existing.blockHash != transaction.blockHash)) { + throw StateError( + 'lightwalletd returned conflicting authentication for one ' + 'transparent transaction', + ); + } + transactions[transaction.summary.txid] = transaction; + if (transactions.length > 10000) { + throw StateError( + 'transparent history exceeds the bounded 10000-transaction limit', + ); + } + } + } + + recordTransactions(initialActivity.transactions); + + while (true) { + final additions = []; + for (final scope in zcash.ZcashTransparentReceiverScope.values) { + final scoped = + knownByAddress.values + .where((receiver) => receiver.scope == scope) + .toList() + ..sort((a, b) => a.childIndex.compareTo(b.childIndex)); + var contiguousThrough = -1; + for (final receiver in scoped) { + if (receiver.childIndex != contiguousThrough + 1) break; + contiguousThrough = receiver.childIndex; + } + final activeChildren = scoped + .where((receiver) => activeAddresses.contains(receiver.address)) + .map((receiver) => receiver.childIndex); + final highestActive = activeChildren.isEmpty + ? -1 + : activeChildren.reduce((a, b) => a > b ? a : b); + final requestedThrough = + (highestActive < 0 + ? discover.gapLimit - 1 + : highestActive + discover.gapLimit) + .clamp(0, discover.hardChildLimit - 1); + if (requestedThrough > contiguousThrough) { + additions.addAll( + discover.deriveRange( + scope, + contiguousThrough + 1, + requestedThrough + 1, + ), + ); + } + } + if (additions.isEmpty) { + return _ZcashTransparentHistoryDiscovery( + transactions: transactions.values.toList(growable: false), + frontiers: Map.unmodifiable(nextFrontiers), + ); + } + + cancellation?.throwIfCancelled(); + _state.transparent.registerAccountReceivers( + account: account, + viewingKeys: viewingKeys, + additionalReceivers: additions, + ); + for (final receiver in additions) { + knownByAddress[receiver.address] = receiver; + } + await _saveState(cancellation); + final additionalActivity = await _loadTransparentActivity( + activity, + additions.map((receiver) => receiver.address).toList(growable: false), + chainHeight, + nextFrontiers, + cancellation, + ); + cancellation?.throwIfCancelled(); + _validateTransparentActivity( + additionalActivity.activeAddresses, + additions.map((receiver) => receiver.address).toSet(), + ); + activeAddresses.addAll(additionalActivity.activeAddresses); + recordTransactions(additionalActivity.transactions); + } + } + + Future _loadTransparentActivity( + ZcashTransparentActivityCallback activity, + List addresses, + int chainHeight, + Map nextFrontiers, + ZcashRecoveryCancellationToken? cancellation, + ) async { + final byStartHeight = >{}; + final initialFrontier = _birthdayHeight <= chainHeight + ? _birthdayHeight - 1 + : chainHeight - 1; + for (final address in addresses) { + final frontier = nextFrontiers[address] ?? initialFrontier; + if (frontier > chainHeight) { + throw StateError( + 'transparent history frontier $frontier is above chain tip ' + '$chainHeight', + ); + } + final startHeight = frontier + 1; + if (startHeight <= chainHeight) { + (byStartHeight[startHeight] ??= []).add(address); + } + } + + final active = {}; + final transactions = []; + for (final entry in byStartHeight.entries) { + final result = await activity(entry.value, entry.key, chainHeight); + cancellation?.throwIfCancelled(); + _validateTransparentActivity(result.activeAddresses, entry.value.toSet()); + active.addAll(result.activeAddresses); + transactions.addAll(result.transactions); + for (final address in entry.value) { + nextFrontiers[address] = chainHeight; + } + } + return ZcashTransparentActivityResult( + activeAddresses: active, + transactions: transactions, + ); + } + + /// Stops this controller from saving. A sync that is still running when + /// its wallet closes would otherwise write the state file again, after a + /// deleted wallet's files are gone. + void close() => _closed = true; + + bool _closed = false; + + void _requireOpen() { + if (_closed) throw StateError('This Zcash wallet state is closed'); + } + + Future _saveState(ZcashRecoveryCancellationToken? cancellation) async { + cancellation?.throwIfCancelled(); + _requireOpen(); + _blockTimes.retainHeights({ + for (final entry in _state.history().entries) entry.height, + }); + await _store.save( + ZcashPersistedWalletState( + syncState: _state, + observedChainHeight: _observedChainHeight, + transparentHistoryFrontiers: _transparentHistoryFrontiers, + blockTimes: _blockTimes.toMap(), + ), + ); + cancellation?.throwIfCancelled(); + } + + static void _validateTransparentActivity( + Set active, + Set queried, + ) { + if (active.difference(queried).isNotEmpty) { + throw StateError( + 'lightwalletd returned activity for an unqueried transparent address', + ); + } + } +} + +zcash.ZcashTransparentRefresh mergeAuthenticatedTransparentHistory({ + required zcash.ZcashTransparentState state, + required zcash.ZcashTransparentRefresh refresh, + required List transactions, +}) { + if (transactions.isEmpty) return refresh; + final canonicalHashes = {...refresh.canonicalBlockHashes}; + final byProtocolTxid = {}; + for (final transaction in transactions) { + if (transaction.summary.network != state.network || + transaction.height < 1 || + transaction.height > refresh.chainHeight) { + throw StateError( + 'authenticated transparent transaction has invalid chain context', + ); + } + final existingHash = canonicalHashes[transaction.height]; + if (existingHash != null && existingHash != transaction.blockHash) { + throw StateError( + 'transparent history conflicts with an authenticated canonical block', + ); + } + canonicalHashes[transaction.height] = transaction.blockHash; + final protocolTxid = zcash.reverseTxidByteOrder( + normalizeZcashTransactionId(transaction.summary.txid), + ); + final existing = byProtocolTxid[protocolTxid]; + if (existing != null && + (existing.height != transaction.height || + existing.blockHash != transaction.blockHash)) { + throw StateError( + 'transparent history authenticates one transaction twice differently', + ); + } + byProtocolTxid[protocolTxid] = transaction; + } + + final knownAddresses = state.addresses.toSet(); + final ownedOutputs = + < + String, + ({ + zcash.ZcashTransparentOutputSummary output, + ZcashAuthenticatedTransparentTransaction transaction, + }) + >{}; + for (final entry in byProtocolTxid.entries) { + for (final output in entry.value.summary.transparent.outputs) { + if (output.address case final address? + when knownAddresses.contains(address)) { + final outpoint = '${entry.key}:${output.outputIndex}'; + final existing = ownedOutputs[outpoint]; + if (existing != null && + (existing.output.address != output.address || + existing.output.scriptHex != output.scriptHex || + existing.output.valueZatoshis != output.valueZatoshis || + existing.transaction.height != entry.value.height || + existing.transaction.blockHash != entry.value.blockHash)) { + throw StateError( + 'transparent history returned conflicting owned outpoint data', + ); + } + ownedOutputs[outpoint] = (output: output, transaction: entry.value); + } + } + } + + final spends = { + for (final spend in refresh.observedSpends) spend.spentOutpoint: spend, + }; + final persistedOwnedOutputs = { + for (final output in state.outputs) output.outpoint: output, + }; + for (final entry in byProtocolTxid.entries) { + for (final input in entry.value.summary.transparent.inputs) { + final prevoutTxid = zcash.reverseTxidByteOrder( + normalizeZcashTransactionId(input.prevoutTxid), + ); + final outpoint = '$prevoutTxid:${input.prevoutIndex}'; + final persistedOutput = persistedOwnedOutputs[outpoint]; + if (!ownedOutputs.containsKey(outpoint) && persistedOutput == null) { + continue; + } + final observed = zcash.ZcashTransparentSpendObservation( + spentOutpoint: outpoint, + spendingProtocolTxid: entry.key, + spentHeight: entry.value.height, + blockHash: entry.value.blockHash, + blockTime: entry.value.blockTime, + feeZatoshis: null, + ); + if (persistedOutput?.spendingProtocolTxid case final spendingTxid? + when spendingTxid != observed.spendingProtocolTxid || + persistedOutput!.spentHeight != observed.spentHeight || + persistedOutput.spentBlockHash != observed.blockHash) { + throw StateError( + 'transparent history conflicts with the persisted spend for one ' + 'outpoint', + ); + } + final existing = spends[outpoint]; + if (existing != null && + (existing.spendingProtocolTxid != observed.spendingProtocolTxid || + existing.spentHeight != observed.spentHeight || + existing.blockHash != observed.blockHash)) { + throw StateError( + 'transparent history returned conflicting spends for one outpoint', + ); + } + spends[outpoint] = observed; + } + } + + final unspentOutpoints = { + for (final output in refresh.unspentOutputs) output.outpoint, + }; + final historicalOutputs = []; + for (final entry in ownedOutputs.entries) { + if (unspentOutpoints.contains(entry.key) || + !spends.containsKey(entry.key)) { + continue; + } + final output = entry.value.output; + final transaction = entry.value.transaction; + historicalOutputs.add( + zcash.ZcashTransparentOutputObservation( + address: output.address!, + protocolTxid: zcash.reverseTxidByteOrder( + normalizeZcashTransactionId(transaction.summary.txid), + ), + outputIndex: output.outputIndex, + scriptHex: output.scriptHex, + valueZatoshis: output.valueZatoshis, + minedHeight: transaction.height, + blockHash: transaction.blockHash, + blockTime: transaction.blockTime, + isCoinbase: transaction.summary.transparent.isCoinbase, + ), + ); + } + return zcash.ZcashTransparentRefresh( + network: refresh.network, + accountFingerprint: refresh.accountFingerprint, + queriedAddresses: refresh.queriedAddresses, + chainHeight: refresh.chainHeight, + chainTipHash: refresh.chainTipHash, + canonicalBlockHashes: canonicalHashes, + unspentOutputs: refresh.unspentOutputs, + historicalOutputs: historicalOutputs, + observedSpends: spends.values.toList(growable: false), + ); +} + +abstract interface class ZcashSyncDataSource { + Future getTipHeight(); + + Future getBlockRange(int start, int end); + + Future getTreeState(int height); + + Future getBlockHash(int height); +} + +ZcashSyncSession openZcashSyncSession({ + required zcash.ZcashWalletSyncState state, + required ZcashSyncDataSource source, + required ZcashScanExecutor scanExecutor, + required String network, + void Function()? checkCancellation, + ZcashBlockTimes? blockTimes, + int rangeSize = 100, +}) { + Future checked(Future Function() operation) async { + checkCancellation?.call(); + final result = await operation(); + checkCancellation?.call(); + return result; + } + + return _ZcashChainSyncSession( + state.syncThrough( + chainTip: () => checked(source.getTipHeight), + fetchRange: (start, end) => checked(() async { + final range = await source.getBlockRange(start, end); + blockTimes?.record(range); + return range; + }), + fetchTreeState: (height) => checked(() => source.getTreeState(height)), + servedBlockHashAt: (height) => checked(() => source.getBlockHash(height)), + scan: (envelope) => checked(() => scanExecutor.scan(envelope)), + network: network, + rangeSize: rangeSize, + ), + source, + checkCancellation, + ); +} + +class _ZcashChainSyncSession implements ZcashReorgRecoverableSyncSession { + const _ZcashChainSyncSession( + this._sync, + this._source, + this._checkCancellation, + ); + + final zcash.ZcashChainSync _sync; + final ZcashSyncDataSource _source; + final void Function()? _checkCancellation; + + @override + Future syncToTip({ + Future Function()? onAdvanced, + }) async { + while (true) { + final outcome = await _sync.step(); + if (outcome is! zcash.ZcashSyncAdvanced) return outcome; + await onAdvanced?.call(); + } + } + + @override + Future resumeFrom(zcash.ZcashReorgRecovery recovery) async { + _checkCancellation?.call(); + final treeState = await _source.getTreeState(recovery.forkHeight); + _checkCancellation?.call(); + _sync.resumeFrom(recovery: recovery, treeState: treeState); + _checkCancellation?.call(); + } +} diff --git a/lib/wallets/wallet/wallet.dart b/lib/wallets/wallet/wallet.dart index 7a8f79c9d..21385508a 100644 --- a/lib/wallets/wallet/wallet.dart +++ b/lib/wallets/wallet/wallet.dart @@ -53,6 +53,7 @@ import 'impl/sub_wallets/solana_token_wallet.dart'; import 'impl/tezos_wallet.dart'; import 'impl/wownero_wallet.dart'; import 'impl/xelis_wallet.dart'; +import 'impl/zcash_wallet.dart'; import 'intermediate/cryptonote_wallet.dart'; import 'wallet_mixin_interfaces/electrumx_interface.dart'; import 'wallet_mixin_interfaces/mnemonic_interface.dart'; @@ -432,6 +433,9 @@ abstract class Wallet { case const (Xelis): return XelisWallet(net); + case const (Zcash): + return ZcashWallet(walletInfo.coin as Zcash); + default: // should never hit in reality throw Exception("Unknown crypto currency: ${walletInfo.coin}"); diff --git a/pubspec.lock b/pubspec.lock index 1a56118de..d67106534 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -420,7 +420,7 @@ packages: source: hosted version: "3.0.7" cryptography: - dependency: transitive + dependency: "direct main" description: name: cryptography sha256: "3eda3029d34ec9095a27a198ac9785630fe525c0eb6a49f3d575272f8e792ef0" @@ -2746,6 +2746,24 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.0" + zcash: + dependency: "direct overridden" + description: + path: "packages/zcash" + ref: c8bc869ba9ba0227f944329df9e875d2a55c5983 + resolved-ref: c8bc869ba9ba0227f944329df9e875d2a55c5983 + url: "https://github.com/ManyMath/zcash.git" + source: git + version: "0.0.8" + zcash_flutter: + dependency: "direct main" + description: + path: "packages/zcash_flutter" + ref: c8bc869ba9ba0227f944329df9e875d2a55c5983 + resolved-ref: c8bc869ba9ba0227f944329df9e875d2a55c5983 + url: "https://github.com/ManyMath/zcash.git" + source: git + version: "0.0.3" zxcvbn: dependency: "direct main" description: diff --git a/scripts/app_config/configure_stack_wallet.sh b/scripts/app_config/configure_stack_wallet.sh index 6f41d27b7..3503b3a2e 100755 --- a/scripts/app_config/configure_stack_wallet.sh +++ b/scripts/app_config/configure_stack_wallet.sh @@ -31,7 +31,8 @@ dart "${APP_PROJECT_ROOT_DIR}/tool/process_pubspec_deps.dart" \ EPIC \ FIRO \ XEL \ - FROST + FROST \ + ZCASH dart "${APP_PROJECT_ROOT_DIR}/tool/gen_interfaces.dart" \ "${APP_PROJECT_ROOT_DIR}/tool/wl_templates" \ diff --git a/scripts/app_config/templates/pubspec.template.yaml b/scripts/app_config/templates/pubspec.template.yaml index b02fa80fc..1db92f351 100644 --- a/scripts/app_config/templates/pubspec.template.yaml +++ b/scripts/app_config/templates/pubspec.template.yaml @@ -64,6 +64,16 @@ dependencies: # ref: d4852f3ebaaef20d71a8954098634af8e25c3b50 # %%END_ENABLE_MWC%% +# zcash_flutter re-exports the Zcash wallet API and builds the zcash-ffi Rust +# library in its hook. Every app depends on it because lib/ uses that API +# directly; the ZCASH flag decides whether the library is built and bundled +# (hooks.user_defines below). + zcash_flutter: + git: + url: https://github.com/ManyMath/zcash.git + path: packages/zcash_flutter + ref: c8bc869ba9ba0227f944329df9e875d2a55c5983 + # %%ENABLE_TOR%% # tor_ffi_plugin: # git: @@ -175,6 +185,7 @@ dependencies: event_bus: ^2.0.0 uuid: ^4.5.2 crypto: ^3.0.2 + cryptography: ^2.9.0 image: ^4.3.0 wakelock_plus: ^1.2.8 intl: ^0.19.0 @@ -311,6 +322,15 @@ flutter_native_splash: color_dark: "2A2D34" dependency_overrides: + # zcash_flutter depends on the hosted zcash package. Take both packages from + # the same commit, whose lightwalletd stubs are generated for the protobuf 4 + # and grpc 4 that the MWEB and CashFusion packages resolve. + zcash: + git: + url: https://github.com/ManyMath/zcash.git + path: packages/zcash + ref: c8bc869ba9ba0227f944329df9e875d2a55c5983 + # required for: native_toolchain_rust >=1.0.3 depends on toml ^0.18.0 # stellar sdk package needs to get 0.18.0 to remove this override toml: ^0.18.0 @@ -384,6 +404,10 @@ hooks: flutter_libmwc: build: PLACEHOLDER_DNIX_BUILD_MODE wsl_distribution: PLACEHOLDER_DNIX_WSL_DISTRIBUTION + # Not a dnix package. process_pubspec_deps.dart sets this to true only for + # apps configured with ZCASH; the others neither build nor bundle zcash-ffi. + zcash_flutter: + enabled: PLACEHOLDER_IF_ZCASH # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/scripts/tests/native_build_config_test.dart b/scripts/tests/native_build_config_test.dart index ab215d173..4be98f183 100644 --- a/scripts/tests/native_build_config_test.dart +++ b/scripts/tests/native_build_config_test.dart @@ -221,6 +221,11 @@ void main(List args) { ) as YamlMap; final dependencies = (pubspec['dependencies'] as YamlMap).keys.toSet(); expect(dependencies.intersection(allPackages), enabledDnixPackages(app)); + final defines = (pubspec['hooks'] as YamlMap)['user_defines'] as YamlMap; + expect(dependencies, contains('zcash_flutter')); + expect(defines['zcash_flutter'], { + 'enabled': app == 'stack_wallet', + }, reason: 'only an app configured with ZCASH builds zcash-ffi'); } } @@ -228,7 +233,7 @@ void main(List args) { final text = File(p.join(root.path, 'pubspec.yaml')).readAsStringSync(); final pubspec = loadYaml(text) as YamlMap; final defines = (pubspec['hooks'] as YamlMap)['user_defines'] as YamlMap; - expect(defines.keys.toSet(), allPackages); + expect(defines.keys.toSet(), {...allPackages, 'zcash_flutter'}); for (final package in allPackages) { expect(defines[package], { 'build': mode, @@ -236,6 +241,7 @@ void main(List args) { }); } expect(text, isNot(contains('PLACEHOLDER_DNIX_BUILD_MODE'))); + expect(text, isNot(contains('PLACEHOLDER_IF_'))); expect(text, isNot(contains('native_build:'))); expect(text, isNot(contains('prebuilt_manifest_'))); expect(text, isNot(contains('PLACEHOLDER_DNIX_WSL_DISTRIBUTION'))); diff --git a/test/utilities/native_library_check_test.dart b/test/utilities/native_library_check_test.dart index 7a8d0ad40..a2d6061b7 100644 --- a/test/utilities/native_library_check_test.dart +++ b/test/utilities/native_library_check_test.dart @@ -2,8 +2,10 @@ import 'dart:io'; import 'package:flutter_test/flutter_test.dart'; import 'package:logger/logger.dart'; +import 'package:stackwallet/app_config.dart'; import 'package:stackwallet/utilities/logger.dart'; import 'package:stackwallet/utilities/native_library_check.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; const _exe = r"C:\Program Files\Stack Wallet\stack_wallet.exe"; const _dll = "monero_libwallet2_api_c.dll"; @@ -140,6 +142,24 @@ void main() { expect(failures.first.result.path, _path); }); + test("a missing Zcash library is reported only in an app with Zcash", () { + addTearDown(() => AppConfig.coinsOverride = null); + final others = AppConfig.coins.where((coin) => coin is! Zcash).toList(); + + // Stack Duo and Campfire do not build or bundle it. + AppConfig.coinsOverride = others; + expect(_startup({"zcash_ffi.dll"}), isEmpty); + + AppConfig.coinsOverride = [...others, Zcash(CryptoCurrencyNetwork.main)]; + final failures = _startup({"zcash_ffi.dll"}); + expect(failures.map((f) => f.displayName), ["Zcash wallets"]); + expect(failures.single.result.problem, NativeLibraryProblem.missing); + expect( + failures.single.result.path, + r"C:\Program Files\Stack Wallet\zcash_ffi.dll", + ); + }); + test("failures are handed over once", () { _startup({_dll}); expect(takeNativeLibraryFailures(), isEmpty); diff --git a/test/wallets/support/zcash_test_coins.dart b/test/wallets/support/zcash_test_coins.dart new file mode 100644 index 000000000..e9ec432e0 --- /dev/null +++ b/test/wallets/support/zcash_test_coins.dart @@ -0,0 +1,18 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/app_config.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; + +/// Lists every Zcash network in [AppConfig.coins] for the tests of the calling +/// file, so that a [WalletInfo] can name one. An app config lists mainnet at +/// most, and never regtest. +void listZcashCoins() { + setUpAll(() { + AppConfig.coinsOverride = [ + ...AppConfig.coins.where((coin) => coin is! Zcash), + Zcash(CryptoCurrencyNetwork.main), + Zcash(CryptoCurrencyNetwork.test), + Zcash.regtest(), + ]; + }); + tearDownAll(() => AppConfig.coinsOverride = null); +} diff --git a/test/wallets/zcash_account_session_test.dart b/test/wallets/zcash_account_session_test.dart new file mode 100644 index 000000000..9acf2a5e0 --- /dev/null +++ b/test/wallets/zcash_account_session_test.dart @@ -0,0 +1,434 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/models/node_model.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_account_session.dart'; +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +class FakeLightwalletdClient implements ZcashLightwalletdClient { + FakeLightwalletdClient({ + required this.chainName, + required this.tipHeight, + this.infoError, + this.neverInfo = false, + this.neverTip = false, + this.infoCompleter, + }); + + final String chainName; + final int tipHeight; + final Object? infoError; + bool neverInfo; + bool neverTip; + final Completer? infoCompleter; + int infoCalls = 0; + int tipCalls = 0; + int closeCalls = 0; + + @override + Future getInfo() async { + infoCalls++; + if (infoError case final error?) throw error; + if (infoCompleter case final completer?) return completer.future; + if (neverInfo) return Completer().future; + return zcash.LightdInfo(chainName: chainName); + } + + @override + Future getTipHeight() async { + tipCalls++; + if (neverTip) return Completer().future; + return tipHeight; + } + + @override + Future close() async { + closeCalls++; + } +} + +class SubmittingLightwalletdClient extends FakeLightwalletdClient + implements ZcashLightwalletdSendClient { + SubmittingLightwalletdClient({ + this.errorCode = 0, + this.errorMessage = '', + this.neverSubmit = false, + }) : super(chainName: 'main', tipHeight: 42); + + final int errorCode; + final String errorMessage; + final bool neverSubmit; + final List submitted = []; + + @override + Future submitTransaction( + Uint8List transaction, + ) async { + submitted.add(Uint8List.fromList(transaction)); + if (neverSubmit) { + return Completer().future; + } + return ZcashSubmissionAcknowledgement( + errorCode: errorCode, + errorMessage: errorMessage, + ); + } +} + +NodeModel node({ + String host = 'https://lightwalletd.example', + int port = 443, + bool useSSL = true, +}) => NodeModel( + host: host, + port: port, + name: 'fixture', + id: 'fixture-node', + useSSL: useSSL, + enabled: true, + coinName: 'zcash', + isFailover: false, + isDown: false, + torEnabled: false, + clearnetEnabled: true, + isPrimary: true, +); + +void main() { + test( + 'submits exact prepared bytes and returns an explicit acknowledgement', + () async { + final client = SubmittingLightwalletdClient(); + final session = ZcashAccountSession( + network: zcash.ZcashNetwork.mainnet, + clientFactory: (_) => client, + ); + await session.replaceNode(node()); + + final acknowledgement = await session.submitTransactionHex('00ff10'); + + expect(client.submitted, [ + Uint8List.fromList([0, 255, 16]), + ]); + expect(acknowledgement.accepted, isTrue); + expect(acknowledgement.errorCode, 0); + await session.close(); + }, + ); + + test('surfaces lightwalletd rejection explicitly', () async { + final client = SubmittingLightwalletdClient( + errorCode: -26, + errorMessage: 'bad-tx', + ); + final session = ZcashAccountSession( + network: zcash.ZcashNetwork.mainnet, + clientFactory: (_) => client, + ); + await session.replaceNode(node()); + + await expectLater( + session.submitTransactionHex('00'), + throwsA( + isA() + .having((e) => e.errorCode, 'errorCode', -26) + .having((e) => e.message, 'message', 'bad-tx'), + ), + ); + await session.close(); + }); + + test('bounds an indeterminate lightwalletd submission', () async { + final client = SubmittingLightwalletdClient(neverSubmit: true); + final session = ZcashAccountSession( + network: zcash.ZcashNetwork.mainnet, + clientFactory: (_) => client, + broadcastTimeout: const Duration(milliseconds: 10), + ); + await session.replaceNode(node()); + + await expectLater( + session.submitTransactionHex('00'), + throwsA( + isA().having( + (e) => e.phase, + 'phase', + 'sendTransaction', + ), + ), + ); + await session.close(); + }); + + test('opens a bounded ready session from a Stack node', () async { + final client = FakeLightwalletdClient(chainName: 'main', tipHeight: 42); + ZcashEndpoint? openedEndpoint; + final session = ZcashAccountSession( + network: zcash.ZcashNetwork.mainnet, + clientFactory: (endpoint) { + openedEndpoint = endpoint; + return client; + }, + requestTimeout: const Duration(milliseconds: 100), + ); + + final readiness = await session.replaceNode(node()); + + expect( + openedEndpoint, + const ZcashEndpoint( + host: 'lightwalletd.example', + port: 443, + useTls: true, + network: zcash.ZcashNetwork.mainnet, + ), + ); + expect(readiness.tipHeight, 42); + expect(client.infoCalls, 1); + expect(client.tipCalls, 1); + expect(client.closeCalls, 0); + + await session.close(); + expect(client.closeCalls, 1); + }); + + test( + 'a rejected replacement closes its client and retains the old one', + () async { + final oldClient = FakeLightwalletdClient( + chainName: 'main', + tipHeight: 42, + ); + final rejectedClient = FakeLightwalletdClient( + chainName: 'main', + tipHeight: 43, + infoError: StateError('not ready'), + ); + final clients = [oldClient, rejectedClient]; + final session = ZcashAccountSession( + network: zcash.ZcashNetwork.mainnet, + clientFactory: (_) => clients.removeAt(0), + requestTimeout: const Duration(milliseconds: 100), + ); + await session.replaceNode(node()); + + await expectLater( + session.replaceNode(node(host: 'replacement.example')), + throwsStateError, + ); + + expect(rejectedClient.closeCalls, 1); + expect(oldClient.closeCalls, 0); + expect(await session.ping(), isTrue); + expect(oldClient.infoCalls, 2); + expect(oldClient.tipCalls, 2); + }, + ); + + test('rejects and closes an endpoint on the wrong Zcash network', () async { + final client = FakeLightwalletdClient(chainName: 'test', tipHeight: 42); + final session = ZcashAccountSession( + network: zcash.ZcashNetwork.mainnet, + clientFactory: (_) => client, + requestTimeout: const Duration(milliseconds: 100), + ); + + await expectLater( + session.replaceNode(node()), + throwsA(isA()), + ); + expect(client.infoCalls, 1); + expect(client.tipCalls, 0); + expect(client.closeCalls, 1); + expect(await session.ping(), isFalse); + }); + + test('accepts lightwalletd test chain identity for regtest', () async { + final client = FakeLightwalletdClient(chainName: 'test', tipHeight: 42); + final session = ZcashAccountSession( + network: zcash.ZcashNetwork.regtest, + clientFactory: (_) => client, + requestTimeout: const Duration(milliseconds: 100), + ); + + final readiness = await session.replaceNode(node()); + + expect(readiness.info.chainName, 'test'); + expect(readiness.tipHeight, 42); + expect(client.closeCalls, 0); + }); + + test('a chain-name mismatch leaves the active client usable', () async { + final oldClient = FakeLightwalletdClient(chainName: 'main', tipHeight: 42); + final wrongNetwork = FakeLightwalletdClient( + chainName: 'test', + tipHeight: 43, + ); + final clients = [oldClient, wrongNetwork]; + final session = ZcashAccountSession( + network: zcash.ZcashNetwork.mainnet, + clientFactory: (_) => clients.removeAt(0), + requestTimeout: const Duration(milliseconds: 100), + ); + await session.replaceNode(node()); + + await expectLater( + session.replaceNode(node(host: 'testnet.example')), + throwsA(isA()), + ); + + expect(session.generation, 1); + expect(wrongNetwork.closeCalls, 1); + expect(oldClient.closeCalls, 0); + expect(await session.ping(), isTrue); + }); + + test('bounds getLightdInfo and closes the timed-out candidate', () async { + final client = FakeLightwalletdClient( + chainName: 'main', + tipHeight: 42, + neverInfo: true, + ); + final session = ZcashAccountSession( + network: zcash.ZcashNetwork.mainnet, + clientFactory: (_) => client, + requestTimeout: const Duration(milliseconds: 10), + ); + + await expectLater( + session.replaceNode(node()), + throwsA( + isA().having( + (error) => error.phase, + 'phase', + 'getLightdInfo', + ), + ), + ); + expect(client.closeCalls, 1); + }); + + test('bounds getTipHeight and closes the timed-out candidate', () async { + final client = FakeLightwalletdClient( + chainName: 'main', + tipHeight: 42, + neverTip: true, + ); + final session = ZcashAccountSession( + network: zcash.ZcashNetwork.mainnet, + clientFactory: (_) => client, + requestTimeout: const Duration(milliseconds: 10), + ); + + await expectLater( + session.replaceNode(node()), + throwsA( + isA().having( + (error) => error.phase, + 'phase', + 'getTipHeight', + ), + ), + ); + expect(client.closeCalls, 1); + }); + + test('bounds readiness when pinging the active client', () async { + final client = FakeLightwalletdClient(chainName: 'main', tipHeight: 42); + final session = ZcashAccountSession( + network: zcash.ZcashNetwork.mainnet, + clientFactory: (_) => client, + requestTimeout: const Duration(milliseconds: 10), + ); + await session.replaceNode(node()); + client.neverTip = true; + + expect(await session.ping(), isFalse); + expect(client.closeCalls, 0); + }); + + test('rejects ambiguous or contradictory Stack node endpoints', () { + final invalid = [ + node(host: ''), + node(host: 'https://lightwalletd.example', useSSL: false), + node(host: 'http://lightwalletd.example', useSSL: true), + node(host: 'https://user@lightwalletd.example'), + node(host: 'https://lightwalletd.example/rpc'), + node(host: 'https://lightwalletd.example?network=main'), + node(host: 'https://lightwalletd.example:9067', port: 443), + node(port: 0), + node(port: 65536), + ]; + + for (final value in invalid) { + expect( + () => ZcashEndpoint.fromNode(value, zcash.ZcashNetwork.mainnet), + throwsArgumentError, + reason: value.toString(), + ); + } + }); + + test( + 'successful replacement advances generation and closes exactly once', + () async { + final first = FakeLightwalletdClient(chainName: 'main', tipHeight: 42); + final second = FakeLightwalletdClient(chainName: 'main', tipHeight: 43); + final clients = [first, second]; + final session = ZcashAccountSession( + network: zcash.ZcashNetwork.mainnet, + clientFactory: (_) => clients.removeAt(0), + requestTimeout: const Duration(milliseconds: 100), + ); + + expect(session.generation, 0); + await session.replaceNode(node()); + expect(session.generation, 1); + await session.replaceNode(node(host: 'replacement.example')); + expect(session.generation, 2); + expect(first.closeCalls, 1); + expect(second.closeCalls, 0); + + await session.close(); + expect(session.generation, 3); + await session.close(); + expect(session.generation, 3); + expect(first.closeCalls, 1); + expect(second.closeCalls, 1); + }, + ); + + test('close prevents an in-flight replacement from installing', () async { + final active = FakeLightwalletdClient(chainName: 'main', tipHeight: 42); + final delayedInfo = Completer(); + final candidate = FakeLightwalletdClient( + chainName: 'main', + tipHeight: 43, + infoCompleter: delayedInfo, + ); + final clients = [active, candidate]; + final session = ZcashAccountSession( + network: zcash.ZcashNetwork.mainnet, + clientFactory: (_) => clients.removeAt(0), + requestTimeout: const Duration(milliseconds: 100), + ); + await session.replaceNode(node()); + + final replacement = session.replaceNode(node(host: 'delayed.example')); + await Future.delayed(Duration.zero); + expect(candidate.infoCalls, 1); + + await session.close(); + delayedInfo.complete(zcash.LightdInfo(chainName: 'main')); + + await expectLater(replacement, throwsStateError); + expect(session.generation, 2); + expect(active.closeCalls, 1); + expect(candidate.closeCalls, 1); + expect(await session.ping(), isFalse); + await session.close(); + expect(active.closeCalls, 1); + expect(candidate.closeCalls, 1); + }); +} diff --git a/test/wallets/zcash_address_type_test.dart b/test/wallets/zcash_address_type_test.dart new file mode 100644 index 000000000..d4f3dd746 --- /dev/null +++ b/test/wallets/zcash_address_type_test.dart @@ -0,0 +1,35 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; + +const _mainnetTransparent = 't1c8oqrzA1kYPdgVhfDNUZn3buAbk6rXxiX'; +const _mainnetSapling = + 'zs1zt3mq96vp65l8ch54r78nc50ml68qsyg3pkteq8pn8sfgza' + 'khgw4vqn6px5w08hrf2uzuam5kmj'; +const _mainnetUnified = + 'u1tcw2tuatlzdc4ncep4nef7v9h5q87jx7t4fzyj7sw5g6775u3fwkucjafgsl2dg6h3hfj' + 'tml85ggqakl5mf2c746ygk7qnp8kyhentqkcnpqwarfcceczd0drzuvtxaeak9kadkwp6sn5x' + 'pj40cwmpjcu8aqy6v8rueum0h9mvefhhfytvrq2dcwxsx4cdk7uzv99yhspftg72ut509'; + +void main() { + final zcash = Zcash(CryptoCurrencyNetwork.main); + + test('keeps existing persisted address type ordinals stable', () { + expect(AddressType.zcashUnified.index, 20); + expect(AddressType.zcashSapling.index, 21); + }); + + test('classifies supported standalone and unified Zcash addresses', () { + expect(zcash.getAddressType(_mainnetUnified), AddressType.zcashUnified); + expect(zcash.getAddressType(_mainnetSapling), AddressType.zcashSapling); + expect(zcash.getAddressType(_mainnetTransparent), AddressType.p2pkh); + }); + + test('rejects invalid or wrong-network Zcash addresses', () { + expect(zcash.getAddressType('not-an-address'), isNull); + expect( + Zcash(CryptoCurrencyNetwork.test).getAddressType(_mainnetTransparent), + isNull, + ); + }); +} diff --git a/test/wallets/zcash_coin_test.dart b/test/wallets/zcash_coin_test.dart new file mode 100644 index 000000000..acb263781 --- /dev/null +++ b/test/wallets/zcash_coin_test.dart @@ -0,0 +1,79 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/utilities/default_nodes.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +void main() { + final mainnet = Zcash(CryptoCurrencyNetwork.main); + final testnet = Zcash(CryptoCurrencyNetwork.test); + final regtest = Zcash.regtest(); + + test('each network has its own identity', () { + expect([mainnet, testnet, regtest].map((coin) => coin.identifier), [ + 'zcash', + 'zcashTestNet', + 'zcashRegtest', + ]); + expect( + [mainnet, testnet, regtest].map((coin) => coin.nativeNetwork), + zcash.ZcashNetwork.values, + ); + expect([mainnet, testnet, regtest].map((coin) => coin.mainNetId).toSet(), { + 'zcash', + }); + }); + + test('regtest is a test network that is not testnet', () { + expect(regtest.network, CryptoCurrencyNetwork.test); + expect(regtest, isNot(testnet)); + expect(regtest.hashCode, isNot(testnet.hashCode)); + expect(regtest, Zcash.regtest()); + expect(testnet, Zcash(CryptoCurrencyNetwork.test)); + expect({mainnet, testnet, regtest, Zcash.regtest()}, hasLength(3)); + }); + + test('other Stack Wallet networks are refused', () { + expect(() => Zcash(CryptoCurrencyNetwork.stage), throwsArgumentError); + expect(() => Zcash(CryptoCurrencyNetwork.test4), throwsArgumentError); + }); + + test('default nodes are lightwalletd endpoints for the right chain', () { + final nodes = { + for (final coin in [mainnet, testnet, regtest]) + coin: coin.defaultNode(isPrimary: true), + }; + + expect( + nodes.values.map((node) => '${node.host}:${node.port} ${node.useSSL}'), + [ + 'zec.rocks:443 true', + 'testnet.zec.rocks:443 true', + '127.0.0.1:9067 false', + ], + ); + for (final MapEntry(key: coin, value: node) in nodes.entries) { + expect(node.coinName, coin.identifier); + expect(node.id, DefaultNodes.buildId(coin)); + expect(node.isPrimary, isTrue); + expect(node.clearnetEnabled, isTrue); + expect(node.torEnabled, isFalse); + } + expect(mainnet.torSupport, isFalse); + }); + + test('mainnet and testnet transactions have an explorer', () { + const txid = + '0123456789abcdef0123456789abcdef' + '0123456789abcdef0123456789abcdef'; + + expect( + mainnet.defaultBlockExplorer(txid), + Uri.https('mainnet.zcashexplorer.app', '/transactions/$txid'), + ); + expect( + testnet.defaultBlockExplorer(txid), + Uri.https('testnet.zcashexplorer.app', '/transactions/$txid'), + ); + expect(() => regtest.defaultBlockExplorer(txid), throwsUnsupportedError); + }); +} diff --git a/test/wallets/zcash_history_mapping_test.dart b/test/wallets/zcash_history_mapping_test.dart new file mode 100644 index 000000000..1c376c12b --- /dev/null +++ b/test/wallets/zcash_history_mapping_test.dart @@ -0,0 +1,445 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/models/balance.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/transaction.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/v2/transaction_v2.dart'; +import 'package:stackwallet/wallets/wallet/impl/zcash_wallet.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_wallet_state_controller.dart'; +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +const _mapper = ZcashStackStateMapper(walletId: 'wallet-1'); + +final _receiveTxid = '22' * 32; +final _sendTxid = 'aa' * 32; +final _blockHash = 'bb' * 32; + +final _sourceNullifier = '11' * 32; +final _changeNullifier = '33' * 32; +final _otherNullifier = '44' * 32; + +/// A wallet that received ten million zatoshis at height 120 and, when +/// [sendMinedAt] is set, spent that note there for a payment of one million +/// and a fee of twenty thousand. With [otherNote], it also holds a second +/// note of five million. +/// +/// The notes are what a sync stores: a position in the note commitment tree +/// and no witness, which a send fetches for the notes it spends. +zcash.ZcashWalletSyncState _state({int? sendMinedAt, bool otherNote = false}) { + final sourceNullifier = _sourceNullifier; + final state = zcash.ZcashWalletSyncState.atBirthday( + cursor: zcash.ZcashLightwalletdSyncCursor.origin(height: 131), + network: zcash.ZcashAddressNetwork.regtest, + accountFingerprint: 'account-a', + ); + final scan = zcash.ZcashScanResult( + scannedBlocks: 2, + discoveredNotes: (sendMinedAt == null ? 1 : 2) + (otherNote ? 1 : 0), + totalValue: otherNote ? 15000000 : 10000000, + scannedHeightRange: const zcash.CompactBlockScanRange(start: 120, end: 131), + notes: [ + zcash.ZcashScannedNote( + height: 120, + tx: _receiveTxid, + output: 0, + value: 10000000, + pool: 'ironwood', + nullifier: sourceNullifier, + commitmentPosition: 0, + blockHash: _blockHash, + ), + if (otherNote) + zcash.ZcashScannedNote( + height: 120, + tx: _receiveTxid, + output: 1, + value: 5000000, + pool: 'ironwood', + nullifier: _otherNullifier, + commitmentPosition: 1, + blockHash: _blockHash, + ), + if (sendMinedAt != null) + zcash.ZcashScannedNote( + height: sendMinedAt, + tx: _sendTxid, + output: 0, + value: 8980000, + pool: 'ironwood', + nullifier: _changeNullifier, + commitmentPosition: 2, + blockHash: _blockHash, + ), + ], + spends: [ + if (sendMinedAt != null) + zcash.ZcashObservedSpend( + height: sendMinedAt, + tx: _sendTxid, + pool: 'ironwood', + nullifier: sourceNullifier, + index: 0, + ), + ], + ); + state.ironwood.apply(scan, accountFingerprint: 'account-a'); + return state; +} + +zcash.ZcashTransactionHistory _history({int? sendMinedAt}) => + _state(sendMinedAt: sendMinedAt).history(); + +/// What a sync of [_state] reports at height 131. +ZcashWalletSnapshot _snapshot({ + int? sendMinedAt, + bool otherNote = false, + Map blockTimes = const {}, +}) { + final state = _state(sendMinedAt: sendMinedAt, otherNote: otherNote); + return ZcashWalletSnapshot( + chainHeight: 131, + balance: state.balance(), + history: state.history(), + blockTimes: blockTimes, + spendableNotes: ZcashWalletSnapshot.spendableNotesOf(state), + unanchoredNotes: ZcashWalletSnapshot.unanchoredNotesOf(state, 131), + ); +} + +zcash.IronwoodPendingSendState _pending({ + String broadcastState = 'acknowledged', + int expiryHeight = 200, +}) => zcash.IronwoodPendingSendState.fromJson({ + 'pending_send_state_version': 2, + 'records': [ + { + 'pending_send_version': 3, + 'transaction': '00', + 'txid': _sendTxid, + 'selected_nullifiers': ['11' * 32], + 'source_pool': 'ironwood', + 'recipient': 'uregtest1destination', + 'actual_destination_pool': 'ironwood', + 'amount_zatoshis': 1000000, + 'fee_zatoshis': 20000, + 'expiry_height': expiryHeight, + 'created_height': 130, + 'broadcast_state': broadcastState, + 'payment_outputs': [ + { + 'encoded_recipient': 'uregtest1destination', + 'receiver_address': 'uregtest1destination', + 'actual_destination_pool': 'ironwood', + 'amount_zatoshis': 1000000, + }, + ], + }, + ], +}); + +TransactionV2 _row( + String txid, { + required int? height, + required int timestamp, + String? blockHash, +}) => TransactionV2( + walletId: 'wallet-1', + blockHash: blockHash, + hash: txid, + txid: txid, + timestamp: timestamp, + height: height, + inputs: const [], + outputs: const [], + version: -1, + type: TransactionType.incoming, + subType: TransactionSubType.none, + otherData: null, +); + +BigInt _sent(TransactionV2 tx) => + tx.getAmountSentFromThisWallet(fractionDigits: 8, subtractFee: true).raw; + +void main() { + group('a send that is not mined', () { + test('is listed once it was submitted', () { + for (final state in ['submitting', 'acknowledged', 'indeterminate']) { + final transactions = _mapper.transactions( + _history(), + pendingSends: _pending(broadcastState: state), + timestamps: {_sendTxid: 1700000500}, + chainHeight: 131, + ); + + expect(transactions.map((tx) => tx.txid), [_receiveTxid, _sendTxid]); + final send = transactions.last; + expect(send.height, isNull, reason: state); + expect(send.blockHash, isNull); + expect(send.getConfirmations(131), 0); + expect(send.type, TransactionType.outgoing); + expect(send.timestamp, 1700000500); + expect(_sent(send), BigInt.from(1000000)); + expect(send.getFee(fractionDigits: 8).raw, BigInt.from(20000)); + } + }); + + test('is not listed while it is only prepared', () { + final transactions = _mapper.transactions( + _history(), + pendingSends: _pending(broadcastState: 'prepared'), + chainHeight: 131, + ); + + expect(transactions.map((tx) => tx.txid), [_receiveTxid]); + }); + + test('is not listed once it can no longer be mined', () { + final pending = _pending(expiryHeight: 140); + + expect( + _mapper + .transactions(_history(), pendingSends: pending, chainHeight: 139) + .map((tx) => tx.txid), + [_receiveTxid, _sendTxid], + ); + expect( + _mapper + .transactions(_history(), pendingSends: pending, chainHeight: 140) + .map((tx) => tx.txid), + [_receiveTxid], + ); + }); + + test('is listed once, as mined, when a block contains it', () { + final transactions = _mapper.transactions( + _history(sendMinedAt: 131), + pendingSends: _pending(), + chainHeight: 131, + ); + + expect(transactions.map((tx) => tx.txid), [_sendTxid, _receiveTxid]); + final send = transactions.first; + expect(send.height, 131); + expect(send.type, TransactionType.outgoing); + // The scan does not carry a shielded fee: the wallet's record does. + expect(send.getFee(fractionDigits: 8).raw, BigInt.from(20000)); + expect(_sent(send), BigInt.from(1000000)); + }); + }); + + test('a send without the wallet\'s record includes its fee in the ' + 'amount', () { + final send = _mapper.transactions(_history(sendMinedAt: 131)).first; + + expect(send.getFee(fractionDigits: 8).raw, BigInt.zero); + expect(_sent(send), BigInt.from(1020000)); + }); + + group('timestamps', () { + test('come from the block times the scan kept', () { + final snapshot = _snapshot( + sendMinedAt: 131, + blockTimes: {120: 1700000120, 131: 1700000131}, + ); + final timestamps = zcashHistoryTimestamps( + snapshot: snapshot, + pendingSends: null, + stored: const {}, + now: 5, + ); + + expect(timestamps, {_receiveTxid: 1700000120, _sendTxid: 1700000131}); + final transactions = _mapper.transactions( + snapshot.history, + timestamps: timestamps, + ); + expect(transactions.map((tx) => tx.timestamp), [1700000131, 1700000120]); + }); + + test('are left unknown for a block whose time was not kept', () { + final snapshot = _snapshot(); + final timestamps = zcashHistoryTimestamps( + snapshot: snapshot, + pendingSends: null, + stored: const {}, + now: 5, + ); + + expect(timestamps, isEmpty); + expect( + _mapper.transactions(snapshot.history).single.timestamp, + ZcashStackStateMapper.unknownTimestampSentinel, + ); + }); + + test('date a send that is not mined when it was first listed', () { + Map timestamps(Map stored) => + zcashHistoryTimestamps( + snapshot: _snapshot(blockTimes: {120: 111}), + pendingSends: _pending(), + stored: stored, + now: 1700000900, + ); + + expect(timestamps(const {}), {_receiveTxid: 111, _sendTxid: 1700000900}); + expect( + timestamps({ + _sendTxid: _row(_sendTxid, height: null, timestamp: 1700000500), + })[_sendTxid], + 1700000500, + ); + }); + }); + + group('balance', () { + test('is the scanned balance without a send in flight', () { + final snapshot = _snapshot(); + + for (final pending in [ + null, + zcash.IronwoodPendingSendState(), + // Reserved for a send the user has not confirmed. + _pending(broadcastState: 'prepared'), + // Can no longer be mined: its notes are the wallet's again. + _pending(expiryHeight: 131), + ]) { + final balance = _mapper.balance(snapshot, pendingSends: pending); + expect(balance.total.raw, BigInt.from(10000000)); + expect(balance.spendable.raw, BigInt.from(10000000)); + expect(balance.pendingSpendable.raw, BigInt.zero); + expect(balance.blockedTotal.raw, BigInt.zero); + } + }); + + test('counts a send that is not mined as spent', () { + final snapshot = _snapshot(otherNote: true); + + for (final state in ['submitting', 'acknowledged', 'indeterminate']) { + final balance = _mapper.balance( + snapshot, + pendingSends: _pending(broadcastState: state), + ); + + // The payment and the fee have left. The change is not spendable + // until a block holds it. The note the send did not use still is. + expect(balance.total.raw, BigInt.from(13980000), reason: state); + expect(balance.spendable.raw, BigInt.from(5000000)); + expect(balance.pendingSpendable.raw, BigInt.from(8980000)); + expect(balance.blockedTotal.raw, BigInt.zero); + } + }); + + test('is the scanned balance again once the send is mined', () { + final snapshot = _snapshot(sendMinedAt: 131); + + final balance = _mapper.balance(snapshot, pendingSends: _pending()); + + // The change is in the tip block: above the anchor of a send, so not + // spendable yet. + expect(balance.total.raw, BigInt.from(8980000)); + expect(balance.spendable.raw, BigInt.zero); + expect(balance.pendingSpendable.raw, BigInt.from(8980000)); + expect(balance.blockedTotal.raw, BigInt.zero); + }); + + test('a note is pending until it is below the anchor of a send', () { + final state = _state(sendMinedAt: 131); + Balance at(int chainHeight) => _mapper.balance( + ZcashWalletSnapshot( + chainHeight: chainHeight, + balance: state.balance(), + history: state.history(), + spendableNotes: ZcashWalletSnapshot.spendableNotesOf(state), + unanchoredNotes: ZcashWalletSnapshot.unanchoredNotesOf( + state, + chainHeight, + ), + ), + ); + + // Received in block 131: a send prepared at height 133 anchors to + // block 130, one prepared at 134 to block 131. + expect(at(133).spendable.raw, BigInt.zero); + expect(at(133).pendingSpendable.raw, BigInt.from(8980000)); + expect(at(134).spendable.raw, BigInt.from(8980000)); + expect(at(134).pendingSpendable.raw, BigInt.zero); + expect(at(134).total.raw, BigInt.from(8980000)); + }); + + test('a note above the anchor that an unmined send holds is counted ' + 'once', () { + final state = _state(); + // The chain was reorganised: the note the send spends is now in a + // block above the anchor. + final snapshot = ZcashWalletSnapshot( + chainHeight: 121, + balance: state.balance(), + history: state.history(), + spendableNotes: ZcashWalletSnapshot.spendableNotesOf(state), + unanchoredNotes: ZcashWalletSnapshot.unanchoredNotesOf(state, 121), + ); + + final balance = _mapper.balance(snapshot, pendingSends: _pending()); + + expect(balance.total.raw, BigInt.from(8980000)); + expect(balance.spendable.raw, BigInt.zero); + expect(balance.pendingSpendable.raw, BigInt.from(8980000)); + expect(balance.blockedTotal.raw, BigInt.zero); + }); + + test('keeps what an unmined send pays to the wallet itself', () { + final snapshot = _snapshot(); + + final own = _mapper.balance( + snapshot, + pendingSends: _pending(), + ownAddresses: {'uregtest1destination'}, + ); + // Only the fee leaves. The payment and the change come back. + expect(own.total.raw, BigInt.from(9980000)); + expect(own.spendable.raw, BigInt.zero); + expect(own.pendingSpendable.raw, BigInt.from(9980000)); + expect(own.blockedTotal.raw, BigInt.zero); + + final other = _mapper.balance( + snapshot, + pendingSends: _pending(), + ownAddresses: {'uregtest1another'}, + ); + expect(other.total.raw, BigInt.from(8980000)); + expect(other.pendingSpendable.raw, BigInt.from(8980000)); + }); + }); + + test('the records of sends that were never mined and cannot be any more ' + 'are dropped, and those of mined sends are kept', () { + List left( + zcash.IronwoodPendingSendState pending, { + int? sendMinedAt, + }) { + ZcashWallet.reconcileLeftoverSends( + pending, + _snapshot(sendMinedAt: sendMinedAt), + ); + return [for (final record in pending.records) record.broadcastState.name]; + } + + // The chain is at height 131. + for (final state in ['acknowledged', 'indeterminate']) { + // Expired and in no block: nothing reads it. + expect(left(_pending(broadcastState: state, expiryHeight: 131)), isEmpty); + // It may still be mined. + expect(left(_pending(broadcastState: state)), [state]); + // Mined: its history row takes the fee and recipients from it. + expect( + left( + _pending(broadcastState: state, expiryHeight: 131), + sendMinedAt: 131, + ), + [state], + ); + } + // Never left the wallet. + expect(left(_pending(broadcastState: 'prepared')), isEmpty); + // The wallet closed before the node answered: it may have it. + expect(left(_pending(broadcastState: 'submitting')), ['indeterminate']); + }); +} diff --git a/test/wallets/zcash_pending_send_store_test.dart b/test/wallets/zcash_pending_send_store_test.dart new file mode 100644 index 000000000..4e2fd6642 --- /dev/null +++ b/test/wallets/zcash_pending_send_store_test.dart @@ -0,0 +1,81 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_pending_send_store.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_wallet_state.dart'; +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +import 'support/xelis_test_fakes.dart'; + +void main() { + test('pending reservations are encrypted and account-bound', () async { + final directory = await Directory.systemTemp.createTemp( + 'zcash_pending_store_', + ); + addTearDown(() => directory.delete(recursive: true)); + final secrets = MemorySecrets(); + final path = '${directory.path}/wallet.pending'; + final store = ZcashEncryptedPendingSendStore( + path: path, + walletId: 'wallet-id', + network: 'main', + accountFingerprint: 'account-a', + secureStorage: secrets, + ); + + await store.save(zcash.IronwoodPendingSendState()); + + expect((await store.load()).records, isEmpty); + final envelope = await File(path).readAsString(); + expect(envelope, isNot(contains('account-a'))); + expect(envelope, isNot(contains('pending_send_version'))); + + final foreign = ZcashEncryptedPendingSendStore( + path: path, + walletId: 'wallet-id', + network: 'main', + accountFingerprint: 'account-b', + secureStorage: secrets, + ); + await expectLater( + foreign.load(), + throwsA( + isA().having( + (error) => error.message, + 'message', + // Says what failed and nothing about the content. + 'pending-send state failed authentication or is corrupt', + ), + ), + ); + }); + + test('a load during a save leaves the save intact', () async { + final directory = await Directory.systemTemp.createTemp( + 'zcash_pending_store_', + ); + addTearDown(() => directory.delete(recursive: true)); + final secrets = MemorySecrets(); + // A refresh and a send each hold their own store for the wallet's file. + ZcashEncryptedPendingSendStore store() => ZcashEncryptedPendingSendStore( + path: '${directory.path}/wallet.pending', + walletId: 'wallet-id', + network: 'main', + accountFingerprint: 'account-a', + secureStorage: secrets, + ); + await store().save(zcash.IronwoodPendingSendState()); + + // A load removes the temporary file of an interrupted save. Run alone, + // these would have a load remove the file a save is about to rename. + await Future.wait([ + for (var i = 0; i < 20; i++) ...[ + store().save(zcash.IronwoodPendingSendState()), + store().load(), + ], + ]); + + expect((await store().load()).records, isEmpty); + expect(File('${directory.path}/wallet.pending.tmp').existsSync(), isFalse); + }); +} diff --git a/test/wallets/zcash_transparent_history_auth_test.dart b/test/wallets/zcash_transparent_history_auth_test.dart new file mode 100644 index 000000000..71464a9fc --- /dev/null +++ b/test/wallets/zcash_transparent_history_auth_test.dart @@ -0,0 +1,424 @@ +import 'package:fixnum/fixnum.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_account_session.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_wallet_state_controller.dart'; +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +zcash.ZcashTransactionSummary _summary( + String txid, { + List> inputs = const [], + List> outputs = const [], +}) => zcash.ZcashTransactionSummary.fromJson({ + 'network': 'mainnet', + 'txid': txid, + 'version': 'v5', + 'header': 2147483653, + 'version_group_id': 654776626, + 'consensus_branch_id': 'nu5', + 'consensus_branch_id_hex': 'c2d6d0b4', + 'lock_time': 0, + 'expiry_height': 0, + 'transparent': { + 'present': inputs.isNotEmpty || outputs.isNotEmpty, + 'vin': inputs.length, + 'vout': outputs.length, + 'inputs': inputs, + 'outputs': outputs, + }, + 'sapling': {'present': false, 'spends': 0, 'outputs': 0}, + 'orchard': {'present': false, 'actions': 0}, + 'ironwood': {'present': false, 'actions': 0}, + 'sprout': {'present': false, 'joinsplits': 0}, +}); + +List _bytes(String hex) => [ + for (var i = 0; i < hex.length; i += 2) + int.parse(hex.substring(i, i + 2), radix: 16), +]; + +zcash.CompactBlock _block({ + required int height, + required String displayedTxid, + String blockHash = + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', +}) => zcash.CompactBlock( + height: Int64(height), + hash: _bytes(blockHash), + time: 1700000000, + vtx: [ + zcash.CompactTx(txid: _bytes(zcash.reverseTxidByteOrder(displayedTxid))), + ], +); + +void main() { + const txid = + '000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f'; + + ZcashDecodedTransparentTransactionCandidate candidate({ + String summaryTxid = txid, + String computedTxid = txid, + int height = 50, + String rawTransactionHex = '00', + }) => ZcashDecodedTransparentTransactionCandidate( + summary: _summary(summaryTxid), + computedTxid: computedTxid, + height: height, + rawTransactionHex: rawTransactionHex, + ); + + test( + 'authenticates exact txid membership and deduplicates raw results', + () async { + var loads = 0; + final authenticated = await authenticateZcashTransparentTransactions( + candidates: [candidate(), candidate()], + startHeight: 40, + chainHeight: 60, + loadBlock: (height) async { + loads++; + return _block(height: height, displayedTxid: txid); + }, + ); + + expect(authenticated, hasLength(1)); + expect(authenticated.single.summary.txid, txid); + expect(authenticated.single.height, 50); + expect(loads, 1); + }, + ); + + test('rejects a decoded txid mismatch before loading a block', () async { + var loaded = false; + await expectLater( + authenticateZcashTransparentTransactions( + candidates: [candidate(computedTxid: 'ff' * 32)], + startHeight: 40, + chainHeight: 60, + loadBlock: (_) async { + loaded = true; + return _block(height: 50, displayedTxid: txid); + }, + ), + throwsStateError, + ); + expect(loaded, isFalse); + }); + + test('rejects a transaction served at the wrong block height', () async { + await expectLater( + authenticateZcashTransparentTransactions( + candidates: [candidate()], + startHeight: 40, + chainHeight: 60, + loadBlock: (_) async => _block(height: 51, displayedTxid: txid), + ), + throwsStateError, + ); + }); + + test( + 'rejects a transaction absent from the claimed canonical block', + () async { + await expectLater( + authenticateZcashTransparentTransactions( + candidates: [candidate()], + startHeight: 40, + chainHeight: 60, + loadBlock: (height) async => + _block(height: height, displayedTxid: 'ff' * 32), + ), + throwsStateError, + ); + }, + ); + + test( + 'rejects duplicate raw transaction ids at conflicting heights', + () async { + await expectLater( + authenticateZcashTransparentTransactions( + candidates: [candidate(), candidate(height: 51)], + startHeight: 40, + chainHeight: 60, + loadBlock: (height) async => + _block(height: height, displayedTxid: txid), + ), + throwsStateError, + ); + }, + ); + + test( + 'normalizes uppercase transaction ids before dedupe and membership', + () async { + final authenticated = await authenticateZcashTransparentTransactions( + candidates: [ + candidate(summaryTxid: txid.toUpperCase()), + candidate(computedTxid: txid.toUpperCase()), + ], + startHeight: 40, + chainHeight: 60, + loadBlock: (height) async => + _block(height: height, displayedTxid: txid), + ); + + expect(authenticated, hasLength(1)); + expect(authenticated.single.summary.txid, txid); + }, + ); + + test('rejects malformed transaction ids before loading blocks', () async { + await expectLater( + authenticateZcashTransparentTransactions( + candidates: [candidate(computedTxid: 'not-a-txid')], + startHeight: 40, + chainHeight: 60, + loadBlock: (_) async => _block(height: 50, displayedTxid: txid), + ), + throwsFormatException, + ); + }); + + test( + 'aborts a transaction stream as soon as its unique cap is exceeded', + () async { + var yielded = 0; + Stream candidates() async* { + for (var i = 0; i < 100; i++) { + yielded++; + final id = i.toRadixString(16).padLeft(64, '0'); + yield candidate( + summaryTxid: id, + computedTxid: id, + rawTransactionHex: i.toRadixString(16).padLeft(2, '0'), + ); + } + } + + await expectLater( + collectZcashTransparentTransactionStream( + stream: candidates(), + into: {}, + maxTransactions: 3, + ), + throwsStateError, + ); + expect(yielded, 4); + }, + ); + + test('rejects conflicting metadata for a duplicate owned outpoint', () { + const address = 't1OwnedAddress'; + const account = zcash.ZcashAccountMetadata( + network: zcash.ZcashAddressNetwork.mainnet, + accountIndex: 0, + ufvk: 'uview-main-account', + transparentAccountXpub: 'xpub-account', + receivers: zcash.ZcashAccountReceiverSet( + orchard: true, + sapling: true, + transparent: true, + p2pkh: true, + p2sh: false, + unknown: 0, + total: 3, + ), + receiverKinds: [ + zcash.ZcashAccountReceiverKind( + kind: zcash.ZcashAddressReceiverType.p2pkh, + pool: zcash.ZcashAddressPool.transparent, + ), + ], + ); + const viewingKeys = zcash.ZcashViewingKeys( + network: zcash.ZcashAddressNetwork.mainnet, + accountIndex: 0, + transparent: zcash.ZcashTransparentViewingKeys( + available: true, + externalIvk: 'external-ivk', + internalIvk: 'internal-ivk', + defaultExternalAddress: address, + defaultExternalIndex: 0, + ), + sapling: zcash.ZcashSaplingViewingKey(available: true), + orchard: zcash.ZcashOrchardViewingKey(available: true), + ); + final state = zcash.ZcashTransparentState.fromAccount( + account: account, + viewingKeys: viewingKeys, + ); + final summary = _summary( + txid, + outputs: const [ + { + 'output_index': 0, + 'address': address, + 'script_hex': '51', + 'value_zatoshis': 1, + }, + { + 'output_index': 0, + 'address': address, + 'script_hex': '52', + 'value_zatoshis': 2, + }, + ], + ); + final refresh = zcash.ZcashTransparentRefresh( + network: state.network, + accountFingerprint: state.accountFingerprint, + queriedAddresses: state.addresses, + chainHeight: 50, + chainTipHash: 'aa' * 32, + canonicalBlockHashes: {50: 'aa' * 32}, + unspentOutputs: const [], + observedSpends: const [], + ); + + expect( + () => mergeAuthenticatedTransparentHistory( + state: state, + refresh: refresh, + transactions: [ + ZcashAuthenticatedTransparentTransaction( + summary: summary, + height: 50, + blockHash: 'aa' * 32, + blockTime: null, + ), + ], + ), + throwsStateError, + ); + }); + + test( + 'an incremental spend joins against an output from the prior refresh', + () { + const address = 't1OwnedAddress'; + const spendTxid = + '111112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f'; + const account = zcash.ZcashAccountMetadata( + network: zcash.ZcashAddressNetwork.mainnet, + accountIndex: 0, + ufvk: 'uview-main-account', + transparentAccountXpub: 'xpub-account', + receivers: zcash.ZcashAccountReceiverSet( + orchard: true, + sapling: true, + transparent: true, + p2pkh: true, + p2sh: false, + unknown: 0, + total: 3, + ), + receiverKinds: [ + zcash.ZcashAccountReceiverKind( + kind: zcash.ZcashAddressReceiverType.p2pkh, + pool: zcash.ZcashAddressPool.transparent, + ), + ], + ); + const viewingKeys = zcash.ZcashViewingKeys( + network: zcash.ZcashAddressNetwork.mainnet, + accountIndex: 0, + transparent: zcash.ZcashTransparentViewingKeys( + available: true, + externalIvk: 'external-ivk', + internalIvk: 'internal-ivk', + defaultExternalAddress: address, + defaultExternalIndex: 0, + ), + sapling: zcash.ZcashSaplingViewingKey(available: true), + orchard: zcash.ZcashOrchardViewingKey(available: true), + ); + final state = zcash.ZcashTransparentState.fromAccount( + account: account, + viewingKeys: viewingKeys, + ); + final fundingProtocolTxid = zcash.reverseTxidByteOrder(txid); + final first = mergeAuthenticatedTransparentHistory( + state: state, + refresh: zcash.ZcashTransparentRefresh( + network: state.network, + accountFingerprint: state.accountFingerprint, + queriedAddresses: state.addresses, + chainHeight: 50, + chainTipHash: 'aa' * 32, + canonicalBlockHashes: {50: 'aa' * 32}, + unspentOutputs: [ + zcash.ZcashTransparentOutputObservation( + address: address, + protocolTxid: fundingProtocolTxid, + outputIndex: 0, + scriptHex: '51', + valueZatoshis: 100000, + minedHeight: 50, + blockHash: 'aa' * 32, + blockTime: 1700000000, + isCoinbase: false, + ), + ], + observedSpends: const [], + ), + transactions: [ + ZcashAuthenticatedTransparentTransaction( + summary: _summary( + txid, + outputs: const [ + { + 'output_index': 0, + 'address': address, + 'script_hex': '51', + 'value_zatoshis': 100000, + }, + ], + ), + height: 50, + blockHash: 'aa' * 32, + blockTime: 1700000000, + ), + ], + ); + state.applyRefresh(first); + + final second = mergeAuthenticatedTransparentHistory( + state: state, + refresh: zcash.ZcashTransparentRefresh( + network: state.network, + accountFingerprint: state.accountFingerprint, + queriedAddresses: state.addresses, + chainHeight: 51, + chainTipHash: 'bb' * 32, + canonicalBlockHashes: {50: 'aa' * 32, 51: 'bb' * 32}, + unspentOutputs: const [], + observedSpends: const [], + ), + transactions: [ + ZcashAuthenticatedTransparentTransaction( + summary: _summary( + spendTxid, + inputs: const [ + {'prevout_txid': txid, 'prevout_index': 0}, + ], + ), + height: 51, + blockHash: 'bb' * 32, + blockTime: 1700000100, + ), + ], + ); + state.applyRefresh(second); + + expect(second.observedSpends, hasLength(1)); + expect( + second.observedSpends.single.spentOutpoint, + '$fundingProtocolTxid:0', + ); + expect( + state.outputs.single.spendingProtocolTxid, + zcash.reverseTxidByteOrder(spendTxid), + ); + }, + ); +} diff --git a/test/wallets/zcash_transparent_receiver_discovery_test.dart b/test/wallets/zcash_transparent_receiver_discovery_test.dart new file mode 100644 index 000000000..0690c9371 --- /dev/null +++ b/test/wallets/zcash_transparent_receiver_discovery_test.dart @@ -0,0 +1,42 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_transparent_receiver_discovery.dart'; +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +const _viewingKeys = zcash.ZcashViewingKeys( + network: zcash.ZcashAddressNetwork.mainnet, + accountIndex: 0, + transparent: zcash.ZcashTransparentViewingKeys( + available: true, + externalIvk: '00', + internalIvk: '11', + defaultExternalAddress: 't-address', + defaultExternalIndex: 0, + ), + sapling: zcash.ZcashSaplingViewingKey(available: false), + orchard: zcash.ZcashOrchardViewingKey(available: false), +); + +void main() { + test('rejects a non-positive transparent discovery gap at runtime', () { + expect( + () => ZcashTransparentReceiverDiscovery( + network: zcash.ZcashNetwork.mainnet, + viewingKeys: _viewingKeys, + gapLimit: 0, + ), + throwsArgumentError, + ); + }); + + test('rejects a hard child limit below the discovery gap', () { + expect( + () => ZcashTransparentReceiverDiscovery( + network: zcash.ZcashNetwork.mainnet, + viewingKeys: _viewingKeys, + gapLimit: 20, + hardChildLimit: 19, + ), + throwsArgumentError, + ); + }); +} diff --git a/test/wallets/zcash_wallet_identity_test.dart b/test/wallets/zcash_wallet_identity_test.dart new file mode 100644 index 000000000..ba2f032d0 --- /dev/null +++ b/test/wallets/zcash_wallet_identity_test.dart @@ -0,0 +1,187 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:stackwallet/db/isar/main_db.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/models/node_model.dart'; +import 'package:stackwallet/services/node_service.dart'; +import 'package:stackwallet/utilities/stack_file_system.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; +import 'package:stackwallet/wallets/wallet/impl/zcash_wallet.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_account_session.dart'; +import 'package:stackwallet/wallets/wallet/wallet.dart'; +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +import 'support/xelis_test_fakes.dart'; +import 'support/zcash_test_coins.dart'; +import '../support/isar_test_utils.dart'; + +class OfflineNodes extends Fake implements NodeService { + @override + NodeModel? getPrimaryNodeFor({required CryptoCurrency currency}) => null; +} + +/// A node that never answers. With no primary node the wallet uses its +/// default one, which these tests must not reach. +class UnreachableClient implements ZcashLightwalletdClient { + @override + Future getInfo() => + Future.error(const SocketException('offline')); + + @override + Future getTipHeight() => Future.error(const SocketException('offline')); + + @override + Future close() async {} +} + +void _stayOffline(ZcashWallet wallet) => wallet.configureAccountSessionFactory( + (network) => ZcashAccountSession( + network: network, + clientFactory: (_) => UnreachableClient(), + ), +); + +void main() { + listZcashCoins(); + TestWidgetsFlutterBinding.ensureInitialized(); + setUpAll(initializeTestIsar); + late Directory root; + + setUpAll(() async { + if (!(Platform.isWindows || Platform.isLinux || Platform.isMacOS)) { + throw UnsupportedError('Run this storage scenario on a desktop host.'); + } + root = await Directory.systemTemp.createTemp('stack_zcash_identity_'); + StackFileSystem.setDesktopOverrideDir(root.path); + }); + tearDownAll(() => root.delete(recursive: true)); + + setUp(() async { + await MainDB.instance.initMainDB(); + addTearDown(() => MainDB.instance.isar.close()); + }); + + test( + 'fixed recovery phrase creates, persists, and reopens one unified address', + () async { + const phrase = + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about'; + final secrets = MemorySecrets(); + final prefs = SessionPrefs(); + final nodes = OfflineNodes(); + + final created = await Wallet.create( + walletInfo: WalletInfo( + walletId: 'zcash-identity', + name: 'Zcash identity fixture', + mainAddressType: AddressType.zcashUnified, + coinName: 'zcash', + restoreHeight: 1, + ), + mainDB: MainDB.instance, + secureStorageInterface: secrets, + nodeService: nodes, + prefs: prefs, + mnemonic: phrase, + mnemonicPassphrase: '', + ) as ZcashWallet; + _stayOffline(created); + await created.init(isRestore: true); + + final createdAddress = await created.getCurrentReceivingAddress(); + expect(createdAddress, isNotNull); + expect(createdAddress!.value, startsWith('u1')); + expect( + created.cryptoCurrency.validateAddress(createdAddress.value), + isTrue, + ); + final persistedReceivers = await MainDB.instance + .getAddresses(created.walletId) + .findAll(); + expect(persistedReceivers.map((address) => address.type).toSet(), { + AddressType.zcashUnified, + AddressType.zcashSapling, + AddressType.p2pkh, + }); + expect(persistedReceivers, hasLength(3)); + expect(created.info.cachedReceivingAddress, createdAddress.value); + // Opening a wallet that has a birthday needs no node, and an + // unreachable one is reported without breaking the wallet. + expect(await created.pingCheck(), isFalse); + await created.updateNode(); + expect(await created.pingCheck(), isFalse); + await created.exit(); + + final reopened = await Wallet.load( + walletId: 'zcash-identity', + mainDB: MainDB.instance, + secureStorageInterface: secrets, + nodeService: nodes, + prefs: prefs, + ) as ZcashWallet; + _stayOffline(reopened); + await reopened.init(); + + final reopenedAddress = await reopened.getCurrentReceivingAddress(); + expect(reopenedAddress, isNotNull); + expect(reopenedAddress!.value, createdAddress.value); + expect(reopened.info.cachedReceivingAddress, createdAddress.value); + expect(await reopened.getMnemonic(), phrase); + await reopened.exit(); + }, + ); + + test('reopening refuses a cached unified-address mismatch', () async { + const phrase = + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about'; + final secrets = MemorySecrets(); + final prefs = SessionPrefs(); + final nodes = OfflineNodes(); + final created = await Wallet.create( + walletInfo: WalletInfo( + walletId: 'zcash-mismatch', + name: 'Zcash mismatch fixture', + mainAddressType: AddressType.zcashUnified, + coinName: 'zcash', + restoreHeight: 1, + ), + mainDB: MainDB.instance, + secureStorageInterface: secrets, + nodeService: nodes, + prefs: prefs, + mnemonic: phrase, + mnemonicPassphrase: '', + ) as ZcashWallet; + await created.init(isRestore: true); + final derivedAddress = created.info.cachedReceivingAddress; + await created.info.updateReceivingAddress( + newAddress: '${derivedAddress}corrupt', + isar: MainDB.instance.isar, + ); + await created.exit(); + + final reopened = await Wallet.load( + walletId: 'zcash-mismatch', + mainDB: MainDB.instance, + secureStorageInterface: secrets, + nodeService: nodes, + prefs: prefs, + ) as ZcashWallet; + await expectLater( + reopened.init(), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('does not match the saved wallet'), + ), + ), + ); + await reopened.exit(); + }); +} diff --git a/test/wallets/zcash_wallet_persistence_test.dart b/test/wallets/zcash_wallet_persistence_test.dart new file mode 100644 index 000000000..5c29e6dd9 --- /dev/null +++ b/test/wallets/zcash_wallet_persistence_test.dart @@ -0,0 +1,138 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_wallet_persistence.dart'; + +void main() { + const deletionTestName = + 'deletes only one wallet Zcash files, temps, and encryption keys'; + test(deletionTestName, () async { + final root = await Directory.systemTemp.createTemp( + 'zcash_wallet_persistence_', + ); + addTearDown(() => root.delete(recursive: true)); + final zcashRoot = await Directory('${root.path}/zcash').create(); + const walletId = 'wallet-delete'; + const otherWalletId = 'wallet-keep'; + final deletedPaths = []; + for (final suffix in zcashWalletPersistenceSuffixes) { + for (final temporary in [false, true]) { + final path = + '${zcashRoot.path}/$walletId.$suffix' + '${temporary ? '.tmp' : ''}'; + await File(path).writeAsString('encrypted'); + deletedPaths.add(path); + } + } + final retainedFile = await File('${zcashRoot.path}/$otherWalletId.state') + .writeAsString('retain'); + final secrets = FakeSecureStorage(); + for (final key in zcashWalletPersistenceKeys(walletId)) { + await secrets.write(key: key, value: 'secret'); + } + const unrelatedKey = 'unrelated-secret'; + await secrets.write(key: unrelatedKey, value: 'retain'); + + await deleteZcashWalletPersistence( + applicationRoot: root, + walletId: walletId, + secureStorage: secrets, + ); + + for (final path in deletedPaths) { + expect(await File(path).exists(), isFalse, reason: path); + } + for (final key in zcashWalletPersistenceKeys(walletId)) { + expect(await secrets.read(key: key), isNull, reason: key); + } + expect(await retainedFile.readAsString(), 'retain'); + expect(await secrets.read(key: unrelatedKey), 'retain'); + }); + + test( + 'retains encryption keys when any persisted file cannot be deleted', + () async { + final root = await Directory.systemTemp.createTemp( + 'zcash_wallet_persistence_failure_', + ); + addTearDown(() => root.delete(recursive: true)); + final zcashRoot = await Directory('${root.path}/zcash').create(); + const walletId = 'wallet-file-failure'; + await Directory('${zcashRoot.path}/$walletId.state').create(); + await File('${zcashRoot.path}/$walletId.pending') + .writeAsString('encrypted'); + final secrets = FakeSecureStorage(); + for (final key in zcashWalletPersistenceKeys(walletId)) { + await secrets.write(key: key, value: 'secret'); + } + + await expectLater( + deleteZcashWalletPersistence( + applicationRoot: root, + walletId: walletId, + secureStorage: secrets, + ), + throwsA(isA()), + ); + + for (final key in zcashWalletPersistenceKeys(walletId)) { + expect(await secrets.read(key: key), 'secret', reason: key); + } + }, + ); + + test('refuses a wallet id that could escape the Zcash directory', () async { + final root = await Directory.systemTemp.createTemp( + 'zcash_wallet_persistence_traversal_', + ); + addTearDown(() => root.delete(recursive: true)); + await Directory('${root.path}/zcash').create(); + final outside = await File('${root.path}/outside.state') + .writeAsString('retain'); + const walletId = '../outside'; + final secrets = FakeSecureStorage(); + final stateKey = zcashWalletStateKey(walletId); + await secrets.write(key: stateKey, value: 'retain'); + + await expectLater( + deleteZcashWalletPersistence( + applicationRoot: root, + walletId: walletId, + secureStorage: secrets, + ), + throwsArgumentError, + ); + + expect(await outside.readAsString(), 'retain'); + expect(await secrets.read(key: stateKey), 'retain'); + }); + + test('removes an exact symlink without following its target', () async { + final root = await Directory.systemTemp.createTemp( + 'zcash_wallet_persistence_link_', + ); + addTearDown(() => root.delete(recursive: true)); + final zcashRoot = await Directory('${root.path}/zcash').create(); + const walletId = 'wallet-link'; + final outside = await File('${root.path}/outside').writeAsString('retain'); + final link = await Link('${zcashRoot.path}/$walletId.state') + .create(outside.path); + final secrets = FakeSecureStorage(); + for (final key in zcashWalletPersistenceKeys(walletId)) { + await secrets.write(key: key, value: 'secret'); + } + + await deleteZcashWalletPersistence( + applicationRoot: root, + walletId: walletId, + secureStorage: secrets, + ); + + expect(await link.exists(), isFalse); + expect(await outside.readAsString(), 'retain'); + for (final key in zcashWalletPersistenceKeys(walletId)) { + expect(await secrets.read(key: key), isNull, reason: key); + } + }); +} diff --git a/test/wallets/zcash_wallet_send_test.dart b/test/wallets/zcash_wallet_send_test.dart new file mode 100644 index 000000000..821507a51 --- /dev/null +++ b/test/wallets/zcash_wallet_send_test.dart @@ -0,0 +1,1788 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:crypto/crypto.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:path/path.dart' as path; +import 'package:stackwallet/db/isar/main_db.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/models/node_model.dart'; +import 'package:stackwallet/services/node_service.dart'; +import 'package:stackwallet/utilities/amount/amount.dart'; +import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart'; +import 'package:stackwallet/utilities/stack_file_system.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; +import 'package:stackwallet/wallets/models/tx_data.dart'; +import 'package:stackwallet/wallets/wallet/impl/zcash_wallet.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_account_session.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_pending_send_store.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_send.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_wallet_state.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 '../support/isar_test_utils.dart'; +import 'support/xelis_test_fakes.dart'; +import 'support/zcash_test_coins.dart'; + +final class SendNodes extends Fake implements NodeService { + @override + NodeModel? getPrimaryNodeFor({required CryptoCurrency currency}) => NodeModel( + host: 'https://send.example', + port: 443, + name: 'send', + id: 'send', + useSSL: true, + enabled: true, + coinName: currency.identifier, + isFailover: false, + isDown: false, + torEnabled: false, + clearnetEnabled: true, + isPrimary: true, + ); +} + +final class SendClient + implements + ZcashLightwalletdSyncClient, + ZcashLightwalletdTransparentClient, + ZcashLightwalletdSendClient { + SendClient({this.chainName = 'main', this.treeState}); + + final String chainName; + final zcash.TreeState? treeState; + final List submitted = []; + bool failTip = false; + int tipHeightCalls = 0; + Completer? nextTipHeightEntered; + Future? nextTipHeightGate; + + @override + Future close() async {} + + @override + Future getBlockHash(int height) async => null; + + @override + Future getBlockRange(int start, int end) => + throw StateError('caught-up fixture must not request blocks'); + + @override + Future getInfo() async => + zcash.LightdInfo(chainName: chainName); + + @override + Future getTipHeight() async { + tipHeightCalls++; + if (failTip) throw StateError('fresh chain tip unavailable'); + final entered = nextTipHeightEntered; + final gate = nextTipHeightGate; + nextTipHeightEntered = null; + nextTipHeightGate = null; + entered?.complete(); + if (gate != null) await gate; + return 42; + } + + @override + Future getTransparentAddressActivity( + List addresses, { + required int startHeight, + required int chainHeight, + }) async => ZcashTransparentActivityResult.empty; + + @override + Future getTransparentRefresh( + zcash.ZcashTransparentState state, { + int maxRangeSize = 1000, + int maxUtxos = 10000, + }) async => zcash.ZcashTransparentRefresh( + network: state.network, + accountFingerprint: state.accountFingerprint, + queriedAddresses: state.addresses, + chainHeight: 42, + chainTipHash: '44' * 32, + canonicalBlockHashes: {42: '44' * 32}, + unspentOutputs: const [], + observedSpends: const [], + ); + + @override + Future getTreeState(int height) async => + treeState ?? + zcash.TreeState( + hash: List.filled(32, '00').join(), + height: height, + time: 1, + ); + + @override + Future submitTransaction( + Uint8List transaction, + ) async { + submitted.add(Uint8List.fromList(transaction)); + return const ZcashSubmissionAcknowledgement(errorCode: 0, errorMessage: ''); + } +} + +final class FixturePreparedSend extends ZcashPreparedWalletSend { + FixturePreparedSend({ + required super.sessionGeneration, + required String requestedAddress, + zcash.ProposalOutputPool preparedOutputPool = + zcash.ProposalOutputPool.ironwood, + }) : super( + encodedRecipient: requestedAddress, + selectedReceiver: zcash.ZcashAddressReceiverType.orchard, + selectedReceiverAddress: 'u1selected-ironwood', + actualOutputPool: preparedOutputPool, + memo: Uint8List.fromList([0x68, 0x69]), + ); + + @override + int get amountZatoshis => 40000; + @override + int get changeZatoshis => 50000; + @override + int get expiryHeight => 83; + @override + int get feeZatoshis => 10000; + @override + int get inputZatoshis => 100000; + @override + List get selectedNotes => const [ + zcash.ZcashScannedNote( + height: 40, + tx: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + output: 0, + value: 100000, + pool: 'ironwood', + nullifier: + 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb' + 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb', + ), + ]; + @override + String get transactionHex => '00ff10'; + @override + String get txid => List.filled(32, '11').join(); +} + +final class FixturePreparedBatch extends ZcashPreparedWalletSend { + FixturePreparedBatch({ + required super.sessionGeneration, + required String requestedAddress, + required List payments, + }) : _outputs = [ + for (final payment in payments) + ( + encodedRecipient: payment.recipient, + amountZatoshis: payment.amountZatoshis, + memo: payment.memo, + ), + ], + super( + encodedRecipient: requestedAddress, + selectedReceiver: zcash.ZcashAddressReceiverType.orchard, + selectedReceiverAddress: 'u1selected-ironwood', + actualOutputPool: zcash.ProposalOutputPool.ironwood, + memo: payments.first.memo, + ); + + final List _outputs; + + @override + List get paymentOutputs => _outputs; + @override + int get amountZatoshis => + _outputs.fold(0, (sum, output) => sum + output.amountZatoshis); + @override + int get changeZatoshis => 10000; + @override + int get expiryHeight => 83; + @override + int get feeZatoshis => 10000; + @override + int get inputZatoshis => 100000; + @override + List get selectedNotes => const []; + @override + String get transactionHex => '00ff20'; + @override + String get txid => List.filled(32, '22').join(); +} + +final class RecordingSendService implements ZcashWalletSendService { + RecordingSendService({ + this.preparedOutputPool = zcash.ProposalOutputPool.ironwood, + }); + + final zcash.ProposalOutputPool preparedOutputPool; + ZcashSendPreparationRequest? request; + ZcashPreparedWalletSend? broadcastPrepared; + + @override + Future prepare( + ZcashSendPreparationRequest request, + ) async { + this.request = request; + if (request.payments.length > 1) { + return FixturePreparedBatch( + sessionGeneration: request.sessionGeneration, + requestedAddress: request.payments.first.recipient, + payments: request.payments, + ); + } + return FixturePreparedSend( + sessionGeneration: request.sessionGeneration, + requestedAddress: request.payments.single.recipient, + preparedOutputPool: preparedOutputPool, + ); + } + + @override + Future broadcast({ + required ZcashPreparedWalletSend prepared, + required zcash.IronwoodPendingSendState pendingSends, + required int chainHeight, + required Future Function() persist, + required Future Function( + String transactionHex, + ) + submit, + }) async { + broadcastPrepared = prepared; + await persist(); + await submit(prepared.transactionHex); + } +} + +final class ParameterResolvingSendService implements ZcashWalletSendService { + @override + Future prepare( + ZcashSendPreparationRequest request, + ) async { + await request.resolveSaplingProvingParameters(); + return FixturePreparedSend( + sessionGeneration: request.sessionGeneration, + requestedAddress: request.payments.single.recipient, + ); + } + + @override + Future broadcast({ + required ZcashPreparedWalletSend prepared, + required zcash.IronwoodPendingSendState pendingSends, + required int chainHeight, + required Future Function() persist, + required Future Function( + String transactionHex, + ) + submit, + }) => throw StateError('parameter fixture must not reach broadcast'); +} + +final class UnusedScanExecutor implements ZcashScanExecutor { + @override + Future scan(zcash.ScanInputEnvelope envelope) => + throw StateError('routing refusal must happen before scanning'); +} + +final class AnchorScanExecutor implements ZcashScanExecutor { + @override + Future scan(zcash.ScanInputEnvelope envelope) async => + zcash.ZcashScanResult( + scannedBlocks: 0, + discoveredNotes: 0, + totalValue: 0, + notes: const [], + saplingAnchor: 'aa' * 32, + ironwoodAnchor: 'bb' * 32, + ); +} + +final class RecordingSpendMaterialProvider + implements ZcashIronwoodSpendMaterialProvider { + int calls = 0; + + @override + Future acquire({ + required ZcashSendPreparationRequest request, + required List candidates, + required int anchorHeight, + }) async { + calls++; + throw StateError('required Sapling must not inspect Ironwood material'); + } +} + +final class FixtureSpendMaterialProvider + implements ZcashIronwoodSpendMaterialProvider { + /// The anchor heights it was asked for. + final List anchors = []; + + @override + Future acquire({ + required ZcashSendPreparationRequest request, + required List candidates, + required int anchorHeight, + }) async { + anchors.add(anchorHeight); + return _material(request, candidates, anchorHeight); + } + + static zcash.ZcashSpendMaterial _material( + ZcashSendPreparationRequest request, + List candidates, + int anchorHeight, + ) => zcash.ZcashSpendMaterial.verified( + accountFingerprint: request.state.accountFingerprint, + pool: 'ironwood', + anchorHeight: anchorHeight, + anchorBlockHash: '44' * 32, + scan: zcash.ZcashScanResult( + scannedBlocks: 1, + discoveredNotes: candidates.length, + totalValue: candidates.fold(0, (sum, note) => sum + note.value), + notes: candidates, + scannedHeightRange: zcash.CompactBlockScanRange( + start: candidates + .map((note) => note.height) + .reduce((left, right) => left < right ? left : right), + end: anchorHeight, + ), + ironwoodAnchor: 'cc' * 32, + ), + ); +} + +final class FixtureIronwoodPaymentBackend + implements zcash.IronwoodPaymentBackend { + final List builds = []; + + @override + zcash.IronwoodFeeQuote quote(zcash.IronwoodPaymentNativeRequest request) { + final input = request.ironwoodSpends.fold( + 0, + (sum, spend) => sum + spend.valueZatoshis, + ); + final nonIronwood = request.outputs.fold( + 0, + (sum, output) => sum + output.valueZatoshis, + ); + return zcash.IronwoodFeeQuote( + network: zcash.ZcashAddressNetwork.regtest, + feeZatoshis: 10000, + feeRule: 'zip317', + consensusBranchId: 'nu6.3', + totalInputZatoshis: input, + nonIronwoodOutputZatoshis: nonIronwood, + maxIronwoodOutputZatoshis: input - nonIronwood - 10000, + ironwoodSpends: request.ironwoodSpends.length, + orchardSpends: 0, + saplingSpends: 0, + transparentInputs: 0, + ); + } + + @override + zcash.IronwoodBuildResult build(zcash.IronwoodPaymentNativeRequest request) { + builds.add(request); + final input = request.ironwoodSpends.fold( + 0, + (sum, spend) => sum + spend.valueZatoshis, + ); + final nonIronwood = request.outputs.fold( + 0, + (sum, output) => sum + output.valueZatoshis, + ); + final transparent = request.outputs.where( + (output) => output.address.startsWith('t'), + ); + final sapling = request.outputs.where( + (output) => output.address.startsWith('z'), + ); + final ironwoodPayment = + request.ironwoodOutput.valueZatoshis! + + request.additionalIronwoodOutputs.fold( + 0, + (sum, output) => sum + output.valueZatoshis!, + ); + final hasIronwoodChange = request.ironwoodChangeZatoshis != null; + return zcash.IronwoodBuildResult( + network: zcash.ZcashAddressNetwork.regtest, + transactionHex: 'ff' * 20, + txid: 'ee' * 32, + version: 'v6', + expiryHeight: request.expiryHeight!, + feeZatoshis: 10000, + feeRule: 'zip317', + proofValidity: 'real', + ironwoodAnchor: request.anchorHex, + ironwoodAnchorSource: 'anchor', + vin: 0, + vout: transparent.length, + saplingOutputs: sapling.isEmpty ? 0 : 2, + ironwoodActions: + request.ironwoodSpends.length + + 1 + + request.additionalIronwoodOutputs.length + + (hasIronwoodChange ? 1 : 0), + ironwoodSpends: request.ironwoodSpends.length, + ironwoodOutputs: + 1 + + request.additionalIronwoodOutputs.length + + (hasIronwoodChange ? 1 : 0), + ironwoodChangeOutputs: hasIronwoodChange ? 1 : 0, + totalInputZatoshis: input, + ironwoodInputZatoshis: input, + ironwoodChangeZatoshis: request.ironwoodChangeZatoshis ?? 0, + nonIronwoodOutputZatoshis: nonIronwood, + ironwoodOutputZatoshis: ironwoodPayment, + rng: 'system', + ); + } +} + +final class FixtureParameterSource implements zcash.SaplingParameterSource { + const FixtureParameterSource(this.bytes); + + final Map> bytes; + + @override + Stream> open(zcash.SaplingParameterArtifact artifact) => + Stream.value(bytes[artifact.fileName]!); +} + +/// A node that refuses every transaction while [refuse] is set, and gives +/// no answer to one while [lose] is. +final class RefusingSendClient extends SendClient { + RefusingSendClient({super.chainName}); + + bool refuse = false; + bool lose = false; + + @override + Future submitTransaction( + Uint8List transaction, + ) async { + if (lose) throw StateError('the connection was lost'); + return refuse + ? const ZcashSubmissionAcknowledgement( + errorCode: -26, + errorMessage: 'refused', + ) + : super.submitTransaction(transaction); + } +} + +void main() { + listZcashCoins(); + TestWidgetsFlutterBinding.ensureInitialized(); + setUpAll(initializeTestIsar); + late Directory root; + + setUpAll(() async { + root = await Directory.systemTemp.createTemp('stack_zcash_send_'); + StackFileSystem.setDesktopOverrideDir(root.path); + }); + tearDownAll(() => root.delete(recursive: true)); + + setUp(() async { + await MainDB.instance.initMainDB(); + addTearDown(() async { + if (MainDB.instance.isar.isOpen) await MainDB.instance.isar.close(); + }); + }); + + test('the fee estimate counts the notes a payment would spend', () { + int fee(List notes, int amount) => + ZcashWallet.estimateZip317Fee(notes, BigInt.from(amount)); + + // Two actions are the minimum, whatever the wallet holds. + expect(fee([], 40000), 10000); + expect(fee([100000], 40000), 10000); + expect(fee([30000, 30000], 40000), 10000); + // The largest notes go first, and each one past the second is an action. + expect(fee([20000, 100000, 20000], 40000), 10000); + expect(fee([20000, 20000, 20000, 20000], 40000), 15000); + expect(fee([20000, 20000, 20000, 20000], 46000), 20000); + // Not enough funds: the fee of spending every note. + expect(fee([20000, 20000, 20000], 90000), 15000); + }); + + test('prepare and confirm preserve one exact backend artifact', () async { + final client = SendClient(); + final service = RecordingSendService(); + final wallet = await _wallet(client, service, 'exact-artifact'); + final address = (await wallet.getCurrentReceivingAddress())!.value; + + final prepared = await wallet.prepareSend( + txData: TxData( + recipients: [ + TxRecipient( + address: address, + amount: Amount(rawValue: BigInt.from(40000), fractionDigits: 8), + isChange: false, + addressType: AddressType.zcashUnified, + ), + ], + memo: 'hi', + ), + ); + + expect(prepared.raw, '00ff10'); + expect(prepared.txid, List.filled(32, '11').join()); + expect(prepared.fee!.raw, BigInt.from(10000)); + expect(service.request!.payments.single.memo, [0x68, 0x69]); + expect(service.request!.payments.single.amountZatoshis, 40000); + expect(service.request!.targetHeight, 43); + expect(service.request!.ironwoodChangeAddress, address); + + final reviewed = prepared.copyWith(note: 'local-only review note'); + final confirmed = await wallet.confirmSend(txData: reviewed); + + expect(confirmed.txid, prepared.txid); + expect(service.broadcastPrepared, isA()); + expect(client.submitted, [ + Uint8List.fromList([0, 255, 16]), + ]); + await wallet.exit(); + }); + + test('wallet surfaces a missing Sapling parameter source', () async { + final wallet = await _wallet( + SendClient(), + ParameterResolvingSendService(), + 'sapling-parameters-required', + saplingParameterResolver: () async { + throw const ZcashSaplingParametersUnavailableException(); + }, + ); + final address = (await wallet.getCurrentReceivingAddress())!.value; + + await expectLater( + wallet.prepareSend( + txData: TxData( + recipients: [ + TxRecipient( + address: address, + amount: Amount(rawValue: BigInt.from(40000), fractionDigits: 8), + isChange: false, + addressType: AddressType.zcashUnified, + ), + ], + ), + ), + throwsA(isA()), + ); + await wallet.exit(); + }); + + test( + 'recovery refreshes chain state before filtering reservations', + () async { + final client = SendClient(); + final wallet = await _wallet( + client, + RecordingSendService(), + 'recover-tip', + ); + final callsBeforeRecovery = client.tipHeightCalls; + client.failTip = true; + + await expectLater( + wallet.recoverPreparedSend(), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('fresh chain tip unavailable'), + ), + ), + ); + expect(client.tipHeightCalls, callsBeforeRecovery + 1); + await wallet.exit(); + }, + ); + + test( + 'confirmation refreshes chain state immediately before broadcast', + () async { + final client = SendClient(); + final service = RecordingSendService(); + final wallet = await _wallet(client, service, 'confirm-tip'); + final address = (await wallet.getCurrentReceivingAddress())!.value; + final prepared = await wallet.prepareSend( + txData: TxData( + recipients: [ + TxRecipient( + address: address, + amount: Amount(rawValue: BigInt.from(40000), fractionDigits: 8), + isChange: false, + addressType: AddressType.zcashUnified, + ), + ], + ), + ); + final callsBeforeConfirmation = client.tipHeightCalls; + client.failTip = true; + + await expectLater( + wallet.confirmSend(txData: prepared), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('fresh chain tip unavailable'), + ), + ), + ); + expect(client.tipHeightCalls, callsBeforeConfirmation + 1); + expect(service.broadcastPrepared, isNull); + expect(client.submitted, isEmpty); + client.failTip = false; + await wallet.cancelSend(txData: prepared); + await wallet.exit(); + }, + ); + + test( + 'confirmation refuses a node replacement during its final refresh', + () async { + final client = SendClient(); + final service = RecordingSendService(); + final wallet = await _wallet(client, service, 'confirm-node-race'); + final address = (await wallet.getCurrentReceivingAddress())!.value; + final prepared = await wallet.prepareSend( + txData: TxData( + recipients: [ + TxRecipient( + address: address, + amount: Amount(rawValue: BigInt.from(40000), fractionDigits: 8), + isChange: false, + addressType: AddressType.zcashUnified, + ), + ], + ), + ); + final refreshEntered = Completer(); + final releaseRefresh = Completer(); + client.nextTipHeightEntered = refreshEntered; + client.nextTipHeightGate = releaseRefresh.future; + + final confirmation = wallet.confirmSend(txData: prepared); + await refreshEntered.future; + await wallet.updateNode(); + releaseRefresh.complete(); + + await expectLater( + confirmation, + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('node changed after preparation'), + ), + ), + ); + expect(service.broadcastPrepared, isNull); + expect(client.submitted, isEmpty); + await wallet.cancelSend(txData: prepared); + await wallet.exit(); + }, + ); + + test('ordered repeated recipients are kept and a changed one is ' + 'refused', () async { + final client = SendClient(); + final service = RecordingSendService(); + final wallet = await _wallet(client, service, 'exact-batch-artifact'); + final address = (await wallet.getCurrentReceivingAddress())!.value; + TxRecipient recipient(int zatoshis) => TxRecipient( + address: address, + amount: Amount(rawValue: BigInt.from(zatoshis), fractionDigits: 8), + isChange: false, + addressType: AddressType.zcashUnified, + ); + // One memo cannot say which recipient it is for. + await expectLater( + wallet.prepareSend( + txData: TxData( + recipients: [recipient(40000), recipient(40000)], + memo: 'for both', + ), + ), + throwsArgumentError, + ); + expect(service.request, isNull); + + final prepared = await wallet.prepareSend( + txData: TxData(recipients: [recipient(40000), recipient(40000)]), + ); + + expect(service.request!.payments.map((p) => p.recipient), [ + address, + address, + ]); + expect(service.request!.payments.map((p) => p.memo), [null, null]); + + final altered = prepared.copyWith( + recipients: [prepared.recipients!.first, recipient(40001)], + ); + await expectLater( + wallet.confirmSend(txData: altered), + throwsA(isA()), + ); + await wallet.confirmSend(txData: prepared); + expect(client.submitted.single, Uint8List.fromList([0, 255, 32])); + await wallet.exit(); + }); + + test( + 'confirmation refuses any replacement of prepared transaction bytes', + () async { + final service = RecordingSendService(); + final wallet = await _wallet(SendClient(), service, 'mismatch'); + final address = (await wallet.getCurrentReceivingAddress())!.value; + final prepared = await wallet.prepareSend( + txData: TxData( + recipients: [ + TxRecipient( + address: address, + amount: Amount(rawValue: BigInt.from(40000), fractionDigits: 8), + isChange: false, + addressType: AddressType.zcashUnified, + ), + ], + ), + ); + + await expectLater( + wallet.confirmSend(txData: prepared.copyWith(raw: 'ff')), + throwsA(isA()), + ); + await expectLater( + wallet.confirmSend( + txData: prepared.copyWith( + recipients: [ + prepared.recipients!.single.copyWith( + address: 'u1review-tampered', + ), + ], + ), + ), + throwsA(isA()), + ); + expect(service.broadcastPrepared, isNull); + await wallet.cancelSend(txData: prepared); + await wallet.exit(); + }, + ); + + test( + 'production routing refuses memo bytes for actual transparent output', + () async { + const phrase = + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about'; + final seed = zcash.nativeMnemonicToSeed(phrase); + final address = await zcash.deriveAddress( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.mainnet, + ); + final state = zcash.ZcashWalletSyncState.atBirthday( + cursor: zcash.ZcashLightwalletdSyncCursor.origin(height: 1), + network: zcash.ZcashAddressNetwork.mainnet, + accountFingerprint: 'fixture-account', + ); + + await expectLater( + const ZcashProductionWalletSendService().prepare( + ZcashSendPreparationRequest( + network: zcash.ZcashNetwork.mainnet, + sessionGeneration: 1, + state: state, + pendingSends: zcash.IronwoodPendingSendState(), + syncClient: SendClient(), + scanExecutor: UnusedScanExecutor(), + seedHex: seed.seedHex, + ironwoodChangeAddress: address.ua, + payments: [ + ZcashSendPayment( + recipient: address.transparentAddress!, + amountZatoshis: 40000, + memo: Uint8List.fromList([0, 255, 1]), + ), + ], + targetHeight: 43, + expiryHeight: 83, + resolveSaplingProvingParameters: () => + throw StateError('must not resolve proving parameters'), + ), + ), + throwsA( + isA().having( + (e) => e.refusal, + 'refusal', + zcash.ProposalRoutingRefusal.transparentMemo, + ), + ), + ); + }, + ); + + test('a wallet without Ironwood notes reports insufficient funds for a ' + 'transparent payment', () async { + const phrase = + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about'; + final seed = zcash.nativeMnemonicToSeed(phrase); + final address = await zcash.deriveAddress( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.mainnet, + ); + final state = zcash.ZcashWalletSyncState.atBirthday( + cursor: zcash.ZcashLightwalletdSyncCursor.origin(height: 1), + network: zcash.ZcashAddressNetwork.mainnet, + accountFingerprint: 'fixture-account', + ); + + await expectLater( + const ZcashProductionWalletSendService().prepare( + ZcashSendPreparationRequest( + network: zcash.ZcashNetwork.mainnet, + sessionGeneration: 1, + state: state, + pendingSends: zcash.IronwoodPendingSendState(), + syncClient: SendClient(), + scanExecutor: UnusedScanExecutor(), + seedHex: seed.seedHex, + ironwoodChangeAddress: address.ua, + payments: [ + ZcashSendPayment( + recipient: address.transparentAddress!, + amountZatoshis: 40000, + ), + ], + targetHeight: 43, + expiryHeight: 83, + resolveSaplingProvingParameters: () => + fail('a transparent payment needs no Sapling parameters'), + ), + ), + throwsA( + isA().having( + (error) => error.refusal, + 'refusal', + zcash.IronwoodSelectionRefusal.insufficientFunds, + ), + ), + ); + }); + + test('production prepares and durably reserves Ironwood payments to every ' + 'ordinary destination pool', () async { + const phrase = + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about'; + final seed = zcash.nativeMnemonicToSeed(phrase); + final address = await zcash.deriveAddress( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.regtest, + ); + final parameterRoot = await Directory.systemTemp.createTemp( + 'stack_zcash_routed_params_', + ); + addTearDown(() => parameterRoot.delete(recursive: true)); + final spendBytes = [1, 2, 3]; + final outputBytes = [4, 5, 6]; + final manifest = zcash.SaplingParameterManifest( + version: 'fixture-v1', + spend: zcash.SaplingParameterArtifact( + fileName: 'spend.params', + expectedBytes: spendBytes.length, + sha256Hex: sha256.convert(spendBytes).toString(), + ), + output: zcash.SaplingParameterArtifact( + fileName: 'output.params', + expectedBytes: outputBytes.length, + sha256Hex: sha256.convert(outputBytes).toString(), + ), + ); + final parameters = + await zcash.SaplingProvingParameterCache( + cacheRoot: parameterRoot, + manifest: manifest, + ).resolve( + source: FixtureParameterSource({ + manifest.spend.fileName: spendBytes, + manifest.output.fileName: outputBytes, + }), + ); + var provingParameterResolutions = 0; + + for (final destination in [ + ( + address: address.ua, + pool: zcash.ProposalOutputPool.ironwood, + pendingPool: zcash.IronwoodDestinationPool.ironwood, + ), + ( + address: address.saplingAddress!, + pool: zcash.ProposalOutputPool.sapling, + pendingPool: zcash.IronwoodDestinationPool.sapling, + ), + ( + address: address.transparentAddress!, + pool: zcash.ProposalOutputPool.transparent, + pendingPool: zcash.IronwoodDestinationPool.transparent, + ), + ]) { + final state = _ironwoodFundedState(); + final pending = zcash.IronwoodPendingSendState(); + final backend = FixtureIronwoodPaymentBackend(); + final prepared = + await ZcashProductionWalletSendService( + spendMaterialProvider: FixtureSpendMaterialProvider(), + ironwoodPaymentBackend: backend, + ).prepare( + ZcashSendPreparationRequest( + network: zcash.ZcashNetwork.regtest, + sessionGeneration: 1, + state: state, + pendingSends: pending, + syncClient: SendClient(chainName: 'test'), + scanExecutor: UnusedScanExecutor(), + seedHex: seed.seedHex, + ironwoodChangeAddress: address.ua, + payments: [ + ZcashSendPayment( + recipient: destination.address, + amountZatoshis: 40000, + ), + ], + targetHeight: 43, + expiryHeight: 83, + resolveSaplingProvingParameters: () async { + provingParameterResolutions++; + return parameters; + }, + regtestNu63ActivationHeight: 40, + ), + ); + + expect(prepared, isA()); + expect(prepared.actualOutputPool, destination.pool); + expect(prepared.encodedRecipient, destination.address); + expect(pending.records, hasLength(1)); + expect(pending.records.single.recipient, destination.address); + expect( + pending.records.single.actualDestinationPool, + destination.pendingPool, + ); + expect(pending.records.single.amountZatoshis, 40000); + expect(pending.records.single.feeZatoshis, 10000); + final build = backend.builds.single; + expect( + build.provingParameters != null, + destination.pool == zcash.ProposalOutputPool.sapling, + ); + if (destination.pool == zcash.ProposalOutputPool.ironwood) { + expect(build.outputs, isEmpty); + expect(build.ironwoodOutput.address, destination.address); + } else { + expect(build.outputs.single.address, destination.address); + expect(build.ironwoodOutput.address, address.ua); + } + } + + expect(provingParameterResolutions, 1); + }); + + test('routed payment broadcast preserves restart, rejection, and ' + 'indeterminate reservation semantics', () async { + final acknowledged = await _prepareTransparentIronwoodPayment(); + final restored = zcash.IronwoodPendingSendState.fromJson( + acknowledged.pending.toJson(), + ); + var persisted = 0; + await acknowledged.service.broadcast( + prepared: acknowledged.prepared, + pendingSends: restored, + chainHeight: 43, + persist: () async { + persisted++; + }, + submit: (_) async => + const ZcashSubmissionAcknowledgement(errorCode: 0, errorMessage: ''), + ); + expect(persisted, 1); + expect( + restored.records.single.broadcastState, + zcash.IronwoodPendingBroadcastState.acknowledged, + ); + + final rejected = await _prepareTransparentIronwoodPayment(); + await expectLater( + rejected.service.broadcast( + prepared: rejected.prepared, + pendingSends: rejected.pending, + chainHeight: 43, + persist: () async {}, + submit: (_) async => throw const ZcashBroadcastRejectedException( + errorCode: -26, + message: 'consensus rejected', + ), + ), + throwsA( + isA().having( + (error) => error.refusal, + 'refusal', + zcash.IronwoodBroadcastRefusal.rejected, + ), + ), + ); + expect(rejected.pending.records, isEmpty); + + final indeterminate = await _prepareTransparentIronwoodPayment(); + await expectLater( + indeterminate.service.broadcast( + prepared: indeterminate.prepared, + pendingSends: indeterminate.pending, + chainHeight: 43, + persist: () async {}, + submit: (_) async => throw StateError('connection closed'), + ), + throwsA( + isA().having( + (error) => error.refusal, + 'refusal', + zcash.IronwoodBroadcastRefusal.undetermined, + ), + ), + ); + expect( + indeterminate.pending.records.single.broadcastState, + zcash.IronwoodPendingBroadcastState.indeterminate, + ); + }); + + test( + 'a send anchors below the tip and spends only notes that deep', + () async { + // The tip is block 42 and the anchor three blocks below it. + final provider = FixtureSpendMaterialProvider(); + await _prepareTransparentIronwoodPayment(provider: provider); + expect(provider.anchors, [39]); + + // A note in block 40 is not in the tree of block 39. + await expectLater( + _prepareTransparentIronwoodPayment(provider: provider, noteHeight: 40), + throwsA( + isA().having( + (e) => e.refusal, + 'refusal', + zcash.IronwoodSelectionRefusal.insufficientFunds, + ), + ), + ); + expect(provider.anchors, [39]); + }, + ); + + test('a node that refuses a resubmitted send does not free its ' + 'notes', () async { + const refusal = ZcashBroadcastRejectedException( + errorCode: -27, + message: 'transaction already in block chain', + ); + Future submit( + ZcashWalletSendService service, + ZcashPreparedWalletSend prepared, + zcash.IronwoodPendingSendState pending, + Object error, + ) => service.broadcast( + prepared: prepared, + pendingSends: pending, + chainHeight: 43, + persist: () async {}, + submit: (_) async => throw error, + ); + + final single = await _prepareTransparentIronwoodPayment(); + final batch = await _prepareMultiIronwoodPayment(); + for (final (service, prepared, pending) in [ + (single.service, single.prepared, single.pending), + (const ZcashProductionWalletSendService(), batch.prepared, batch.pending), + ]) { + // The first submission ends without an answer: the node may have it. + await expectLater( + submit(service, prepared, pending, StateError('connection closed')), + throwsA(anything), + ); + expect( + pending.records.single.broadcastState, + zcash.IronwoodPendingBroadcastState.indeterminate, + ); + + // A node that has the transaction refuses the copy. Freeing the notes + // on that answer would let a second payment be built. + await expectLater( + submit(service, prepared, pending, refusal), + throwsA(anything), + ); + expect( + pending.records.single.broadcastState, + zcash.IronwoodPendingBroadcastState.indeterminate, + ); + expect(pending.reservedNullifiersAt(43), isNotEmpty); + } + + // The refusal of a first submission does free them. + final refused = await _prepareMultiIronwoodPayment(); + await expectLater( + submit( + const ZcashProductionWalletSendService(), + refused.prepared, + refused.pending, + refusal, + ), + throwsA(isA()), + ); + expect(refused.pending.records, isEmpty); + }); + + test( + 'confirmed history omits plaintext shielded recipients and memos', + () async { + final fixture = await _prepareMultiIronwoodPayment(); + final record = fixture.pending.records.single; + final state = fixture.state; + state.ironwood.apply( + zcash.ZcashScanResult( + scannedBlocks: 3, + discoveredNotes: 0, + totalValue: 0, + notes: const [], + spends: [ + zcash.ZcashObservedSpend( + height: 43, + tx: zcash.reverseTxidByteOrder(record.txid), + pool: 'ironwood', + nullifier: 'bb' * 32, + index: 0, + ), + ], + scannedHeightRange: const zcash.CompactBlockScanRange( + start: 41, + end: 43, + ), + ironwoodAnchor: 'dd' * 32, + ), + accountFingerprint: state.accountFingerprint, + ); + + final history = const ZcashStackStateMapper(walletId: 'history-wallet') + .transactions(state.history(), pendingSends: fixture.pending); + final transaction = history.singleWhere( + (transaction) => transaction.txid == record.txid, + ); + final external = transaction.outputs.where( + (output) => !output.walletOwns, + ); + expect(external, hasLength(1)); + expect(external.single.addresses, isEmpty); + expect(external.single.value, BigInt.from(40000)); + final metadata = + jsonDecode(transaction.otherData!) as Map; + expect(metadata, isNot(contains('zcashPaymentOutputs'))); + }, + ); + + test( + 'restart rehydrates and broadcasts only the exact persisted artifact', + () async { + final fixture = await _prepareMultiIronwoodPayment(); + final restored = zcash.IronwoodPendingSendState.fromJson( + (jsonDecode(jsonEncode(fixture.pending.toJson())) as Map) + .cast(), + ); + final record = restored.records.single; + final artifact = ZcashRecoveredPreparedSend( + record: record, + notes: fixture.state.ironwood.notes + .where( + (note) => + note.nullifier != null && + record.selectedNullifiers.contains(note.nullifier), + ) + .toList(), + sessionGeneration: 7, + ); + expect(artifact.transactionHex, record.transactionHex); + expect(artifact.txid, record.txid); + expect(artifact.paymentOutputs.map((output) => output.encodedRecipient), [ + fixture.address, + fixture.address, + ]); + expect(artifact.paymentOutputs.map((output) => output.memo), [ + [1], + [2], + ]); + + var expiredPersisted = false; + var expiredSubmitted = false; + await expectLater( + const ZcashProductionWalletSendService().broadcast( + prepared: artifact, + pendingSends: restored, + chainHeight: record.expiryHeight, + persist: () async => expiredPersisted = true, + submit: (_) async { + expiredSubmitted = true; + return const ZcashSubmissionAcknowledgement( + errorCode: 0, + errorMessage: '', + ); + }, + ), + throwsA( + isA().having( + (error) => error.refusal, + 'refusal', + zcash.IronwoodPendingSendRefusal.expiredRequiresRebuild, + ), + ), + ); + expect(expiredPersisted, isFalse); + expect(expiredSubmitted, isFalse); + expect( + restored.records.single.broadcastState, + zcash.IronwoodPendingBroadcastState.prepared, + ); + + var persisted = 0; + await const ZcashProductionWalletSendService().broadcast( + prepared: artifact, + pendingSends: restored, + chainHeight: 43, + persist: () async => persisted++, + submit: (transactionHex) async { + expect(transactionHex, record.transactionHex); + return const ZcashSubmissionAcknowledgement( + errorCode: 0, + errorMessage: '', + ); + }, + ); + expect(persisted, 1); + expect( + restored.records.single.broadcastState, + zcash.IronwoodPendingBroadcastState.acknowledged, + ); + + final tamperedJson = (jsonDecode( + jsonEncode(fixture.pending.toJson()), + ) as Map).cast(); + final tamperedRecord = + (tamperedJson['records']! as List).single as Map; + final tamperedOutputs = tamperedRecord['payment_outputs'] as List; + (tamperedOutputs.last as Map)['memo'] = '03'; + final tampered = zcash.IronwoodPendingSendState.fromJson(tamperedJson); + await expectLater( + const ZcashProductionWalletSendService().broadcast( + prepared: artifact, + pendingSends: tampered, + chainHeight: 43, + persist: () async {}, + submit: (_) async => const ZcashSubmissionAcknowledgement( + errorCode: 0, + errorMessage: '', + ), + ), + throwsA(isA()), + ); + }, + ); + + for (final (scenario, name) in [ + ( + 'resumed', + 'real wallet restart resumes encrypted artifact and discard releases it', + ), + ( + 'mined', + 'a send that a block already holds is not offered again after a restart', + ), + ( + 'left prepared', + 'a new send frees the notes of one that was only prepared before a ' + 'restart', + ), + ( + 'left submitting', + 'a new send keeps the notes of one that was being submitted before a ' + 'restart', + ), + ('refused', 'a send the node refuses is no longer prepared'), + ( + 'lost', + 'a send whose submission had no answer is submitted again when it is ' + 'confirmed again', + ), + ]) { + test(name, () async { + final mined = scenario == 'mined'; + final secrets = MemorySecrets(); + final original = await _wallet( + SendClient(chainName: 'test'), + RecordingSendService(), + 'restart-user-flow-$scenario', + coin: Zcash.regtest(), + secureStorage: secrets, + restoreHeight: 1, + ); + final walletId = original.walletId; + await original.exit(); + + const phrase = + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about'; + final seed = zcash.nativeMnemonicToSeed(phrase); + final metadata = zcash.deriveNativeAccountMetadata( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.regtest, + ); + final fixture = await _prepareMultiIronwoodPayment(); + const coveredRange = zcash.CompactBlockScanRange(start: 39, end: 40); + const emptyCoveredScan = zcash.ZcashScanResult( + scannedBlocks: 2, + discoveredNotes: 0, + totalValue: 0, + notes: [], + scannedHeightRange: coveredRange, + ); + fixture.state.sapling.apply( + emptyCoveredScan, + accountFingerprint: fixture.state.accountFingerprint, + ); + fixture.state.orchard.apply( + emptyCoveredScan, + accountFingerprint: fixture.state.accountFingerprint, + ); + const caughtUpScan = zcash.ZcashScanResult( + scannedBlocks: 2, + discoveredNotes: 0, + totalValue: 0, + notes: [], + scannedHeightRange: zcash.CompactBlockScanRange(start: 41, end: 42), + ); + fixture.state.sapling.apply( + caughtUpScan, + accountFingerprint: fixture.state.accountFingerprint, + ); + fixture.state.orchard.apply( + caughtUpScan, + accountFingerprint: fixture.state.accountFingerprint, + ); + final record = fixture.pending.records.single; + fixture.state.ironwood.apply( + mined + ? zcash.ZcashScanResult( + scannedBlocks: 2, + discoveredNotes: 0, + totalValue: 0, + notes: const [], + scannedHeightRange: caughtUpScan.scannedHeightRange, + spends: [ + for (final (index, nullifier) + in record.selectedNullifiers.indexed) + zcash.ZcashObservedSpend( + height: 42, + tx: zcash.reverseTxidByteOrder(record.txid), + pool: 'ironwood', + nullifier: nullifier, + index: index, + ), + ], + ) + : caughtUpScan, + accountFingerprint: fixture.state.accountFingerprint, + ); + if (mined) { + // Submitted before the restart, with no answer from the node. + fixture.pending + ..markSubmitting(record.txid) + ..markIndeterminate(record.txid); + } else if (scenario == 'left submitting') { + // The wallet closed while the node had not answered. + fixture.pending.markSubmitting(record.txid); + } + final alignedState = zcash.ZcashWalletSyncState( + // The persisted fixture is caught up through height 42. Recovery now + // refreshes before examining reservations, so its cursor must agree + // with the lightwalletd tip instead of relying on cached inspection. + cursor: zcash.ZcashLightwalletdSyncCursor.origin(height: 43), + network: fixture.state.network, + accountFingerprint: fixture.state.accountFingerprint, + sapling: fixture.state.sapling, + orchard: fixture.state.orchard, + ironwood: fixture.state.ironwood, + transparent: fixture.state.transparent, + ); + final reboundState = ZcashPersistedWalletState( + syncState: _withAccountFingerprint(alignedState, metadata.fingerprint), + observedChainHeight: 42, + ); + final root = await StackFileSystem.applicationRootDirectory(); + final stateStore = ZcashEncryptedWalletStateStore( + path: path.join(root.path, 'zcash', '$walletId.state'), + walletId: walletId, + network: zcash.ZcashAddressNetwork.regtest.name, + accountFingerprint: metadata.fingerprint, + secureStorage: secrets, + ); + final pendingStore = ZcashEncryptedPendingSendStore( + path: path.join(root.path, 'zcash', '$walletId.pending'), + walletId: walletId, + network: zcash.ZcashAddressNetwork.regtest.name, + accountFingerprint: metadata.fingerprint, + secureStorage: secrets, + ); + await stateStore.save(reboundState); + await pendingStore.save(fixture.pending); + + final restored = await Wallet.load( + walletId: walletId, + mainDB: MainDB.instance, + secureStorageInterface: secrets, + nodeService: SendNodes(), + prefs: SessionPrefs(), + ) as ZcashWallet; + final client = RefusingSendClient(chainName: 'test'); + restored.configureAccountSessionFactory( + (network) => + ZcashAccountSession(network: network, clientFactory: (_) => client), + ); + restored.configureRegtestConsensus(nu63ActivationHeight: 130); + if (scenario.startsWith('left')) { + // The user does not resume the send and prepares another one. + restored.configureSendService(RecordingSendService()); + await restored.init(); + await restored.prepareSend( + txData: TxData( + recipients: [ + TxRecipient( + address: (await restored.getCurrentReceivingAddress())!.value, + amount: Amount(rawValue: BigInt.from(40000), fractionDigits: 8), + isChange: false, + addressType: AddressType.zcashUnified, + ), + ], + ), + ); + final left = (await pendingStore.load()).records; + if (scenario == 'left prepared') { + // It never left the wallet. + expect(left, isEmpty); + } else { + // It may have reached the node. + expect(left.single.txid, fixture.prepared.txid); + expect( + left.single.broadcastState, + zcash.IronwoodPendingBroadcastState.indeterminate, + ); + } + await restored.exit(); + return; + } + await restored.init(); + + final recovered = await restored.recoverPreparedSend(); + if (mined) { + expect(recovered, isNull); + expect( + (await pendingStore.load()).records.single.txid, + fixture.prepared.txid, + ); + await restored.exit(); + return; + } + expect(recovered, isNotNull); + expect(recovered!.raw, fixture.prepared.transactionHex); + expect(recovered.txid, fixture.prepared.txid); + expect(recovered.recipients!.map((recipient) => recipient.address), [ + fixture.address, + fixture.address, + ]); + + if (scenario == 'refused') { + client.refuse = true; + await expectLater( + restored.confirmSend(txData: recovered), + throwsA(isA()), + ); + expect((await pendingStore.load()).records, isEmpty); + // Nothing is prepared any more: the same confirmation says so, and + // there is nothing to resume. + await expectLater( + restored.confirmSend(txData: recovered), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('exact prepared transaction artifact'), + ), + ), + ); + expect(await restored.recoverPreparedSend(), isNull); + await restored.exit(); + return; + } + if (scenario == 'lost') { + client.lose = true; + await expectLater( + restored.confirmSend(txData: recovered), + throwsA(anything), + ); + expect( + (await pendingStore.load()).records.single.broadcastState, + zcash.IronwoodPendingBroadcastState.indeterminate, + ); + // It may have reached the node: confirming again submits the same + // transaction. + client.lose = false; + await restored.confirmSend(txData: recovered); + expect( + client.submitted.single + .map((byte) => byte.toRadixString(16).padLeft(2, '0')) + .join(), + fixture.prepared.transactionHex, + ); + expect( + (await pendingStore.load()).records.single.broadcastState, + zcash.IronwoodPendingBroadcastState.acknowledged, + ); + await restored.exit(); + return; + } + + await restored.cancelSend(txData: recovered); + expect((await pendingStore.load()).records, isEmpty); + await restored.exit(); + }); + } +} + +zcash.ZcashWalletSyncState _ironwoodFundedState({int noteHeight = 39}) { + const fingerprint = 'fixture-account'; + final state = zcash.ZcashWalletSyncState.atBirthday( + cursor: zcash.ZcashLightwalletdSyncCursor.origin(height: 1), + network: zcash.ZcashAddressNetwork.regtest, + accountFingerprint: fingerprint, + ); + state.ironwood.apply( + zcash.ZcashScanResult( + scannedBlocks: 2, + discoveredNotes: 1, + totalValue: 100000, + notes: [ + zcash.ZcashScannedNote( + // 39 is deep enough for the anchor of a send prepared at height 42. + height: noteHeight, + tx: 'aa' * 32, + output: 0, + value: 100000, + pool: 'ironwood', + nullifier: 'bb' * 32, + commitmentPosition: 0, + recipient: 'uregtest1-wallet-note', + rseed: '11' * 32, + rho: '22' * 32, + noteVersion: 'v3', + witness: '33' * 40, + ), + ], + scannedHeightRange: const zcash.CompactBlockScanRange(start: 39, end: 40), + ironwoodAnchor: 'cc' * 32, + ), + accountFingerprint: fingerprint, + ); + return state; +} + +Future< + ({ + ZcashProductionWalletSendService service, + zcash.IronwoodPendingSendState pending, + ZcashPreparedWalletSend prepared, + }) +> +_prepareTransparentIronwoodPayment({ + FixtureSpendMaterialProvider? provider, + int noteHeight = 39, +}) async { + const phrase = + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about'; + final seed = zcash.nativeMnemonicToSeed(phrase); + final address = await zcash.deriveAddress( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.regtest, + ); + final pending = zcash.IronwoodPendingSendState(); + final service = ZcashProductionWalletSendService( + spendMaterialProvider: provider ?? FixtureSpendMaterialProvider(), + ironwoodPaymentBackend: FixtureIronwoodPaymentBackend(), + ); + final prepared = await service.prepare( + ZcashSendPreparationRequest( + network: zcash.ZcashNetwork.regtest, + sessionGeneration: 1, + state: _ironwoodFundedState(noteHeight: noteHeight), + pendingSends: pending, + syncClient: SendClient(chainName: 'test'), + scanExecutor: UnusedScanExecutor(), + seedHex: seed.seedHex, + ironwoodChangeAddress: address.ua, + payments: [ + ZcashSendPayment( + recipient: address.transparentAddress!, + amountZatoshis: 40000, + ), + ], + targetHeight: 43, + expiryHeight: 83, + resolveSaplingProvingParameters: () => + throw StateError('transparent output needs no Sapling parameters'), + regtestNu63ActivationHeight: 40, + ), + ); + return (service: service, pending: pending, prepared: prepared); +} + +Future< + ({ + zcash.IronwoodPendingSendState pending, + zcash.ZcashWalletSyncState state, + ZcashPreparedWalletSend prepared, + String address, + }) +> +_prepareMultiIronwoodPayment() async { + const phrase = + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about'; + final seed = zcash.nativeMnemonicToSeed(phrase); + final address = await zcash.deriveAddress( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.regtest, + ); + final pending = zcash.IronwoodPendingSendState(); + final state = _ironwoodFundedState(); + final prepared = + await ZcashProductionWalletSendService( + spendMaterialProvider: FixtureSpendMaterialProvider(), + ironwoodPaymentBackend: FixtureIronwoodPaymentBackend(), + ).prepare( + ZcashSendPreparationRequest( + network: zcash.ZcashNetwork.regtest, + sessionGeneration: 1, + state: state, + pendingSends: pending, + syncClient: SendClient(chainName: 'test'), + scanExecutor: UnusedScanExecutor(), + seedHex: seed.seedHex, + ironwoodChangeAddress: address.ua, + payments: [ + ZcashSendPayment( + recipient: address.ua, + amountZatoshis: 20000, + memo: Uint8List.fromList([1]), + ), + ZcashSendPayment( + recipient: address.ua, + amountZatoshis: 20000, + memo: Uint8List.fromList([2]), + ), + ], + targetHeight: 43, + expiryHeight: 83, + resolveSaplingProvingParameters: () => + throw StateError('Ironwood outputs need no Sapling parameters'), + regtestNu63ActivationHeight: 40, + ), + ); + return ( + pending: pending, + state: state, + prepared: prepared, + address: address.ua, + ); +} + +/// [state] as the account with [fingerprint] would hold it, so a fixture +/// scanned for a placeholder account can be stored for a real wallet. +zcash.ZcashWalletSyncState _withAccountFingerprint( + zcash.ZcashWalletSyncState state, + String fingerprint, +) { + final json = state.toJson(); + json['account_fingerprint'] = fingerprint; + for (final field in ['sapling', 'orchard', 'ironwood', 'transparent']) { + final store = (json[field] as Map).cast(); + if (store['account_fingerprint'] != null) { + store['account_fingerprint'] = fingerprint; + } + json[field] = store; + } + return zcash.ZcashWalletSyncState.fromJson(json); +} + +Future _wallet( + SendClient client, + ZcashWalletSendService service, + String id, { + Zcash? coin, + SecureStorageInterface? secureStorage, + int restoreHeight = 43, + ZcashSaplingParameterResolver? saplingParameterResolver, +}) async { + final currency = coin ?? Zcash(CryptoCurrencyNetwork.main); + final wallet = await Wallet.create( + walletInfo: WalletInfo( + walletId: 'zcash-send-$id', + name: 'Zcash send fixture', + mainAddressType: AddressType.zcashUnified, + coinName: currency.identifier, + restoreHeight: restoreHeight, + ), + mainDB: MainDB.instance, + secureStorageInterface: secureStorage ?? MemorySecrets(), + nodeService: SendNodes(), + prefs: SessionPrefs(), + mnemonic: + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about', + mnemonicPassphrase: '', + ) as ZcashWallet; + wallet.configureAccountSessionFactory( + (network) => + ZcashAccountSession(network: network, clientFactory: (_) => client), + ); + wallet.configureSendService(service); + if (saplingParameterResolver != null) { + wallet.configureSaplingParameterResolver(saplingParameterResolver); + } + if (currency.nativeNetwork == zcash.ZcashNetwork.regtest) { + wallet.configureRegtestConsensus(nu63ActivationHeight: 130); + } + await wallet.init(isRestore: true); + return wallet; +} diff --git a/test/wallets/zcash_wallet_session_test.dart b/test/wallets/zcash_wallet_session_test.dart new file mode 100644 index 000000000..27591e172 --- /dev/null +++ b/test/wallets/zcash_wallet_session_test.dart @@ -0,0 +1,1301 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:stackwallet/db/isar/main_db.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/address.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/transaction.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/v2/transaction_v2.dart'; +import 'package:stackwallet/models/node_model.dart'; +import 'package:stackwallet/services/node_service.dart'; +import 'package:stackwallet/utilities/stack_file_system.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:stackwallet/wallets/isar/models/wallet_info.dart'; +import 'package:stackwallet/wallets/wallet/impl/zcash_wallet.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_account_session.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 '../support/isar_test_utils.dart'; +import 'support/xelis_test_fakes.dart'; +import 'support/zcash_test_coins.dart'; + +List _pools(TransactionV2 transaction) => + (jsonDecode(transaction.otherData!) + as Map)[ZcashStackStateMapper.poolsKey] + as List; + +class MutableZcashNodes extends Fake implements NodeService { + MutableZcashNodes(this.primary); + + NodeModel primary; + + @override + NodeModel? getPrimaryNodeFor({required CryptoCurrency currency}) => primary; +} + +zcash.ZcashTransactionSummary transparentSummary({ + required String txid, + List> inputs = const [], + List> outputs = const [], +}) => zcash.ZcashTransactionSummary.fromJson({ + 'network': 'mainnet', + 'txid': txid, + 'version': 'v5', + 'header': 2147483653, + 'version_group_id': 654776626, + 'consensus_branch_id': 'nu5', + 'consensus_branch_id_hex': 'c2d6d0b4', + 'lock_time': 0, + 'expiry_height': 0, + 'transparent': { + 'present': true, + 'vin': inputs.length, + 'vout': outputs.length, + 'is_coinbase': false, + 'inputs': inputs, + 'outputs': outputs, + }, + 'sapling': {'present': false, 'spends': 0, 'outputs': 0}, + 'orchard': {'present': false, 'actions': 0}, + 'ironwood': {'present': false, 'actions': 0}, + 'sprout': {'present': false, 'joinsplits': 0}, +}); + +class WalletSessionClient implements ZcashLightwalletdClient { + WalletSessionClient({ + required this.chainName, + required this.tipHeight, + this.beforeTipReturn, + this.beforeClose, + }); + + final String chainName; + final int tipHeight; + final Future Function()? beforeTipReturn; + final Future Function()? beforeClose; + int infoCalls = 0; + int tipCalls = 0; + int closeCalls = 0; + + @override + Future getInfo() async { + infoCalls++; + return zcash.LightdInfo(chainName: chainName); + } + + @override + Future getTipHeight() async { + tipCalls++; + await beforeTipReturn?.call(); + return tipHeight; + } + + @override + Future close() async { + closeCalls++; + await beforeClose?.call(); + } +} + +class SyncWalletSessionClient extends WalletSessionClient + implements ZcashLightwalletdSyncClient, ZcashLightwalletdTransparentClient { + SyncWalletSessionClient({ + required super.chainName, + required super.tipHeight, + super.beforeClose, + this.restoredTransparentOutputs = const [], + this.activeTransparentAddresses = const {}, + this.authenticatedTransparentTransactions = const [], + this.transparentRefreshStarted, + this.transparentRefreshRelease, + }); + + final List< + ({ + zcash.ZcashTransparentReceiverScope scope, + int childIndex, + int valueZatoshis, + }) + > + restoredTransparentOutputs; + final Set activeTransparentAddresses; + final List + authenticatedTransparentTransactions; + final Completer? transparentRefreshStarted; + final Completer? transparentRefreshRelease; + bool failTip = false; + int treeStateCalls = 0; + int transparentRefreshCalls = 0; + int? receivedMaxRangeSize; + int? receivedMaxUtxos; + List? queriedTransparentAddresses; + List? queriedTransparentReceivers; + final List> transparentActivityQueries = []; + final List<({int startHeight, int endHeight})> transparentActivityRanges = []; + String transparentTipHash = '44' * 32; + + @override + Future getTransparentAddressActivity( + List addresses, { + required int startHeight, + required int chainHeight, + }) async { + transparentActivityQueries.add([...addresses]); + transparentActivityRanges.add(( + startHeight: startHeight, + endHeight: chainHeight, + )); + return ZcashTransparentActivityResult( + activeAddresses: addresses + .where(activeTransparentAddresses.contains) + .toSet(), + transactions: authenticatedTransparentTransactions, + ); + } + + @override + Future getTransparentRefresh( + zcash.ZcashTransparentState state, { + int maxRangeSize = 1000, + int maxUtxos = 10000, + }) async { + transparentRefreshCalls++; + transparentRefreshStarted?.complete(); + await transparentRefreshRelease?.future; + receivedMaxRangeSize = maxRangeSize; + receivedMaxUtxos = maxUtxos; + queriedTransparentAddresses = state.addresses; + queriedTransparentReceivers = state.receivers; + final restored = [ + for (final output in restoredTransparentOutputs) + ( + output, + state.receivers.singleWhere( + (receiver) => + receiver.scope == output.scope && + receiver.childIndex == output.childIndex, + ), + ), + ]; + return zcash.ZcashTransparentRefresh( + network: state.network, + accountFingerprint: state.accountFingerprint, + queriedAddresses: state.addresses, + chainHeight: tipHeight, + chainTipHash: transparentTipHash, + canonicalBlockHashes: {tipHeight: transparentTipHash}, + unspentOutputs: [ + for (final (output, receiver) in restored) + zcash.ZcashTransparentOutputObservation( + address: receiver.address, + protocolTxid: + (output.scope == zcash.ZcashTransparentReceiverScope.external + ? '11' + : '22') * + 32, + outputIndex: output.childIndex, + scriptHex: '51', + valueZatoshis: output.valueZatoshis, + minedHeight: tipHeight, + blockHash: transparentTipHash, + blockTime: 1700000000, + creationFeeZatoshis: 1000, + isCoinbase: false, + ), + ], + observedSpends: const [], + ); + } + + @override + Future getTipHeight() { + if (failTip) throw StateError('test tip failure'); + return super.getTipHeight(); + } + + @override + Future getBlockHash(int height) async => null; + + @override + Future getBlockRange(int start, int end) => + throw StateError('caught-up fixture must not request blocks'); + + @override + Future getTreeState(int height) async { + treeStateCalls++; + return zcash.TreeState( + hash: '0000000000000000000000000000000000000000000000000000000000000000', + height: height, + time: 1, + ); + } +} + +NodeModel walletNode({required String host, required String id}) => NodeModel( + host: host, + port: 443, + name: id, + id: id, + useSSL: true, + enabled: true, + coinName: 'zcash', + isFailover: false, + isDown: false, + torEnabled: false, + clearnetEnabled: true, + isPrimary: true, +); + +void main() { + listZcashCoins(); + TestWidgetsFlutterBinding.ensureInitialized(); + setUpAll(initializeTestIsar); + late Directory root; + + setUpAll(() async { + if (!(Platform.isWindows || Platform.isLinux || Platform.isMacOS)) { + throw UnsupportedError('Run this storage scenario on a desktop host.'); + } + root = await Directory.systemTemp.createTemp('stack_zcash_session_'); + StackFileSystem.setDesktopOverrideDir(root.path); + }); + tearDownAll(() => root.delete(recursive: true)); + + setUp(() async { + await MainDB.instance.initMainDB(); + addTearDown(() async { + if (MainDB.instance.isar.isOpen) await MainDB.instance.isar.close(); + }); + }); + + test( + 'new wallet persists the validated next lightwalletd height before sync', + () async { + final node = walletNode(host: 'https://birthday.example', id: 'birthday'); + final client = SyncWalletSessionClient(chainName: 'main', tipHeight: 42); + final wallet = await Wallet.create( + walletInfo: WalletInfo( + walletId: 'zcash-new-wallet-birthday', + name: 'Zcash birthday fixture', + mainAddressType: AddressType.zcashUnified, + coinName: 'zcash', + ), + mainDB: MainDB.instance, + secureStorageInterface: MemorySecrets(), + nodeService: MutableZcashNodes(node), + prefs: SessionPrefs(), + mnemonic: + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about', + mnemonicPassphrase: '', + ) as ZcashWallet; + wallet.configureAccountSessionFactory( + (network) => + ZcashAccountSession(network: network, clientFactory: (_) => client), + ); + + await wallet.init(isRestore: false); + + expect(wallet.info.restoreHeight, 43); + expect( + (await MainDB.instance.isar.walletInfo + .where() + .walletIdEqualTo(wallet.walletId) + .findFirst()) + ?.restoreHeight, + 43, + ); + // The connection that found the birthday is kept for the first sync. + expect(client.treeStateCalls, 1); + await wallet.updateChainHeight(); + expect(client.treeStateCalls, 1); + expect(client.closeCalls, 0); + await wallet.exit(); + }, + ); + + test( + 'restore without a positive birthday fails before node access', + () async { + final node = walletNode(host: 'https://restore.example', id: 'restore'); + final client = SyncWalletSessionClient(chainName: 'main', tipHeight: 42); + final wallet = await Wallet.create( + walletInfo: WalletInfo( + walletId: 'zcash-missing-restore-birthday', + name: 'Zcash missing birthday fixture', + mainAddressType: AddressType.zcashUnified, + coinName: 'zcash', + ), + mainDB: MainDB.instance, + secureStorageInterface: MemorySecrets(), + nodeService: MutableZcashNodes(node), + prefs: SessionPrefs(), + mnemonic: + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about', + mnemonicPassphrase: '', + ) as ZcashWallet; + wallet.configureAccountSessionFactory( + (network) => + ZcashAccountSession(network: network, clientFactory: (_) => client), + ); + + await expectLater( + wallet.init(isRestore: true), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('explicit positive block height'), + ), + ), + ); + + expect(client.infoCalls, 0); + expect(client.tipCalls, 0); + expect(client.closeCalls, 0); + await wallet.exit(); + }, + ); + + test('new wallet rejects an out-of-range lightwalletd tip', () async { + final node = walletNode(host: 'https://invalid-tip.example', id: 'bad-tip'); + final client = SyncWalletSessionClient(chainName: 'main', tipHeight: -1); + final wallet = await Wallet.create( + walletInfo: WalletInfo( + walletId: 'zcash-invalid-tip-birthday', + name: 'Zcash invalid tip fixture', + mainAddressType: AddressType.zcashUnified, + coinName: 'zcash', + ), + mainDB: MainDB.instance, + secureStorageInterface: MemorySecrets(), + nodeService: MutableZcashNodes(node), + prefs: SessionPrefs(), + mnemonic: + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about', + mnemonicPassphrase: '', + ) as ZcashWallet; + wallet.configureAccountSessionFactory( + (network) => + ZcashAccountSession(network: network, clientFactory: (_) => client), + ); + + await expectLater( + wallet.init(isRestore: false), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('lightwalletd tip must be between'), + ), + ), + ); + + expect(wallet.info.restoreHeight, 0); + expect(client.closeCalls, 1); + await wallet.exit(); + expect(client.closeCalls, 1); + }); + + test( + 'wallet init, updateNode, ping, and exit own one account session', + () async { + final firstNode = walletNode(host: 'https://first.example', id: 'first'); + final secondNode = walletNode( + host: 'https://second.example', + id: 'second', + ); + final nodes = MutableZcashNodes(firstNode); + final clients = [ + SyncWalletSessionClient(chainName: 'main', tipHeight: 42), + SyncWalletSessionClient(chainName: 'main', tipHeight: 43), + ]; + final openedEndpoints = []; + + final wallet = await Wallet.create( + walletInfo: WalletInfo( + walletId: 'zcash-session', + name: 'Zcash session fixture', + mainAddressType: AddressType.zcashUnified, + coinName: 'zcash', + restoreHeight: 43, + ), + mainDB: MainDB.instance, + secureStorageInterface: MemorySecrets(), + nodeService: nodes, + prefs: SessionPrefs(), + mnemonic: + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about', + mnemonicPassphrase: '', + ) as ZcashWallet; + wallet.configureAccountSessionFactory( + (network) => ZcashAccountSession( + network: network, + clientFactory: (endpoint) { + openedEndpoints.add(endpoint); + return clients[openedEndpoints.length - 1]; + }, + requestTimeout: const Duration(milliseconds: 100), + ), + ); + + // A wallet with a birthday opens without its node. + await wallet.init(isRestore: true); + expect(wallet.accountSessionGeneration, 0); + expect(openedEndpoints, isEmpty); + + expect(await wallet.pingCheck(), isTrue); + expect(wallet.accountSessionGeneration, 1); + expect(openedEndpoints.single.host, 'first.example'); + expect(await wallet.pingCheck(), isTrue); + expect(clients.first.infoCalls, 2); + expect(clients.first.tipCalls, 2); + + nodes.primary = secondNode; + await wallet.updateNode(); + expect(wallet.accountSessionGeneration, 2); + expect(openedEndpoints.last.host, 'second.example'); + expect(clients.first.closeCalls, 1); + expect(await wallet.pingCheck(), isTrue); + + await wallet.exit(); + await wallet.exit(); + expect(clients.first.closeCalls, 1); + expect(clients.last.closeCalls, 1); + }, + ); + + test('new wallet init failure after readiness closes the account ' + 'session', () async { + final nodes = MutableZcashNodes( + walletNode(host: 'https://ready.example', id: 'ready'), + ); + final client = WalletSessionClient( + chainName: 'main', + tipHeight: 42, + beforeTipReturn: () async { + await MainDB.instance.isar.close(); + }, + ); + final wallet = await Wallet.create( + walletInfo: WalletInfo( + walletId: 'zcash-init-rollback', + name: 'Zcash init rollback fixture', + mainAddressType: AddressType.zcashUnified, + coinName: 'zcash', + ), + mainDB: MainDB.instance, + secureStorageInterface: MemorySecrets(), + nodeService: nodes, + prefs: SessionPrefs(), + mnemonic: + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about', + mnemonicPassphrase: '', + ) as ZcashWallet; + wallet.configureAccountSessionFactory( + (network) => ZcashAccountSession( + network: network, + clientFactory: (_) => client, + requestTimeout: const Duration(milliseconds: 100), + ), + ); + + await expectLater(wallet.init(isRestore: false), throwsA(anything)); + + expect(client.infoCalls, 1); + expect(client.tipCalls, 1); + expect(client.closeCalls, 1); + await wallet.exit(); + expect(client.closeCalls, 1); + }); + + test('sync hooks share state and update Stack caches', () async { + final node = walletNode(host: 'https://sync.example', id: 'sync'); + final client = SyncWalletSessionClient(chainName: 'main', tipHeight: 42); + final wallet = await Wallet.create( + walletInfo: WalletInfo( + walletId: 'zcash-sync-hooks', + name: 'Zcash sync hooks fixture', + mainAddressType: AddressType.zcashUnified, + coinName: 'zcash', + restoreHeight: 43, + ), + mainDB: MainDB.instance, + secureStorageInterface: MemorySecrets(), + nodeService: MutableZcashNodes(node), + prefs: SessionPrefs(), + mnemonic: + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about', + mnemonicPassphrase: '', + ) as ZcashWallet; + wallet.configureAccountSessionFactory( + (network) => + ZcashAccountSession(network: network, clientFactory: (_) => client), + ); + await wallet.init(isRestore: true); + + await wallet.updateChainHeight(); + await Future.wait([wallet.updateTransactions(), wallet.updateBalance()]); + + expect(wallet.info.cachedChainHeight, 42); + expect(wallet.info.cachedBalance.total.raw, BigInt.zero); + expect(await wallet.updateUTXOs(), isFalse); + // One to open the connection and one for the sync, which the three + // updates of a refresh share. + expect(client.tipCalls, 2); + + // The next refresh syncs again. + await wallet.updateChainHeight(); + await Future.wait([wallet.updateTransactions(), wallet.updateBalance()]); + expect(client.tipCalls, 3); + await wallet.exit(); + }); + + test('closing a wallet during the scan of a restore stops the scan and ' + 'stores nothing of it', () async { + final refreshStarted = Completer(); + final releaseRefresh = Completer(); + final node = walletNode( + host: 'https://cancel-recovery.example', + id: 'cancel-recovery', + ); + final client = SyncWalletSessionClient( + chainName: 'main', + tipHeight: 42, + restoredTransparentOutputs: const [ + ( + scope: zcash.ZcashTransparentReceiverScope.external, + childIndex: 0, + valueZatoshis: 75000, + ), + ], + transparentRefreshStarted: refreshStarted, + transparentRefreshRelease: releaseRefresh, + ); + final wallet = await Wallet.create( + walletInfo: WalletInfo( + walletId: 'zcash-cancel-recovery', + name: 'Zcash cancellation fixture', + mainAddressType: AddressType.zcashUnified, + coinName: 'zcash', + restoreHeight: 43, + ), + mainDB: MainDB.instance, + secureStorageInterface: MemorySecrets(), + nodeService: MutableZcashNodes(node), + prefs: SessionPrefs(), + mnemonic: + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about', + mnemonicPassphrase: '', + ) as ZcashWallet; + wallet.configureAccountSessionFactory( + (network) => + ZcashAccountSession(network: network, clientFactory: (_) => client), + ); + await wallet.init(isRestore: true); + final initialTotal = wallet.info.cachedBalance.total.raw; + final initialSpendable = wallet.info.cachedBalance.spendable.raw; + final initialHeight = wallet.info.cachedChainHeight; + + // The restore returns once the node answers. The scan is the refresh + // it starts, which the views do not wait for. + await wallet.recover(isRescan: false).timeout(const Duration(seconds: 5)); + await refreshStarted.future.timeout(const Duration(seconds: 5)); + + await wallet.exit().timeout(const Duration(seconds: 1)); + + expect(client.closeCalls, 1); + expect(wallet.accountSessionGeneration, 0); + releaseRefresh.complete(); + await wallet.refresh(); + expect( + await MainDB.instance.isar.transactionV2s + .where() + .walletIdEqualTo(wallet.walletId) + .count(), + 0, + ); + expect(wallet.info.cachedBalance.total.raw, initialTotal); + expect(wallet.info.cachedBalance.spendable.raw, initialSpendable); + expect(wallet.info.cachedChainHeight, initialHeight); + + // Opened again, the wallet connects the next time it needs the node. + await wallet.init(); + expect(await wallet.pingCheck(), isTrue); + expect(wallet.accountSessionGeneration, isNonZero); + await wallet.exit(); + expect(client.closeCalls, 2); + expect(wallet.accountSessionGeneration, 0); + }); + + test('transparent receiver refresh reaches balance and history', () async { + const mnemonic = + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about'; + final seed = zcash.nativeMnemonicToSeed(mnemonic); + final viewing = zcash + .deriveNativeViewingKeys( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.mainnet, + ) + .transparent; + String receiver( + zcash.ZcashTransparentReceiverScope scope, + int childIndex, + ) => zcash.deriveNativeTransparentAddressFromViewingKey( + viewingKeyHex: scope == zcash.ZcashTransparentReceiverScope.external + ? viewing.externalIvk! + : viewing.internalIvk!, + network: zcash.ZcashNetwork.mainnet, + childIndex: childIndex, + scope: scope == zcash.ZcashTransparentReceiverScope.external + ? zcash.ZcashTransparentKeyScope.external + : zcash.ZcashTransparentKeyScope.internal, + ); + final node = walletNode( + host: 'https://transparent.example', + id: 'transparent', + ); + final nodes = MutableZcashNodes(node); + final secrets = MemorySecrets(); + final client = SyncWalletSessionClient( + chainName: 'main', + tipHeight: 42, + activeTransparentAddresses: { + receiver(zcash.ZcashTransparentReceiverScope.external, 19), + receiver(zcash.ZcashTransparentReceiverScope.external, 25), + receiver(zcash.ZcashTransparentReceiverScope.internal, 4), + }, + restoredTransparentOutputs: const [ + ( + scope: zcash.ZcashTransparentReceiverScope.external, + childIndex: 25, + valueZatoshis: 75000, + ), + ( + scope: zcash.ZcashTransparentReceiverScope.internal, + childIndex: 4, + valueZatoshis: 50000, + ), + ], + ); + final wallet = await Wallet.create( + walletInfo: WalletInfo( + walletId: 'zcash-transparent', + name: 'Zcash transparent fixture', + mainAddressType: AddressType.zcashUnified, + coinName: 'zcash', + restoreHeight: 43, + ), + mainDB: MainDB.instance, + secureStorageInterface: secrets, + nodeService: nodes, + prefs: SessionPrefs(), + mnemonic: mnemonic, + mnemonicPassphrase: '', + ) as ZcashWallet; + wallet.configureAccountSessionFactory( + (network) => + ZcashAccountSession(network: network, clientFactory: (_) => client), + ); + await wallet.init(isRestore: true); + + await wallet.recover(isRescan: false); + await wallet.refresh(); + + expect(client.transparentRefreshCalls, 1); + expect(client.receivedMaxRangeSize, 1000); + expect(client.receivedMaxUtxos, 10000); + final transparentRows = + (await MainDB.instance.getAddresses(wallet.walletId).findAll()).where( + (row) => row.type == AddressType.p2pkh, + ); + expect(transparentRows, hasLength(1)); + expect(client.queriedTransparentAddresses, hasLength(71)); + expect(client.transparentActivityQueries, hasLength(3)); + expect( + client.transparentActivityRanges, + everyElement((startHeight: 42, endHeight: 42)), + ); + expect( + client.queriedTransparentReceivers, + containsAll([ + isA() + .having( + (receiver) => receiver.scope, + 'scope', + zcash.ZcashTransparentReceiverScope.external, + ) + .having((receiver) => receiver.childIndex, 'childIndex', 25), + isA() + .having( + (receiver) => receiver.scope, + 'scope', + zcash.ZcashTransparentReceiverScope.internal, + ) + .having((receiver) => receiver.childIndex, 'childIndex', 4), + ]), + ); + expect(wallet.info.cachedBalance.total.raw, BigInt.from(125000)); + expect(wallet.info.cachedBalance.spendable.raw, BigInt.zero); + final transactions = await MainDB.instance.isar.transactionV2s + .where() + .walletIdEqualTo(wallet.walletId) + .findAll(); + expect(transactions, hasLength(2)); + expect(transactions.map(_pools), everyElement(equals(['transparent']))); + expect(transactions.every((tx) => tx.timestamp == 1700000000), isTrue); + expect(transactions.first.getFee(fractionDigits: 8).raw, BigInt.from(1000)); + + client.transparentTipHash = '55' * 32; + await expectLater(wallet.updateChainHeight(), throwsA(anything)); + final retained = + (await MainDB.instance.isar.transactionV2s + .where() + .walletIdEqualTo(wallet.walletId) + .findAll()) + .first; + expect(retained.blockHash, '44' * 32); + expect(wallet.info.cachedBalance.total.raw, BigInt.from(125000)); + await wallet.exit(); + + final restartClient = SyncWalletSessionClient( + chainName: 'main', + tipHeight: 42, + activeTransparentAddresses: { + receiver(zcash.ZcashTransparentReceiverScope.external, 19), + receiver(zcash.ZcashTransparentReceiverScope.external, 25), + receiver(zcash.ZcashTransparentReceiverScope.internal, 4), + }, + restoredTransparentOutputs: const [ + ( + scope: zcash.ZcashTransparentReceiverScope.external, + childIndex: 25, + valueZatoshis: 75000, + ), + ( + scope: zcash.ZcashTransparentReceiverScope.internal, + childIndex: 4, + valueZatoshis: 50000, + ), + ], + ); + final reopened = await Wallet.load( + walletId: wallet.walletId, + mainDB: MainDB.instance, + secureStorageInterface: secrets, + nodeService: nodes, + prefs: SessionPrefs(), + ) as ZcashWallet; + reopened.configureAccountSessionFactory( + (network) => ZcashAccountSession( + network: network, + clientFactory: (_) => restartClient, + ), + ); + await reopened.init(isRestore: false); + await reopened.recover(isRescan: false); + await reopened.refresh(); + + expect(restartClient.treeStateCalls, 0); + expect(restartClient.transparentRefreshCalls, 1); + expect(restartClient.queriedTransparentAddresses, hasLength(71)); + // The authenticated history frontier is durable, so reopening at the + // same tip refreshes the UTXO snapshot without re-querying raw history. + expect(restartClient.transparentActivityQueries, isEmpty); + expect(restartClient.transparentActivityRanges, isEmpty); + expect(reopened.info.cachedBalance.total.raw, BigInt.from(125000)); + + await reopened.recover(isRescan: true); + await reopened.refresh(); + + expect(restartClient.treeStateCalls, 1); + expect(restartClient.transparentRefreshCalls, 2); + expect(restartClient.queriedTransparentAddresses, hasLength(71)); + expect(restartClient.transparentActivityQueries, hasLength(1)); + expect(restartClient.transparentActivityRanges.single, ( + startHeight: 42, + endHeight: 42, + )); + expect(reopened.info.cachedBalance.total.raw, BigInt.from(125000)); + await reopened.exit(); + }); + + test( + 'restore reconstructs fully-spent transparent transaction history', + () async { + const mnemonic = + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about'; + final seed = zcash.nativeMnemonicToSeed(mnemonic); + final viewing = zcash + .deriveNativeViewingKeys( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.mainnet, + ) + .transparent; + final address = zcash.deriveNativeTransparentAddressFromViewingKey( + viewingKeyHex: viewing.externalIvk!, + network: zcash.ZcashNetwork.mainnet, + childIndex: 0, + scope: zcash.ZcashTransparentKeyScope.external, + ); + final receiveTxid = '11' * 32; + final spendTxid = '22' * 32; + final authenticated = [ + ZcashAuthenticatedTransparentTransaction( + summary: transparentSummary( + txid: receiveTxid, + outputs: [ + { + 'output_index': 0, + 'address': address, + 'script_hex': '76a914${'33' * 20}88ac', + 'value_zatoshis': 125000, + }, + ], + ), + height: 42, + blockHash: '44' * 32, + blockTime: 1700000000, + ), + ZcashAuthenticatedTransparentTransaction( + summary: transparentSummary( + txid: spendTxid, + inputs: [ + {'prevout_txid': receiveTxid, 'prevout_index': 0}, + ], + ), + height: 42, + blockHash: '44' * 32, + blockTime: 1700000000, + ), + ]; + final client = SyncWalletSessionClient( + chainName: 'main', + tipHeight: 42, + activeTransparentAddresses: {address}, + authenticatedTransparentTransactions: authenticated, + ); + final nodes = MutableZcashNodes( + walletNode(host: 'https://history.example', id: 'history'), + ); + final wallet = await Wallet.create( + walletInfo: WalletInfo( + walletId: 'zcash-fully-spent-history', + name: 'Zcash fully spent history fixture', + mainAddressType: AddressType.zcashUnified, + coinName: 'zcash', + restoreHeight: 43, + ), + mainDB: MainDB.instance, + secureStorageInterface: MemorySecrets(), + nodeService: nodes, + prefs: SessionPrefs(), + mnemonic: mnemonic, + mnemonicPassphrase: '', + ) as ZcashWallet; + wallet.configureAccountSessionFactory( + (network) => + ZcashAccountSession(network: network, clientFactory: (_) => client), + ); + await wallet.init(isRestore: true); + await wallet.recover(isRescan: false); + await wallet.refresh(); + + expect(wallet.info.cachedBalance.total.raw, BigInt.zero); + final history = await MainDB.instance.isar.transactionV2s + .where() + .walletIdEqualTo(wallet.walletId) + .findAll(); + expect(history, hasLength(2)); + expect( + history.map((row) => row.txid), + containsAll([receiveTxid, spendTxid]), + ); + expect( + history + .singleWhere((row) => row.txid == receiveTxid) + .getAmountReceivedInThisWallet(fractionDigits: 8) + .raw, + BigInt.from(125000), + ); + expect( + history + .singleWhere((row) => row.txid == spendTxid) + .getAmountSentFromThisWallet(fractionDigits: 8, subtractFee: false) + .raw, + BigInt.from(125000), + ); + expect(history.map(_pools), everyElement(['transparent'])); + await wallet.exit(); + }, + ); + + test('restore syncs in place and rescan restarts at the birthday', () async { + final node = walletNode(host: 'https://rescan.example', id: 'rescan'); + final client = SyncWalletSessionClient(chainName: 'main', tipHeight: 42); + final wallet = await Wallet.create( + walletInfo: WalletInfo( + walletId: 'zcash-rescan', + name: 'Zcash rescan fixture', + mainAddressType: AddressType.zcashUnified, + coinName: 'zcash', + restoreHeight: 43, + ), + mainDB: MainDB.instance, + secureStorageInterface: MemorySecrets(), + nodeService: MutableZcashNodes(node), + prefs: SessionPrefs(), + mnemonic: + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about', + mnemonicPassphrase: '', + ) as ZcashWallet; + wallet.configureAccountSessionFactory( + (network) => + ZcashAccountSession(network: network, clientFactory: (_) => client), + ); + await wallet.init(isRestore: true); + expect(client.treeStateCalls, 0); + + await wallet.recover(isRescan: false); + await wallet.refresh(); + expect(client.treeStateCalls, 1); + expect(client.transparentRefreshCalls, 1); + expect(wallet.info.cachedChainHeight, 42); + + await MainDB.instance.updateOrPutTransactionV2s([ + TransactionV2( + walletId: wallet.walletId, + blockHash: 'stale-block', + hash: 'stale-hash', + txid: 'stale-txid', + timestamp: 1, + height: 1, + inputs: const [], + outputs: const [], + version: 1, + type: TransactionType.incoming, + subType: TransactionSubType.none, + otherData: null, + ), + ]); + final receiversBefore = await MainDB.instance + .getAddresses(wallet.walletId) + .findAll(); + + await wallet.recover(isRescan: true); + await wallet.refresh(); + + expect(client.treeStateCalls, 2); + expect(client.transparentRefreshCalls, 2); + expect( + await MainDB.instance.isar.transactionV2s + .where() + .walletIdEqualTo(wallet.walletId) + .findAll(), + isEmpty, + ); + final receiversAfter = await MainDB.instance + .getAddresses(wallet.walletId) + .findAll(); + expect( + receiversAfter.map( + (row) => (row.value, row.type, row.subType, row.derivationIndex), + ), + unorderedEquals( + receiversBefore.map( + (row) => (row.value, row.type, row.subType, row.derivationIndex), + ), + ), + ); + expect(wallet.info.cachedChainHeight, 42); + expect(wallet.info.cachedBalance.total.raw, BigInt.zero); + + await MainDB.instance.updateOrPutTransactionV2s([ + TransactionV2( + walletId: wallet.walletId, + blockHash: 'last-known-block', + hash: 'last-known-hash', + txid: 'last-known-txid', + timestamp: 2, + height: 2, + inputs: const [], + outputs: const [], + version: 1, + type: TransactionType.incoming, + subType: TransactionSubType.none, + otherData: null, + ), + ]); + client.failTip = true; + + // The rescan forgets what was scanned and starts over. The scan cannot + // reach the node, so what the wallet shows stays as it was. + await wallet.recover(isRescan: true); + await wallet.refresh(); + + expect( + await MainDB.instance.isar.transactionV2s + .where() + .txidWalletIdEqualTo('last-known-txid', wallet.walletId) + .findFirst(), + isNotNull, + ); + expect(wallet.info.cachedChainHeight, 42); + await wallet.exit(); + }); + + Future syncWallet( + String id, + ZcashLightwalletdClient Function(ZcashEndpoint endpoint) clientFactory, { + int restoreHeight = 43, + MutableZcashNodes? nodes, + }) async { + final wallet = await Wallet.create( + walletInfo: WalletInfo( + walletId: id, + name: 'Zcash $id fixture', + mainAddressType: AddressType.zcashUnified, + coinName: 'zcash', + restoreHeight: restoreHeight, + ), + mainDB: MainDB.instance, + secureStorageInterface: MemorySecrets(), + nodeService: + nodes ?? + MutableZcashNodes(walletNode(host: 'https://$id.example', id: id)), + prefs: SessionPrefs(), + mnemonic: + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about', + mnemonicPassphrase: '', + ) as ZcashWallet; + wallet.configureAccountSessionFactory( + (network) => ZcashAccountSession( + network: network, + clientFactory: clientFactory, + requestTimeout: const Duration(milliseconds: 100), + ), + ); + return wallet; + } + + test('a restore reports a node or a birthday it cannot use, and starts ' + 'no scan', () async { + // The node's tip is below the wallet's birthday. + final behind = SyncWalletSessionClient(chainName: 'main', tipHeight: 40); + final early = await syncWallet( + 'zcash-restore-above-tip', + (_) => behind, + restoreHeight: 43, + ); + await early.init(isRestore: true); + await expectLater( + early.recover(isRescan: false), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('above the validated lightwalletd tip 40'), + ), + ), + ); + expect(behind.treeStateCalls, 0); + await early.exit(); + + // The node is of another network. + final testnet = SyncWalletSessionClient(chainName: 'test', tipHeight: 42); + final wrong = await syncWallet('zcash-restore-wrong-chain', (_) => testnet); + await wrong.init(isRestore: true); + await expectLater(wrong.recover(isRescan: false), throwsA(anything)); + expect(testnet.treeStateCalls, 0); + await wrong.exit(); + }); + + test('a wallet without a birthday opens, and refuses to sync', () async { + final client = SyncWalletSessionClient(chainName: 'main', tipHeight: 42); + final wallet = await syncWallet( + 'zcash-no-birthday', + (_) => client, + restoreHeight: 0, + ); + + // As when the app loads its wallets: neither a restore nor a new wallet. + // Failing here would fail the load of every other wallet with it. + await wallet.init(); + expect(client.infoCalls, 0); + expect(wallet.info.restoreHeight, 0); + + await expectLater( + wallet.updateChainHeight(), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('restore height must be between 1 and'), + ), + ), + ); + expect(await wallet.pingCheck(), isFalse); + expect(client.treeStateCalls, 0); + await wallet.exit(); + }); + + test('a failed node change stops using the old node and recovers', () async { + final nodes = MutableZcashNodes( + walletNode(host: 'https://good.example', id: 'good'), + ); + final opened = []; + final good = []; + final wallet = await syncWallet('zcash-node-change', (endpoint) { + opened.add(endpoint.host); + if (endpoint.host == 'bad.example') { + return WalletSessionClient(chainName: 'test', tipHeight: 42); + } + good.add(SyncWalletSessionClient(chainName: 'main', tipHeight: 42)); + return good.last; + }, nodes: nodes); + await wallet.init(isRestore: true); + await wallet.updateChainHeight(); + expect(opened, ['good.example']); + + nodes.primary = walletNode(host: 'https://bad.example', id: 'bad'); + // Nothing awaits a node change (see node_change_notifier.dart), so it + // reports a node it cannot use through the sync that follows. + await wallet.updateNode(); + // The replaced node is not used again, and the wallet still has the keys + // it needs to connect once the configured node answers. + expect(good.single.closeCalls, 1); + expect(await wallet.pingCheck(), isFalse); + await expectLater( + wallet.updateChainHeight(), + throwsA(isA()), + ); + + nodes.primary = walletNode(host: 'https://good.example', id: 'good'); + await wallet.updateChainHeight(); + expect(wallet.info.cachedChainHeight, 42); + expect(await wallet.pingCheck(), isTrue); + expect(opened.where((host) => host == 'good.example'), hasLength(2)); + await wallet.exit(); + }); + + test('a closed wallet stays closed until it is opened again', () async { + final opened = []; + final wallet = await syncWallet('zcash-closed', (endpoint) { + opened.add(endpoint.host); + return SyncWalletSessionClient(chainName: 'main', tipHeight: 42); + }); + await wallet.init(isRestore: true); + await wallet.updateChainHeight(); + await wallet.exit(); + + // A refresh that was queued behind the one that ran, a ping or a node + // change can still arrive. None of them may open a connection that + // nothing closes, or write state for a wallet that is being deleted. + await expectLater(wallet.updateChainHeight(), throwsStateError); + expect(await wallet.pingCheck(), isFalse); + await wallet.updateNode(); + expect(opened, hasLength(1)); + + // Leaving a wallet's view closes it when it is not kept syncing, and + // opening the view again opens the same wallet object. + await wallet.init(); + await wallet.updateChainHeight(); + expect(opened, hasLength(2)); + expect(await wallet.pingCheck(), isTrue); + await wallet.exit(); + }); + + test('a wallet opened while it is still closing opens after the ' + 'close', () async { + // A connection with a request in flight takes a while to shut down. + final slowClose = Completer(); + final opened = []; + final wallet = await syncWallet('zcash-reopened', (endpoint) { + final client = SyncWalletSessionClient( + chainName: 'main', + tipHeight: 42, + beforeClose: opened.isEmpty ? () => slowClose.future : null, + ); + opened.add(client); + return client; + }); + await wallet.init(isRestore: true); + await wallet.updateChainHeight(); + + // The wallet views start the exit and do not wait for it. + var closed = false; + unawaited(wallet.exit().then((_) => closed = true)); + await wallet.init(); + + // Otherwise the end of the exit would stop the sync of the wallet that + // was just opened. + expect(closed, isTrue); + expect(opened.single.closeCalls, 1); + await wallet.updateChainHeight(); + expect(opened, hasLength(2)); + expect(await wallet.pingCheck(), isTrue); + await wallet.exit(); + expect(opened.last.closeCalls, 1); + }); + + test('a refresh drops stored transactions the history no longer ' + 'has', () async { + final client = SyncWalletSessionClient(chainName: 'main', tipHeight: 42); + final wallet = await syncWallet('zcash-reorged-row', (_) => client); + await wallet.init(isRestore: true); + await MainDB.instance.updateOrPutTransactionV2s([ + TransactionV2( + walletId: wallet.walletId, + blockHash: 'reorged-block', + hash: 'reorged-hash', + txid: 'reorged-txid', + timestamp: 1, + height: 41, + inputs: const [], + outputs: const [], + version: 1, + type: TransactionType.incoming, + subType: TransactionSubType.none, + otherData: null, + ), + TransactionV2( + walletId: 'another-wallet', + blockHash: 'other-block', + hash: 'other-hash', + txid: 'other-txid', + timestamp: 1, + height: 41, + inputs: const [], + outputs: const [], + version: 1, + type: TransactionType.incoming, + subType: TransactionSubType.none, + otherData: null, + ), + ]); + + await wallet.updateTransactions(); + + final remaining = + (await MainDB.instance.isar.transactionV2s.where().findAll()).map( + (row) => row.txid, + ); + expect(remaining, isNot(contains('reorged-txid'))); + expect(remaining, contains('other-txid')); + await wallet.exit(); + }); +} diff --git a/test/wallets/zcash_wallet_state_controller_test.dart b/test/wallets/zcash_wallet_state_controller_test.dart new file mode 100644 index 000000000..a8cc426d8 --- /dev/null +++ b/test/wallets/zcash_wallet_state_controller_test.dart @@ -0,0 +1,1660 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:fixnum/fixnum.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/transaction.dart'; +import 'package:stackwallet/models/isar/models/blockchain_data/v2/transaction_v2.dart'; +import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_account_session.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_wallet_state.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_wallet_state_controller.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_transparent_receiver_discovery.dart'; +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +void main() { + test('transparent history persists incremental frontiers and rewinds ' + 'them after a reorg', () async { + final directory = await Directory.systemTemp.createTemp( + 'zcash_controller_transparent_range_', + ); + addTearDown(() => directory.delete(recursive: true)); + final seed = zcash.nativeMnemonicToSeed( + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about', + ); + final account = zcash.deriveNativeAccountMetadata( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.mainnet, + ); + final viewingKeys = zcash.deriveNativeViewingKeys( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.mainnet, + ); + final discovery = ZcashTransparentReceiverDiscovery( + network: zcash.ZcashNetwork.mainnet, + viewingKeys: viewingKeys, + ); + final defaultAddress = viewingKeys.transparent.defaultExternalAddress; + final ranges = <({int start, int end})>[]; + final store = ZcashEncryptedWalletStateStore( + path: '${directory.path}/wallet.state', + walletId: 'wallet-range', + network: 'main', + accountFingerprint: account.fingerprint, + secureStorage: FakeSecureStorage(), + ); + final sync = _MutableSyncSession(150); + Future + openController() => ZcashWalletStateController.open( + store: store, + accountFingerprint: account.fingerprint, + network: 'main', + birthdayHeight: 100, + loadBirthdayTreeState: (_) async => const zcash.TreeState( + hash: + '0000000000000000000000000000000000000000000000000000000000000000', + height: 99, + time: 1, + ), + scanExecutor: _UnusedScanExecutor(), + openSync: (_, _) => sync, + accountMetadata: account, + viewingKeys: viewingKeys, + additionalTransparentReceivers: discovery.initialReceivers().where( + (receiver) => receiver.address != defaultAddress, + ), + transparentDiscovery: discovery, + transparentActivity: (addresses, start, end) async { + ranges.add((start: start, end: end)); + return ZcashTransparentActivityResult.empty; + }, + refreshTransparent: (state) async => zcash.ZcashTransparentRefresh( + network: state.network, + accountFingerprint: state.accountFingerprint, + queriedAddresses: state.addresses, + chainHeight: sync.chainHeight, + chainTipHash: sync.chainHeight == 150 ? '22' * 32 : '33' * 32, + canonicalBlockHashes: { + 150: '22' * 32, + if (sync.chainHeight != 150) sync.chainHeight: '33' * 32, + }, + unspentOutputs: const [], + observedSpends: const [], + ), + ); + final controller = await openController(); + + await controller.refresh(); + await controller.refresh(); + sync.chainHeight = 152; + await controller.refresh(); + final reopened = await openController(); + await reopened.refresh(); + + sync.triggerReorg( + const zcash.ZcashSyncReorged( + recovery: zcash.ZcashReorgRecovery( + forkHeight: 150, + forkBlockHash: + '22222222222222222222222222222222' + '22222222222222222222222222222222', + resumeHeight: 151, + depth: 2, + ), + detection: zcash.ZcashChainReorgException( + message: 'test reorg', + height: 151, + expectedPrevHash: + '22222222222222222222222222222222' + '22222222222222222222222222222222', + servedPrevHash: + '44444444444444444444444444444444' + '44444444444444444444444444444444', + ), + ), + ); + await reopened.refresh(); + expect(sync.resumeCalls, 1); + + expect(ranges, [ + (start: 100, end: 150), + (start: 151, end: 152), + (start: 151, end: 152), + ]); + }); + + test('newly discovered receivers backfill from the birthday while known ' + 'receivers stay incremental', () async { + final directory = await Directory.systemTemp.createTemp( + 'zcash_controller_new_receiver_frontier_', + ); + addTearDown(() => directory.delete(recursive: true)); + final seed = zcash.nativeMnemonicToSeed( + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about', + ); + final account = zcash.deriveNativeAccountMetadata( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.mainnet, + ); + final viewingKeys = zcash.deriveNativeViewingKeys( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.mainnet, + ); + final discovery = ZcashTransparentReceiverDiscovery( + network: zcash.ZcashNetwork.mainnet, + viewingKeys: viewingKeys, + gapLimit: 2, + hardChildLimit: 6, + ); + final defaultAddress = viewingKeys.transparent.defaultExternalAddress; + final initial = discovery.initialReceivers(); + final newlyActive = initial.singleWhere( + (receiver) => + receiver.scope == zcash.ZcashTransparentReceiverScope.external && + receiver.childIndex == 1, + ); + final sync = _MutableSyncSession(150); + final requests = <({List addresses, int start, int end})>[]; + final controller = await ZcashWalletStateController.open( + store: ZcashEncryptedWalletStateStore( + path: '${directory.path}/wallet.state', + walletId: 'wallet-new-receiver', + network: 'main', + accountFingerprint: account.fingerprint, + secureStorage: FakeSecureStorage(), + ), + accountFingerprint: account.fingerprint, + network: 'main', + birthdayHeight: 100, + loadBirthdayTreeState: (_) async => const zcash.TreeState( + hash: + '0000000000000000000000000000000000000000000000000000000000000000', + height: 99, + time: 1, + ), + scanExecutor: _UnusedScanExecutor(), + openSync: (_, _) => sync, + accountMetadata: account, + viewingKeys: viewingKeys, + additionalTransparentReceivers: initial.where( + (receiver) => receiver.address != defaultAddress, + ), + transparentDiscovery: discovery, + transparentActivity: (addresses, start, end) async { + requests.add((addresses: addresses, start: start, end: end)); + return ZcashTransparentActivityResult( + activeAddresses: end == 151 && start == 151 + ? {newlyActive.address} + : const {}, + ); + }, + refreshTransparent: (state) async => zcash.ZcashTransparentRefresh( + network: state.network, + accountFingerprint: state.accountFingerprint, + queriedAddresses: state.addresses, + chainHeight: sync.chainHeight, + chainTipHash: sync.chainHeight == 150 ? '22' * 32 : '33' * 32, + canonicalBlockHashes: { + 150: '22' * 32, + if (sync.chainHeight != 150) sync.chainHeight: '33' * 32, + }, + unspentOutputs: const [], + observedSpends: const [], + ), + ); + + await controller.refresh(); + sync.chainHeight = 151; + await controller.refresh(); + + expect(requests.map((request) => (request.start, request.end)), [ + (100, 150), + (151, 151), + (100, 151), + ]); + expect(requests.last.addresses, hasLength(2)); + expect(requests.last.addresses, isNot(contains(newlyActive.address))); + }); + + test('reorg recovery rolls every pool back before resuming from the ' + 'authenticated fork tree', () async { + final directory = await Directory.systemTemp.createTemp( + 'zcash_controller_reorg_recovery_', + ); + addTearDown(() => directory.delete(recursive: true)); + final seed = zcash.nativeMnemonicToSeed( + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about', + ); + final account = zcash.deriveNativeAccountMetadata( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.mainnet, + ); + final viewingKeys = zcash.deriveNativeViewingKeys( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.mainnet, + ); + final discovery = ZcashTransparentReceiverDiscovery( + network: zcash.ZcashNetwork.mainnet, + viewingKeys: viewingKeys, + gapLimit: 1, + hardChildLimit: 2, + ); + final defaultAddress = viewingKeys.transparent.defaultExternalAddress; + final receivers = discovery.initialReceivers(); + final transparent = + zcash.ZcashTransparentState.fromAccount( + account: account, + viewingKeys: viewingKeys, + additionalReceivers: receivers.where( + (receiver) => receiver.address != defaultAddress, + ), + )..applyRefresh( + zcash.ZcashTransparentRefresh( + network: zcash.ZcashAddressNetwork.mainnet, + accountFingerprint: account.fingerprint, + queriedAddresses: receivers + .map((receiver) => receiver.address) + .toList(), + chainHeight: 152, + chainTipHash: '99' * 32, + canonicalBlockHashes: {150: '22' * 32, 152: '99' * 32}, + unspentOutputs: const [], + observedSpends: const [], + ), + ); + final coverage = _coverage(100, 152); + final state = zcash.ZcashWalletSyncState( + cursor: zcash.ZcashLightwalletdSyncCursor( + nextHeight: 153, + priorBlockHash: '99' * 32, + trail: zcash.ZcashChainTrail( + checkpoints: [ + zcash.ZcashChainCheckpoint(height: 150, blockHash: '22' * 32), + zcash.ZcashChainCheckpoint(height: 151, blockHash: '77' * 32), + zcash.ZcashChainCheckpoint(height: 152, blockHash: '99' * 32), + ], + ), + ), + network: zcash.ZcashAddressNetwork.mainnet, + accountFingerprint: account.fingerprint, + sapling: zcash.SaplingNoteStore() + ..apply(coverage, accountFingerprint: account.fingerprint), + orchard: zcash.OrchardNoteStore() + ..apply(coverage, accountFingerprint: account.fingerprint), + ironwood: zcash.IronwoodNoteStore() + ..apply(coverage, accountFingerprint: account.fingerprint), + transparent: transparent, + ); + final store = ZcashEncryptedWalletStateStore( + path: '${directory.path}/wallet.state', + walletId: 'wallet-reorg-recovery', + network: 'main', + accountFingerprint: account.fingerprint, + secureStorage: FakeSecureStorage(), + ); + await store.save( + ZcashPersistedWalletState( + syncState: state, + observedChainHeight: 152, + transparentHistoryFrontiers: { + for (final receiver in receivers) receiver.address: 152, + }, + ), + ); + late _BackedRecoverySyncSession sync; + final ranges = <({int start, int end})>[]; + final controller = await ZcashWalletStateController.open( + store: store, + accountFingerprint: account.fingerprint, + network: 'main', + birthdayHeight: 100, + loadBirthdayTreeState: (height) async => _replacementTreeState(height), + scanExecutor: _UnusedScanExecutor(), + openSync: (opened, _) => sync = _BackedRecoverySyncSession(opened), + accountMetadata: account, + viewingKeys: viewingKeys, + additionalTransparentReceivers: receivers.where( + (receiver) => receiver.address != defaultAddress, + ), + transparentDiscovery: discovery, + transparentActivity: (addresses, start, end) async { + ranges.add((start: start, end: end)); + return ZcashTransparentActivityResult.empty; + }, + refreshTransparent: (transparent) async => zcash.ZcashTransparentRefresh( + network: transparent.network, + accountFingerprint: transparent.accountFingerprint, + queriedAddresses: transparent.addresses, + chainHeight: 152, + chainTipHash: '44' * 32, + canonicalBlockHashes: {150: '22' * 32, 152: '44' * 32}, + unspentOutputs: const [], + observedSpends: const [], + ), + ); + + await controller.refresh(); + + final persisted = (await store.load())!; + expect(sync.resumeCalls, 1); + expect(sync.sawRolledBackStores, isTrue); + expect(persisted.syncState.sapling.coveredThrough, 152); + expect(persisted.syncState.orchard.coveredThrough, 152); + expect(persisted.syncState.ironwood.coveredThrough, 152); + expect( + persisted.syncState.transparent.refreshedThroughBlockHash, + '44' * 32, + ); + expect(persisted.observedChainHeight, 152); + expect(persisted.transparentHistoryFrontiers.values, everyElement(152)); + expect(ranges, [(start: 151, end: 152)]); + }); + + test('registers the UA transparent child at its exact ' + 'regtest index', () async { + final directory = await Directory.systemTemp.createTemp( + 'zcash_controller_transparent_receiver_', + ); + addTearDown(() => directory.delete(recursive: true)); + final seed = zcash.nativeMnemonicToSeed( + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about', + ); + final account = zcash.deriveNativeAccountMetadata( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.regtest, + ); + final viewingKeys = zcash.deriveNativeViewingKeys( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.regtest, + ); + final address = await zcash.deriveAddress( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.regtest, + ); + final store = ZcashEncryptedWalletStateStore( + path: '${directory.path}/wallet.state', + walletId: 'wallet-1', + network: 'regtest', + accountFingerprint: account.fingerprint, + secureStorage: FakeSecureStorage(), + ); + + final controller = await ZcashWalletStateController.open( + store: store, + accountFingerprint: account.fingerprint, + network: 'regtest', + birthdayHeight: 100, + loadBirthdayTreeState: (_) async => const zcash.TreeState( + hash: + '0000000000000000000000000000000000000000000000000000000000000000', + height: 99, + time: 1, + ), + scanExecutor: _UnusedScanExecutor(), + openSync: (_, _) => + const _ImmediateSyncSession(zcash.ZcashSyncCaughtUp(chainHeight: 99)), + accountMetadata: account, + viewingKeys: viewingKeys, + additionalTransparentReceivers: [ + zcash.ZcashTransparentReceiver( + address: address.transparentAddress!, + scope: zcash.ZcashTransparentReceiverScope.external, + childIndex: address.nextValidIndex, + ), + ], + refreshTransparent: (state) async { + expect(state.addresses, contains(address.transparentAddress)); + return zcash.ZcashTransparentRefresh( + network: state.network, + accountFingerprint: state.accountFingerprint, + queriedAddresses: state.addresses, + chainHeight: 99, + chainTipHash: '22' * 32, + canonicalBlockHashes: {99: '22' * 32}, + unspentOutputs: [ + zcash.ZcashTransparentOutputObservation( + address: address.transparentAddress!, + protocolTxid: '11' * 32, + outputIndex: 0, + scriptHex: '51', + valueZatoshis: 100000, + minedHeight: 99, + blockHash: '22' * 32, + blockTime: 1700000000, + isCoinbase: false, + ), + ], + observedSpends: const [], + ); + }, + ); + await controller.refresh(); + + final transparent = (await store.load())!.syncState.transparent; + expect( + address.nextValidIndex, + isNot(viewingKeys.transparent.defaultExternalIndex), + ); + expect( + transparent.receivers, + contains( + isA() + .having( + (receiver) => receiver.address, + 'address', + address.transparentAddress, + ) + .having( + (receiver) => receiver.childIndex, + 'child', + address.nextValidIndex, + ), + ), + ); + expect( + transparent.unspentOutputs.single.address, + address.transparentAddress, + ); + expect(controller.snapshot.balance.byPool['transparent'], 100000); + final key = zcash.deriveNativeTransparentSpendingKey( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.regtest, + childIndex: address.nextValidIndex, + ); + try { + expect(key.address, address.transparentAddress); + expect( + key.address, + transparent.coinSet.tracked.single.utxo.address, + reason: + 'the synced UA receiver must have the exact spendable child key', + ); + } finally { + key.destroy(); + } + }); + + test('concurrent refresh callers share one serialized sync', () async { + final directory = await Directory.systemTemp.createTemp( + 'zcash_controller_test_', + ); + addTearDown(() => directory.delete(recursive: true)); + final executor = _UnusedScanExecutor(); + final sync = _GatedSyncSession(); + final controller = await ZcashWalletStateController.open( + store: ZcashEncryptedWalletStateStore( + path: '${directory.path}/wallet.state', + walletId: 'wallet-1', + network: 'main', + accountFingerprint: 'account-a', + secureStorage: FakeSecureStorage(), + ), + accountFingerprint: 'account-a', + network: 'main', + birthdayHeight: 100, + loadBirthdayTreeState: (_) async => const zcash.TreeState( + hash: + '0000000000000000000000000000000000000000000000000000000000000000', + height: 99, + time: 1, + ), + scanExecutor: executor, + openSync: (state, receivedExecutor) { + expect(receivedExecutor, same(executor)); + return sync; + }, + ); + + final first = controller.refresh(); + final second = controller.refresh(); + final third = controller.refresh(); + await Future.delayed(Duration.zero); + expect(sync.calls, 1); + sync.complete(const zcash.ZcashSyncCaughtUp(chainHeight: 125)); + + final snapshots = await Future.wait([first, second, third]); + expect(snapshots.map((e) => e.chainHeight), everyElement(125)); + expect(sync.calls, 1); + }); + + const cancelledRefreshTestName = + 'cancelled refresh never persists or exposes the late sync result'; + test(cancelledRefreshTestName, () async { + final directory = await Directory.systemTemp.createTemp( + 'zcash_controller_cancelled_refresh_', + ); + addTearDown(() => directory.delete(recursive: true)); + final store = ZcashEncryptedWalletStateStore( + path: '${directory.path}/wallet.state', + walletId: 'wallet-cancelled-refresh', + network: 'main', + accountFingerprint: 'account-a', + secureStorage: FakeSecureStorage(), + ); + final sync = _GatedSyncSession(); + final controller = await ZcashWalletStateController.open( + store: store, + accountFingerprint: 'account-a', + network: 'main', + birthdayHeight: 100, + loadBirthdayTreeState: (_) async => const zcash.TreeState( + hash: + '0000000000000000000000000000000000000000000000000000000000000000', + height: 99, + time: 1, + ), + scanExecutor: _UnusedScanExecutor(), + openSync: (_, _) => sync, + ); + final cancellation = ZcashRecoveryCancellationToken(); + + final refreshing = controller.refresh(cancellation: cancellation); + await Future.delayed(Duration.zero); + cancellation.cancel(); + sync.complete(const zcash.ZcashSyncCaughtUp(chainHeight: 125)); + + await expectLater( + refreshing, + throwsA(isA()), + ); + expect(controller.snapshot.chainHeight, 99); + expect((await store.load())?.observedChainHeight, 99); + }); + + test( + 'cancelled native scan result is rejected before store application', + () async { + const fingerprint = 'cancelled-native-scan'; + final state = zcash.ZcashWalletSyncState.atBirthday( + cursor: zcash.ZcashLightwalletdSyncCursor.origin(height: 11), + network: zcash.ZcashAddressNetwork.regtest, + accountFingerprint: fingerprint, + ); + final scanStarted = Completer(); + final releaseScan = Completer(); + final executor = _GatedScanExecutor(scanStarted, releaseScan); + var cancelled = false; + final session = openZcashSyncSession( + state: state, + source: const _SingleBlockSyncSource(), + scanExecutor: executor, + network: 'regtest', + checkCancellation: () { + if (cancelled) throw const ZcashRecoveryCancelledException(); + }, + ); + + final syncing = session.syncToTip(); + await scanStarted.future; + cancelled = true; + releaseScan.complete(); + + await expectLater( + syncing, + throwsA(isA()), + ); + expect(state.cursor.nextHeight, 11); + expect(state.sapling.notes, isEmpty); + expect(state.orchard.notes, isEmpty); + expect(state.ironwood.notes, isEmpty); + }, + ); + + test('a sync saves its progress as it goes and keeps the times of the ' + 'wallet\'s blocks', () async { + final directory = await Directory.systemTemp.createTemp( + 'zcash_controller_checkpoint_test_', + ); + addTearDown(() => directory.delete(recursive: true)); + final secrets = FakeSecureStorage(); + ZcashEncryptedWalletStateStore store() => ZcashEncryptedWalletStateStore( + path: '${directory.path}/wallet.state', + walletId: 'wallet-1', + network: 'regtest', + accountFingerprint: 'account-a', + secureStorage: secrets, + ); + const source = _ChainSource(tip: 35); + final reached30 = Completer(); + final release = Completer(); + final executor = _NoteAtHeightScanExecutor( + noteHeight: 15, + pauseAt: 30, + paused: reached30, + release: release, + ); + Future open() { + final blockTimes = ZcashBlockTimes(); + return ZcashWalletStateController.open( + store: store(), + accountFingerprint: 'account-a', + network: 'regtest', + birthdayHeight: 11, + loadBirthdayTreeState: source.getTreeState, + scanExecutor: executor, + openSync: (state, executor) => openZcashSyncSession( + state: state, + source: source, + scanExecutor: executor, + network: 'regtest', + blockTimes: blockTimes, + rangeSize: 1, + ), + blockTimes: blockTimes, + ); + } + + final controller = await open(); + final refreshing = controller.refresh(); + await reached30.future; + + // Heights 11 to 29 are scanned: the save after every tenth range has + // happened once, and an interrupted sync resumes from it. + final checkpoint = (await store().load())!; + expect(checkpoint.syncState.cursor.nextHeight, 21); + expect(checkpoint.syncState.ironwood.notes.single.height, 15); + expect(checkpoint.blockTimes, {15: 1700000015}); + + release.complete(); + final snapshot = await refreshing; + expect(snapshot.chainHeight, 35); + expect(snapshot.blockTimes, {15: 1700000015}); + + // The sync stores the note without its witness, which a send fetches, + // so the backend's own count does not hold it. + expect(snapshot.balance.spendableZatoshis, 0); + expect(snapshot.spendableNotes, {'11' * 32: 1000}); + expect( + const ZcashStackStateMapper(walletId: 'wallet-1') + .balance(snapshot) + .spendable + .raw, + BigInt.from(1000), + ); + + final reopened = await open(); + expect(reopened.snapshot.blockTimes, {15: 1700000015}); + expect(reopened.snapshot.history.entries.single.height, 15); + expect(reopened.snapshot.spendableNotes, {'11' * 32: 1000}); + }); + + test('a sync that is still running when its wallet closes saves nothing ' + 'more', () async { + final directory = await Directory.systemTemp.createTemp( + 'zcash_controller_closed_test_', + ); + addTearDown(() => directory.delete(recursive: true)); + final secrets = FakeSecureStorage(); + ZcashEncryptedWalletStateStore store() => ZcashEncryptedWalletStateStore( + path: '${directory.path}/wallet.state', + walletId: 'wallet-1', + network: 'regtest', + accountFingerprint: 'account-a', + secureStorage: secrets, + ); + const source = _ChainSource(tip: 35); + final reached30 = Completer(); + final release = Completer(); + final blockTimes = ZcashBlockTimes(); + final controller = await ZcashWalletStateController.open( + store: store(), + accountFingerprint: 'account-a', + network: 'regtest', + birthdayHeight: 11, + loadBirthdayTreeState: source.getTreeState, + scanExecutor: _NoteAtHeightScanExecutor( + noteHeight: 15, + pauseAt: 30, + paused: reached30, + release: release, + ), + openSync: (state, executor) => openZcashSyncSession( + state: state, + source: source, + scanExecutor: executor, + network: 'regtest', + blockTimes: blockTimes, + rangeSize: 1, + ), + blockTimes: blockTimes, + ); + final refreshing = controller.refresh(); + await reached30.future; + + // The wallet is deleted, or its node replaced, during the scan of + // height 30. The save that would follow it does not happen. + controller.close(); + release.complete(); + await expectLater( + refreshing, + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('closed'), + ), + ), + ); + expect((await store().load())!.syncState.cursor.nextHeight, 21); + await expectLater(controller.refresh(), throwsStateError); + }); + + group('a block that arrives between the shielded and the transparent ' + 'pass', () { + Future open( + _MutableSyncSession sync, { + required int Function() transparentTip, + }) async { + final directory = await Directory.systemTemp.createTemp( + 'zcash_controller_tip_round_', + ); + addTearDown(() => directory.delete(recursive: true)); + final seed = zcash.nativeMnemonicToSeed( + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about', + ); + final account = zcash.deriveNativeAccountMetadata( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.mainnet, + ); + final viewingKeys = zcash.deriveNativeViewingKeys( + seedHex: seed.seedHex, + network: zcash.ZcashNetwork.mainnet, + ); + return ZcashWalletStateController.open( + store: ZcashEncryptedWalletStateStore( + path: '${directory.path}/wallet.state', + walletId: 'wallet-tip', + network: 'main', + accountFingerprint: account.fingerprint, + secureStorage: FakeSecureStorage(), + ), + accountFingerprint: account.fingerprint, + network: 'main', + birthdayHeight: 100, + loadBirthdayTreeState: (_) async => + zcash.TreeState(hash: '00' * 32, height: 99, time: 1), + scanExecutor: _UnusedScanExecutor(), + openSync: (_, _) => sync, + accountMetadata: account, + viewingKeys: viewingKeys, + refreshTransparent: (state) async { + final tip = transparentTip(); + return zcash.ZcashTransparentRefresh( + network: state.network, + accountFingerprint: state.accountFingerprint, + queriedAddresses: state.addresses, + chainHeight: tip, + chainTipHash: '22' * 32, + canonicalBlockHashes: {tip: '22' * 32}, + unspentOutputs: const [], + observedSpends: const [], + ); + }, + ); + } + + test('is synced in the same refresh', () async { + final sync = _MutableSyncSession(150); + var transparentPasses = 0; + final controller = await open( + sync, + transparentTip: () { + transparentPasses++; + // The block arrives after the first shielded pass. + return sync.chainHeight = 151; + }, + ); + + final snapshot = await controller.refresh(); + + expect(snapshot.chainHeight, 151); + expect(transparentPasses, 2); + }); + + test('fails the refresh when the passes never agree', () async { + final sync = _MutableSyncSession(150); + var transparentPasses = 0; + final controller = await open( + sync, + transparentTip: () { + transparentPasses++; + return ++sync.chainHeight; + }, + ); + + await expectLater(controller.refresh(), throwsStateError); + expect(transparentPasses, ZcashWalletStateController.maximumTipRounds); + }); + }); + + test( + 'failed pre-birthday reorg rescan preserves the durable checkpoint', + () async { + final directory = await Directory.systemTemp.createTemp( + 'zcash_controller_reorg_test_', + ); + addTearDown(() => directory.delete(recursive: true)); + final store = ZcashEncryptedWalletStateStore( + path: '${directory.path}/wallet.state', + walletId: 'wallet-1', + network: 'main', + accountFingerprint: 'account-a', + secureStorage: FakeSecureStorage(), + ); + var treeStateLoads = 0; + final controller = await ZcashWalletStateController.open( + store: store, + accountFingerprint: 'account-a', + network: 'main', + birthdayHeight: 100, + loadBirthdayTreeState: (_) async { + treeStateLoads++; + if (treeStateLoads > 1) { + throw StateError('birthday tree unavailable'); + } + return const zcash.TreeState( + hash: + '00000000000000000000000000000000' + '00000000000000000000000000000000', + height: 99, + time: 1, + ); + }, + scanExecutor: _UnusedScanExecutor(), + openSync: (_, _) => const _ThrowingSyncSession( + zcash.ZcashReorgTooDeepException( + message: 'fork predates retained trail', + lowestHeightSearched: 100, + ), + ), + ); + + await expectLater( + controller.refresh(), + throwsA( + isA().having( + (error) => error.message, + 'message', + 'birthday tree unavailable', + ), + ), + ); + + expect(controller.snapshot.chainHeight, 99); + expect((await store.load())?.observedChainHeight, 99); + }, + ); + + test( + 'pre-birthday reorg reopens a fresh birthday sync and rescans', + () async { + final directory = await Directory.systemTemp.createTemp( + 'zcash_controller_deep_reorg_rescan_', + ); + addTearDown(() => directory.delete(recursive: true)); + final store = ZcashEncryptedWalletStateStore( + path: '${directory.path}/wallet.state', + walletId: 'wallet-deep-reorg', + network: 'main', + accountFingerprint: 'account-a', + secureStorage: FakeSecureStorage(), + ); + var treeStateLoads = 0; + var syncOpens = 0; + final controller = await ZcashWalletStateController.open( + store: store, + accountFingerprint: 'account-a', + network: 'main', + birthdayHeight: 100, + loadBirthdayTreeState: (_) async { + treeStateLoads++; + return const zcash.TreeState( + hash: + '00000000000000000000000000000000' + '00000000000000000000000000000000', + height: 99, + time: 1, + ); + }, + scanExecutor: _UnusedScanExecutor(), + openSync: (_, _) { + syncOpens++; + return syncOpens == 1 + ? const _ThrowingSyncSession( + zcash.ZcashReorgTooDeepException( + message: 'fork predates retained trail', + lowestHeightSearched: 100, + ), + ) + : const _ImmediateSyncSession( + zcash.ZcashSyncCaughtUp(chainHeight: 125), + ); + }, + ); + + final snapshot = await controller.refresh(); + + expect(snapshot.chainHeight, 125); + expect(treeStateLoads, 2); + expect(syncOpens, 2); + expect((await store.load())?.observedChainHeight, 125); + }, + ); + + test('repeated too-deep reorgs perform only one birthday restart', () async { + final directory = await Directory.systemTemp.createTemp( + 'zcash_controller_repeated_deep_reorg_', + ); + addTearDown(() => directory.delete(recursive: true)); + final store = ZcashEncryptedWalletStateStore( + path: '${directory.path}/wallet.state', + walletId: 'wallet-repeated-deep-reorg', + network: 'main', + accountFingerprint: 'account-a', + secureStorage: FakeSecureStorage(), + ); + var treeStateLoads = 0; + var syncOpens = 0; + final controller = await ZcashWalletStateController.open( + store: store, + accountFingerprint: 'account-a', + network: 'main', + birthdayHeight: 100, + loadBirthdayTreeState: (_) async { + treeStateLoads++; + return const zcash.TreeState( + hash: + '00000000000000000000000000000000' + '00000000000000000000000000000000', + height: 99, + time: 1, + ); + }, + scanExecutor: _UnusedScanExecutor(), + openSync: (_, _) { + syncOpens++; + return const _ThrowingSyncSession( + zcash.ZcashReorgTooDeepException( + message: 'server remains below the retained trail', + lowestHeightSearched: 100, + ), + ); + }, + ); + + await expectLater( + controller.refresh(), + throwsA( + isA().having( + (error) => error.attempts, + 'attempts', + 1, + ), + ), + ); + + expect(treeStateLoads, 2); + expect(syncOpens, 2); + expect(controller.snapshot.chainHeight, 99); + expect((await store.load())?.observedChainHeight, 99); + }); + + test( + 'repeated shallow reorgs stop at the per-refresh recovery limit', + () async { + final directory = await Directory.systemTemp.createTemp( + 'zcash_controller_repeated_shallow_reorg_', + ); + addTearDown(() => directory.delete(recursive: true)); + final store = ZcashEncryptedWalletStateStore( + path: '${directory.path}/wallet.state', + walletId: 'wallet-repeated-shallow-reorg', + network: 'main', + accountFingerprint: 'account-a', + secureStorage: FakeSecureStorage(), + ); + var treeStateLoads = 0; + var syncOpens = 0; + late _RepeatingShallowSyncSession sync; + final controller = await ZcashWalletStateController.open( + store: store, + accountFingerprint: 'account-a', + network: 'main', + birthdayHeight: 100, + loadBirthdayTreeState: (_) async { + treeStateLoads++; + return const zcash.TreeState( + hash: + '00000000000000000000000000000000' + '00000000000000000000000000000000', + height: 99, + time: 1, + ); + }, + scanExecutor: _UnusedScanExecutor(), + openSync: (_, _) { + syncOpens++; + return sync = _RepeatingShallowSyncSession(); + }, + ); + + await expectLater( + controller.refresh(), + throwsA( + isA().having( + (error) => error.attempts, + 'attempts', + ZcashWalletStateController.maximumRecoveryCyclesPerRefresh, + ), + ), + ); + + expect(sync.syncCalls, 3); + expect(sync.resumeCalls, 2); + expect(sync.forkTreeLoads, 2); + expect(treeStateLoads, 1); + expect(syncOpens, 1); + expect((await store.load())?.observedChainHeight, 99); + }, + ); + + test('maps pool balance and only known shielded history fields', () { + const transaction = + '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const scan = zcash.ZcashScanResult( + scannedBlocks: 1, + discoveredNotes: 2, + totalValue: 12, + scannedHeightRange: zcash.CompactBlockScanRange(start: 100, end: 100), + notes: [ + zcash.ZcashScannedNote( + height: 100, + tx: transaction, + output: 0, + value: 5, + pool: 'sapling', + nullifier: + '11111111111111111111111111111111' + '11111111111111111111111111111111', + recipient: 'zs-test', + rseed: '00', + witness: '00', + commitmentPosition: 0, + blockHash: + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + ), + zcash.ZcashScannedNote( + height: 100, + tx: transaction, + output: 1, + value: 7, + pool: 'orchard', + nullifier: + '22222222222222222222222222222222' + '22222222222222222222222222222222', + recipient: 'u-test', + rho: '00', + rseed: '00', + witness: '00', + noteVersion: 'v2', + commitmentPosition: 1, + blockHash: + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + ), + ], + ); + final state = zcash.ZcashWalletSyncState.atBirthday( + cursor: zcash.ZcashLightwalletdSyncCursor.fromTreeState( + const zcash.TreeState( + hash: + '00000000000000000000000000000000' + '00000000000000000000000000000000', + height: 99, + time: 1, + ), + ), + network: zcash.ZcashAddressNetwork.mainnet, + accountFingerprint: 'account-a', + ); + state.sapling.apply(scan, accountFingerprint: 'account-a'); + state.orchard.apply(scan, accountFingerprint: 'account-a'); + state.ironwood.apply(scan, accountFingerprint: 'account-a'); + final nativeBalance = zcash.ZcashAccountBalance.fromScan(scan: scan); + const mapper = ZcashStackStateMapper(walletId: 'wallet-1'); + + final balance = mapper.balance( + ZcashWalletSnapshot( + chainHeight: 131, + balance: nativeBalance, + history: state.history(), + spendableNotes: ZcashWalletSnapshot.spendableNotesOf(state), + ), + ); + final transactions = mapper.transactions(state.history()); + + expect(nativeBalance.byPool, { + 'sapling': 5, + 'orchard': 7, + 'ironwood': 0, + 'transparent': 0, + }); + // Sapling and Orchard funds are the wallet's, but a send spends + // Ironwood notes only. + expect(balance.total.raw, BigInt.from(12)); + expect(balance.spendable.raw, BigInt.zero); + expect(balance.blockedTotal.raw, BigInt.from(12)); + expect(transactions, hasLength(1)); + expect(transactions.single.height, 100); + expect(transactions.single.timestamp, 0); + expect( + transactions.single.blockHash, + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', + ); + final metadata = + jsonDecode(transactions.single.otherData!) as Map; + expect(metadata.keys, { + TxV2OdKeys.overrideFee, + ZcashStackStateMapper.poolsKey, + }); + expect(metadata[ZcashStackStateMapper.poolsKey], ['orchard', 'sapling']); + expect( + transactions.single.getAmountReceivedInThisWallet(fractionDigits: 8).raw, + BigInt.from(12), + ); + // No fee is known for a received shielded transaction, and without an + // input to derive one from, reading it must still not throw. + expect(transactions.single.getFee(fractionDigits: 8).raw, BigInt.zero); + }); + + test( + 'native scan executor delegates raw FFI work across its boundary', + () async { + (String ufvk, String network, String envelope)? received; + final executor = ZcashNativeIsolateScanExecutor( + ufvk: 'secret-ufvk', + network: 'main', + worker: (request) async { + received = request; + return jsonEncode({ + 'scanned_blocks': 0, + 'discovered_notes': 0, + 'total_value': 0, + 'notes': [], + 'spends': [], + }); + }, + ); + final envelope = zcash.ScanInputEnvelope(blocks: const []); + + final result = await executor.scan(envelope); + + expect(received?.$1, 'secret-ufvk'); + expect(received?.$2, 'main'); + expect(received?.$3, envelope.encode()); + expect(result.scannedBlocks, 0); + }, + ); + + test('a scan that finds an Orchard note does not fail', () async { + final raw = jsonEncode({ + 'scanned_blocks': 1, + 'discovered_notes': 1, + 'total_value': 54321, + 'notes': [ + { + 'height': 1, + 'tx': 'ef' * 32, + 'output': 1, + 'value': 54321, + 'pool': 'orchard', + 'nullifier': '12' * 32, + 'commitment_position': 9, + 'is_change': false, + }, + ], + 'spends': [], + }); + // The scanner reports the account's Orchard notes on mainnet too. A + // scan that refused one would stop the wallet at that block for good. + final executor = ZcashNativeIsolateScanExecutor( + ufvk: 'secret-ufvk', + network: 'main', + worker: (_) async => raw, + ); + + final result = await executor.scan( + zcash.ScanInputEnvelope(blocks: const []), + ); + expect(result.notes.single.pool, 'orchard'); + }); + + test('unvalued spend is a send of unknown amount', () { + const transaction = + '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'; + const scan = zcash.ZcashScanResult( + scannedBlocks: 1, + discoveredNotes: 0, + totalValue: 0, + scannedHeightRange: zcash.CompactBlockScanRange(start: 100, end: 100), + notes: [], + spends: [ + zcash.ZcashObservedSpend( + height: 100, + tx: transaction, + pool: 'sapling', + nullifier: + '11111111111111111111111111111111' + '11111111111111111111111111111111', + index: 0, + ), + ], + ); + final state = zcash.ZcashWalletSyncState.atBirthday( + cursor: zcash.ZcashLightwalletdSyncCursor.fromTreeState( + const zcash.TreeState( + hash: + '00000000000000000000000000000000' + '00000000000000000000000000000000', + height: 99, + time: 1, + ), + ), + network: zcash.ZcashAddressNetwork.mainnet, + accountFingerprint: 'account-a', + ); + state.sapling.apply(scan, accountFingerprint: 'account-a'); + state.orchard.apply(scan, accountFingerprint: 'account-a'); + state.ironwood.apply(scan, accountFingerprint: 'account-a'); + + final mapped = const ZcashStackStateMapper(walletId: 'wallet-1') + .transactions(state.history()) + .single; + + expect(mapped.type, TransactionType.outgoing); + expect(mapped.inputs, isEmpty); + expect( + mapped + .getAmountSentFromThisWallet(fractionDigits: 8, subtractFee: true) + .raw, + BigInt.zero, + ); + }); +} + +class _GatedSyncSession implements ZcashSyncSession { + final _completer = Completer(); + var calls = 0; + + @override + Future syncToTip({ + Future Function()? onAdvanced, + }) { + calls += 1; + return _completer.future; + } + + void complete(zcash.ZcashSyncOutcome outcome) => _completer.complete(outcome); +} + +class _UnusedScanExecutor implements ZcashScanExecutor { + @override + Future scan(zcash.ScanInputEnvelope envelope) => + throw StateError('scan should not be reached by this fake sync'); +} + +class _GatedScanExecutor implements ZcashScanExecutor { + _GatedScanExecutor(this.started, this.release); + + final Completer started; + final Completer release; + + @override + Future scan(zcash.ScanInputEnvelope envelope) async { + started.complete(); + await release.future; + final range = envelope.range!; + return zcash.ZcashScanResult( + scannedBlocks: 1, + discoveredNotes: 1, + totalValue: 1000, + scannedHeightRange: range, + notes: [ + zcash.ZcashScannedNote( + height: range.start, + tx: _cancelHashHex(range.start), + output: 0, + value: 1000, + pool: 'ironwood', + nullifier: '11' * 32, + ), + ], + ); + } +} + +/// A chain of empty blocks up to [tip], each with the time 1700000000 plus +/// its height. +class _ChainSource implements ZcashSyncDataSource { + const _ChainSource({required this.tip}); + + final int tip; + + @override + Future getBlockHash(int height) async => + height <= tip ? _cancelHashHex(height) : null; + + @override + Future getBlockRange( + int start, + int end, + ) async => zcash.ZcashLightwalletdScanSource([ + for (var height = start; height <= end; height++) + zcash.CompactBlock() + ..height = Int64(height) + ..time = 1700000000 + height + ..hash = _cancelHashBytes(height) + ..prevHash = _cancelHashBytes(height - 1), + ]); + + @override + Future getTreeState(int height) async => zcash.TreeState( + hash: zcash.reverseTxidByteOrder(_cancelHashHex(height)), + height: height, + time: 1, + ironwood: zcash.ShieldedTree(finalState: 'tree-$height'), + ); + + @override + Future getTipHeight() async => tip; +} + +/// Finds one note, in the block at [noteHeight], and waits for [release] +/// before it scans the block at [pauseAt]. +class _NoteAtHeightScanExecutor implements ZcashScanExecutor { + _NoteAtHeightScanExecutor({ + required this.noteHeight, + required this.pauseAt, + required this.paused, + required this.release, + }); + + final int noteHeight; + final int pauseAt; + final Completer paused; + final Completer release; + + @override + Future scan(zcash.ScanInputEnvelope envelope) async { + final range = envelope.range!; + if (range.start == pauseAt && !paused.isCompleted) { + paused.complete(); + await release.future; + } + final found = range.start <= noteHeight && noteHeight <= range.end; + return zcash.ZcashScanResult( + scannedBlocks: range.end - range.start + 1, + discoveredNotes: found ? 1 : 0, + totalValue: found ? 1000 : 0, + scannedHeightRange: range, + notes: [ + if (found) + zcash.ZcashScannedNote( + height: noteHeight, + tx: _cancelHashHex(noteHeight), + output: 0, + value: 1000, + pool: 'ironwood', + nullifier: '11' * 32, + commitmentPosition: 7, + blockHash: _cancelHashHex(noteHeight), + ), + ], + ); + } +} + +class _SingleBlockSyncSource implements ZcashSyncDataSource { + const _SingleBlockSyncSource(); + + @override + Future getBlockHash(int height) async => + height == 11 ? _cancelHashHex(height) : null; + + @override + Future getBlockRange( + int start, + int end, + ) async => zcash.ZcashLightwalletdScanSource([ + for (var height = start; height <= end; height++) + zcash.CompactBlock() + ..height = Int64(height) + ..hash = _cancelHashBytes(height) + ..prevHash = _cancelHashBytes(height - 1), + ]); + + @override + Future getTreeState(int height) async => zcash.TreeState( + hash: zcash.reverseTxidByteOrder(_cancelHashHex(height)), + height: height, + time: 1, + ironwood: zcash.ShieldedTree(finalState: 'tree-$height'), + ); + + @override + Future getTipHeight() async => 11; +} + +List _cancelHashBytes(int height) { + final bytes = List.filled(32, 0); + bytes[1] = height & 0xff; + bytes[2] = (height >> 8) & 0xff; + return bytes; +} + +String _cancelHashHex(int height) => [ + for (final byte in _cancelHashBytes(height)) + byte.toRadixString(16).padLeft(2, '0'), +].join(); + +class _ImmediateSyncSession implements ZcashSyncSession { + const _ImmediateSyncSession(this.outcome); + + final zcash.ZcashSyncOutcome outcome; + + @override + Future syncToTip({ + Future Function()? onAdvanced, + }) async => outcome; +} + +class _ThrowingSyncSession implements ZcashSyncSession { + const _ThrowingSyncSession(this.error); + + final Object error; + + @override + Future syncToTip({ + Future Function()? onAdvanced, + }) => Future.error(error); +} + +class _MutableSyncSession implements ZcashReorgRecoverableSyncSession { + _MutableSyncSession(this.chainHeight); + + int chainHeight; + zcash.ZcashSyncReorged? _reorg; + var resumeCalls = 0; + + void triggerReorg(zcash.ZcashSyncReorged outcome) => _reorg = outcome; + + @override + Future syncToTip({ + Future Function()? onAdvanced, + }) async { + return _reorg ?? zcash.ZcashSyncCaughtUp(chainHeight: chainHeight); + } + + @override + Future resumeFrom(zcash.ZcashReorgRecovery recovery) async { + expect(recovery, same(_reorg?.recovery)); + resumeCalls++; + _reorg = null; + } +} + +class _RepeatingShallowSyncSession implements ZcashReorgRecoverableSyncSession { + var syncCalls = 0; + var resumeCalls = 0; + var forkTreeLoads = 0; + + static const recovery = zcash.ZcashReorgRecovery( + forkHeight: 99, + forkBlockHash: + '0000000000000000000000000000000000000000000000000000000000000000', + resumeHeight: 100, + depth: 1, + ); + + @override + Future syncToTip({ + Future Function()? onAdvanced, + }) async { + syncCalls++; + return const zcash.ZcashSyncReorged( + recovery: recovery, + detection: zcash.ZcashChainReorgException( + message: 'server keeps changing the shallow fork', + height: 100, + expectedPrevHash: + '0000000000000000000000000000000000000000000000000000000000000000', + servedPrevHash: + '1111111111111111111111111111111111111111111111111111111111111111', + ), + ); + } + + @override + Future resumeFrom(zcash.ZcashReorgRecovery received) async { + resumeCalls++; + forkTreeLoads++; + expect(received, same(recovery)); + } +} + +zcash.ZcashScanResult _coverage(int start, int end) => zcash.ZcashScanResult( + scannedBlocks: end - start + 1, + discoveredNotes: 0, + totalValue: 0, + scannedHeightRange: zcash.CompactBlockScanRange(start: start, end: end), + notes: const [], +); + +String _replacementHash(int height) => switch (height) { + 150 => '22' * 32, + 151 => '33' * 32, + 152 => '44' * 32, + _ => height.toRadixString(16).padLeft(64, '0'), +}; + +List _hexBytes(String value) => [ + for (var index = 0; index < value.length; index += 2) + int.parse(value.substring(index, index + 2), radix: 16), +]; + +zcash.TreeState _replacementTreeState(int height) => zcash.TreeState( + hash: zcash.reverseTxidByteOrder(_replacementHash(height)), + height: height, + time: 1700000000 + height, +); + +zcash.CompactBlock _replacementBlock(int height) => zcash.CompactBlock( + height: Int64(height), + hash: _hexBytes(_replacementHash(height)), + prevHash: _hexBytes(_replacementHash(height - 1)), + time: 1700000000 + height, +); + +class _BackedRecoverySyncSession implements ZcashReorgRecoverableSyncSession { + _BackedRecoverySyncSession(this.state) { + sync = state.syncThrough( + chainTip: () async => 152, + fetchRange: (start, end) async => zcash.ZcashLightwalletdScanSource([ + for (var height = start; height <= end; height++) + _replacementBlock(height), + ]), + fetchTreeState: (height) async => _replacementTreeState(height), + scan: (envelope) async { + final range = envelope.range!; + return _coverage(range.start, range.end); + }, + servedBlockHashAt: (height) async => _replacementHash(height), + network: 'main', + ); + } + + final zcash.ZcashWalletSyncState state; + late final zcash.ZcashChainSync sync; + var resumed = false; + var resumeCalls = 0; + var sawRolledBackStores = false; + + static const recovery = zcash.ZcashReorgRecovery( + forkHeight: 150, + forkBlockHash: + '2222222222222222222222222222222222222222222222222222222222222222', + resumeHeight: 151, + depth: 2, + ); + + @override + Future syncToTip({ + Future Function()? onAdvanced, + }) { + if (resumed) return sync.syncToTip(); + return Future.value( + const zcash.ZcashSyncReorged( + recovery: recovery, + detection: zcash.ZcashChainReorgException( + message: 'test replacement chain', + height: 151, + expectedPrevHash: + '99999999999999999999999999999999' + '99999999999999999999999999999999', + servedPrevHash: + '22222222222222222222222222222222' + '22222222222222222222222222222222', + ), + ), + ); + } + + @override + Future resumeFrom(zcash.ZcashReorgRecovery received) async { + resumeCalls++; + sawRolledBackStores = + received.forkHeight == recovery.forkHeight && + state.sapling.coveredThrough == recovery.forkHeight && + state.orchard.coveredThrough == recovery.forkHeight && + state.ironwood.coveredThrough == recovery.forkHeight && + state.transparent.refreshedThroughHeight == recovery.forkHeight && + state.transparent.refreshedThroughBlockHash == recovery.forkBlockHash; + if (!sawRolledBackStores) { + throw StateError( + 'controller resumed before every wallet store rolled back', + ); + } + sync.resumeFrom( + recovery: received, + treeState: _replacementTreeState(received.forkHeight), + ); + resumed = true; + } +} diff --git a/test/wallets/zcash_wallet_state_test.dart b/test/wallets/zcash_wallet_state_test.dart new file mode 100644 index 000000000..94590fa45 --- /dev/null +++ b/test/wallets/zcash_wallet_state_test.dart @@ -0,0 +1,284 @@ +import 'dart:io'; +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:stackwallet/utilities/flutter_secure_storage_interface.dart'; +import 'package:stackwallet/wallets/wallet/intermediate/zcash_wallet_state.dart'; +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +void main() { + late Directory directory; + late FakeSecureStorage secrets; + + setUp(() async { + directory = await Directory.systemTemp.createTemp('zcash_state_test_'); + secrets = FakeSecureStorage(); + }); + + tearDown(() async { + await directory.delete(recursive: true); + }); + + zcash.ZcashWalletSyncState walletState({ + String fingerprint = 'account-a', + }) => zcash.ZcashWalletSyncState.atBirthday( + cursor: zcash.ZcashLightwalletdSyncCursor.fromTreeState( + const zcash.TreeState( + hash: + '0000000000000000000000000000000000000000000000000000000000000000', + height: 99, + time: 1, + ), + ), + network: zcash.ZcashAddressNetwork.mainnet, + accountFingerprint: fingerprint, + ); + + test('encrypted state reopens at the persisted birthday', () async { + final path = '${directory.path}/wallet.state'; + final store = ZcashEncryptedWalletStateStore( + path: path, + walletId: 'wallet-1', + network: 'main', + accountFingerprint: 'account-a', + secureStorage: secrets, + ); + await store.save( + ZcashPersistedWalletState( + syncState: walletState(), + observedChainHeight: 99, + transparentHistoryFrontiers: const {'t1fixture': 123}, + ), + ); + + final reopened = await store.load(); + + expect(reopened, isNotNull); + expect(reopened!.syncState.cursor.nextHeight, 100); + expect(reopened.observedChainHeight, 99); + expect(reopened.syncState.accountFingerprint, 'account-a'); + expect(reopened.transparentHistoryFrontiers, {'t1fixture': 123}); + }); + + test( + 'persisted state contains no plaintext and rejects corruption', + () async { + final path = '${directory.path}/wallet.state'; + final store = ZcashEncryptedWalletStateStore( + path: path, + walletId: 'wallet-1', + network: 'main', + accountFingerprint: 'account-a-sensitive', + secureStorage: secrets, + ); + await store.save( + ZcashPersistedWalletState( + syncState: walletState(fingerprint: 'account-a-sensitive'), + observedChainHeight: 99, + ), + ); + + final encoded = await File(path).readAsString(); + expect(encoded, isNot(contains('account-a-sensitive'))); + expect(encoded, isNot(contains('observed_chain_height'))); + + final envelope = jsonDecode(encoded) as Map; + final ciphertext = base64Decode(envelope['ciphertext'] as String); + ciphertext[0] ^= 1; + envelope['ciphertext'] = base64Encode(ciphertext); + await File(path).writeAsString(jsonEncode(envelope), flush: true); + + await expectLater( + store.load(), + throwsA(isA()), + ); + }, + ); + + test('reopen cleans an interrupted temporary write', () async { + final path = '${directory.path}/wallet.state'; + final store = ZcashEncryptedWalletStateStore( + path: path, + walletId: 'wallet-1', + network: 'main', + accountFingerprint: 'account-a', + secureStorage: secrets, + ); + await store.save( + ZcashPersistedWalletState( + syncState: walletState(), + observedChainHeight: 99, + ), + ); + final interrupted = File('$path.tmp'); + await interrupted.writeAsString('partial plaintext write'); + + final reopened = await store.load(); + + expect(reopened?.observedChainHeight, 99); + expect(await interrupted.exists(), isFalse); + }); + + test( + 'reset removes only the encrypted checkpoint and temporary write', + () async { + final path = '${directory.path}/wallet.state'; + final store = ZcashEncryptedWalletStateStore( + path: path, + walletId: 'wallet-1', + network: 'main', + accountFingerprint: 'account-a', + secureStorage: secrets, + ); + await store.save( + ZcashPersistedWalletState( + syncState: walletState(), + observedChainHeight: 99, + ), + ); + await File('$path.tmp').writeAsString('interrupted'); + final keyBefore = await secrets.read( + key: 'zcash_wallet_state_key_v1_wallet-1', + ); + + await store.reset(); + + expect(await File(path).exists(), isFalse); + expect(await File('$path.tmp').exists(), isFalse); + expect( + await secrets.read(key: 'zcash_wallet_state_key_v1_wallet-1'), + keyBefore, + ); + expect(await store.load(), isNull); + }, + ); + + test('refuses symlink state paths and foreign account contexts', () async { + final target = File('${directory.path}/target'); + await target.writeAsString('do not overwrite'); + final linkedPath = '${directory.path}/wallet.state'; + await Link(linkedPath).create(target.path); + final linkedStore = ZcashEncryptedWalletStateStore( + path: linkedPath, + walletId: 'wallet-1', + network: 'main', + accountFingerprint: 'account-a', + secureStorage: secrets, + ); + await expectLater( + linkedStore.save( + ZcashPersistedWalletState( + syncState: walletState(), + observedChainHeight: 99, + ), + ), + throwsA(isA()), + ); + expect(await target.readAsString(), 'do not overwrite'); + + await Link(linkedPath).delete(); + final correctStore = ZcashEncryptedWalletStateStore( + path: linkedPath, + walletId: 'wallet-1', + network: 'main', + accountFingerprint: 'account-a', + secureStorage: secrets, + ); + await correctStore.save( + ZcashPersistedWalletState( + syncState: walletState(), + observedChainHeight: 99, + ), + ); + final foreignStore = ZcashEncryptedWalletStateStore( + path: linkedPath, + walletId: 'wallet-1', + network: 'main', + accountFingerprint: 'account-b', + secureStorage: secrets, + ); + await expectLater( + foreignStore.load(), + throwsA(isA()), + ); + }); + + test('refuses state for a foreign consensus network', () async { + final store = ZcashEncryptedWalletStateStore( + path: '${directory.path}/wallet.state', + walletId: 'wallet-1', + network: 'main', + accountFingerprint: 'account-a', + secureStorage: secrets, + ); + final foreign = zcash.ZcashWalletSyncState.atBirthday( + cursor: zcash.ZcashLightwalletdSyncCursor.fromTreeState( + const zcash.TreeState( + hash: + '00000000000000000000000000000000' + '00000000000000000000000000000000', + height: 99, + time: 1, + ), + ), + network: zcash.ZcashAddressNetwork.testnet, + accountFingerprint: 'account-a', + ); + + await expectLater( + store.save( + ZcashPersistedWalletState(syncState: foreign, observedChainHeight: 99), + ), + throwsA(isA()), + ); + }); + + test('spendable witness state survives restart without plaintext', () async { + final state = walletState(); + const scan = zcash.ZcashScanResult( + scannedBlocks: 1, + discoveredNotes: 1, + totalValue: 123, + scannedHeightRange: zcash.CompactBlockScanRange(start: 99, end: 99), + notes: [ + zcash.ZcashScannedNote( + height: 99, + tx: + '0123456789abcdef0123456789abcdef' + '0123456789abcdef0123456789abcdef', + output: 0, + value: 123, + pool: 'sapling', + nullifier: + '11111111111111111111111111111111' + '11111111111111111111111111111111', + recipient: 'secret-sapling-recipient', + rseed: 'aabb', + witness: 'ccdd', + ), + ], + ); + state.sapling.apply(scan, accountFingerprint: 'account-a'); + state.orchard.apply(scan, accountFingerprint: 'account-a'); + state.ironwood.apply(scan, accountFingerprint: 'account-a'); + final path = '${directory.path}/wallet.state'; + final store = ZcashEncryptedWalletStateStore( + path: path, + walletId: 'wallet-1', + network: 'main', + accountFingerprint: 'account-a', + secureStorage: secrets, + ); + + await store.save( + ZcashPersistedWalletState(syncState: state, observedChainHeight: 99), + ); + final reopened = await store.load(); + final encrypted = await File(path).readAsString(); + + expect(reopened?.syncState.balance().spendableZatoshis, 123); + expect(encrypted, isNot(contains('secret-sapling-recipient'))); + expect(encrypted, isNot(contains('aabb'))); + expect(encrypted, isNot(contains('ccdd'))); + }); +} diff --git a/tool/process_pubspec_deps.dart b/tool/process_pubspec_deps.dart index d6c2b09cd..227812c2e 100644 --- a/tool/process_pubspec_deps.dart +++ b/tool/process_pubspec_deps.dart @@ -53,7 +53,15 @@ void _process(String filePath, List enableCoinMarkers) { } } - File(filePath).writeAsStringSync(updatedLines.join('\n')); + // PLACEHOLDER_IF_ becomes true for an enabled marker and false for + // any other, for a setting that follows a marker outside its block. + final output = updatedLines + .join('\n') + .replaceAllMapped( + RegExp(r'PLACEHOLDER_IF_([A-Z0-9_]+)'), + (match) => '${enableCoinMarkers.contains(match[1])}', + ); + File(filePath).writeAsStringSync(output); print( 'Updated pubspec.yaml with enabled blocks: ${enableCoinMarkers.join(", ")}', );