diff --git a/docs/building/testing.md b/docs/building/testing.md index a66ec2806..a42685662 100644 --- a/docs/building/testing.md +++ b/docs/building/testing.md @@ -37,6 +37,30 @@ Then run: python3 -m unittest discover -s scripts/linux/tests -p 'test_*.py' -v ``` +## Zcash integration tests + +The unit tests in `test/wallets/zcash_*_test.dart` use fakes and need no node. + +`integration_test/zcash/zcash_regtest_test.dart` drives `ZcashWallet`, with +the app's own `zcash-ffi` library, against a private regtest chain. It starts +a `zebrad` and a `lightwalletd` on free local ports, in a temporary directory, +and stops them when it ends. It covers a new wallet, receiving, a send with a +memo from broadcast to confirmation, spending received funds, and a restore +from the recovery phrase and birthday. Run it through the wrapper, on a Linux +or macOS host with an app configured with `ZCASH` enabled: + +```sh +bash scripts/zcash_e2e_test.sh # host desktop +bash scripts/zcash_e2e_test.sh linux # explicit device +``` + +The wrapper takes the two executables from `ZEBRAD_BIN` and +`LIGHTWALLETD_BIN`, or from `PATH`. The suite is tested with zebrad 7.0.0 and +lightwalletd 0.6.1. The Linux app links the JsonCPP and libsecret that +`build_app.sh` builds, so a checkout configured another way needs +`scripts/linux/build_secure_storage_deps.sh` run once. A Linux host without a +display needs `xvfb-run -a` in front of the command. + ## Xelis integration tests Run these on a configured desktop target (`windows`, `linux`, or `macos`) with diff --git a/integration_test/zcash/zcash_regtest_chain.dart b/integration_test/zcash/zcash_regtest_chain.dart new file mode 100644 index 000000000..3d50e7647 --- /dev/null +++ b/integration_test/zcash/zcash_regtest_chain.dart @@ -0,0 +1,426 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:path/path.dart' as path; +import 'package:stackwallet/models/node_model.dart'; +import 'package:stackwallet/wallets/crypto_currency/crypto_currency.dart'; +import 'package:zcash_flutter/zcash_flutter.dart' as zcash; + +/// A private Zcash regtest chain for the end-to-end test: a zebrad that mines +/// on demand, and a lightwalletd that serves it to wallets. +/// +/// NU6.3 is active from [nu63ActivationHeight], so every block a wallet sees +/// is one where shielded payments use the Ironwood pool. +class ZcashRegtestChain { + ZcashRegtestChain._( + this._root, + this._zebrad, + this._lightwalletd, + this._zebra, + this._lightwalletdClient, + this.lightwalletdPort, + ); + + /// The first height zebrad accepts for NU6.3 above the earlier upgrades, + /// which all activate at height 1. + static const nu63ActivationHeight = 2; + + /// Blocks before a coinbase output can be spent. + static const coinbaseMaturity = 100; + + // The miner's key is thirty-two 0x11 bytes: a regtest fixture that guards + // nothing, written out so the chain is the same on every run. + static const _minerAddress = 'tmYjAZFpvdDXTaJrq2WikAntitBNJJo9VSo'; + static final _minerSecretKey = '11' * 32; + + final Directory _root; + final _Node _zebrad; + final _Node _lightwalletd; + final zcash.ZebraClient _zebra; + final zcash.LightwalletdClient _lightwalletdClient; + final int lightwalletdPort; + final _spentCoinbases = {}; + bool _closed = false; + + /// Starts both nodes from the executables at [zebradPath] and + /// [lightwalletdPath] and mines until the first coinbase is spendable. + static Future start({ + required String zebradPath, + required String lightwalletdPath, + }) async { + final root = await Directory.systemTemp.createTemp('stack_zcash_e2e_'); + _Node? zebrad; + _Node? lightwalletd; + zcash.ZebraClient? zebra; + zcash.LightwalletdClient? lightwalletdClient; + try { + final ports = await _freePorts(4); + final zebradConfig = File(path.join(root.path, 'zebrad.toml')); + await zebradConfig.writeAsString( + _zebradConfig(rpcPort: ports[0], p2pPort: ports[1]), + ); + zebrad = await _Node.start( + 'zebrad', + zebradPath, + ['--config', zebradConfig.path, 'start'], + // zebrad also reads its configuration from ZEBRA_* variables. + environment: { + for (final entry in Platform.environment.entries) + if (!entry.key.startsWith('ZEBRA_')) entry.key: entry.value, + }, + ); + zebra = zcash.ZebraClient( + host: '127.0.0.1', + port: ports[0], + timeout: const Duration(seconds: 5), + ); + await _until('zebrad to answer RPC', [zebrad], () async { + await zebra!.getInfo(); + return true; + }); + final upgrades = (await zebra.getBlockchainInfo()).upgrades.values; + final nu63 = upgrades.where((upgrade) => upgrade.name == 'NU6.3'); + if (nu63.length != 1 || + nu63.single.activationHeight != nu63ActivationHeight) { + throw StateError( + 'zebrad does not activate NU6.3 at $nu63ActivationHeight: ' + '${[for (final u in upgrades) '${u.name}=${u.activationHeight}']}', + ); + } + + final zcashConf = File(path.join(root.path, 'zcash.conf')); + await zcashConf.writeAsString( + 'regtest=1\n' + 'rpcconnect=127.0.0.1\n' + 'rpcport=${ports[0]}\n' + 'rpcuser=stack_e2e\n' + 'rpcpassword=stack_e2e_local_only\n', + ); + final data = await Directory(path.join(root.path, 'lightwalletd')) + .create(); + lightwalletd = await _Node.start('lightwalletd', lightwalletdPath, [ + '--no-tls-very-insecure', + '--zcash-conf-path', + zcashConf.path, + '--data-dir', + data.path, + '--log-file', + path.join(root.path, 'lightwalletd.log'), + '--grpc-bind-addr', + '127.0.0.1:${ports[2]}', + '--http-bind-addr', + '127.0.0.1:${ports[3]}', + ]); + lightwalletdClient = zcash.LightwalletdClient( + host: '127.0.0.1', + port: ports[2], + useTls: false, + ); + await _until( + 'lightwalletd to answer gRPC', + [zebrad, lightwalletd], + () async { + await lightwalletdClient!.getInfo(); + return true; + }, + ); + + final chain = ZcashRegtestChain._( + root, + zebrad, + lightwalletd, + zebra, + lightwalletdClient, + ports[2], + ); + await chain.mine(coinbaseMaturity + 1); + return chain; + } catch (_) { + await lightwalletdClient?.close(); + zebra?.close(); + await lightwalletd?.stop(); + await zebrad?.stop(); + await root.delete(recursive: true); + rethrow; + } + } + + /// The lightwalletd endpoint as the primary node of [coin]. + NodeModel node(Zcash coin) => NodeModel( + host: '127.0.0.1', + port: lightwalletdPort, + name: 'Zcash regtest', + id: 'zcash-e2e-regtest', + useSSL: false, + enabled: true, + coinName: coin.identifier, + isFailover: false, + isDown: false, + torEnabled: false, + clearnetEnabled: true, + isPrimary: true, + ); + + Future height() => _zebra.getBlockCount(); + + /// The time in the header of the block at [height], in seconds. + Future blockTime(int height) async => + (await _zebra.getBlockHeader('$height')).time; + + /// Mines [blocks] blocks, each with whatever the mempool holds, and returns + /// once lightwalletd serves the last of them. + Future mine(int blocks) async { + for (var i = 0; i < blocks; i++) { + await _mineOne(); + } + final tip = await height(); + await _until( + 'lightwalletd to reach height $tip', + [_zebrad, _lightwalletd], + () async { + return (await _lightwalletdClient.getLatestBlock()).height.toInt() >= + tip; + }, + ); + } + + /// Sends one matured coinbase output, less the fee, to the Ironwood receiver + /// of [unifiedAddress]. The transaction waits in the mempool for [mine]. + Future<({String txid, int zatoshis})> fund(String unifiedAddress) async { + final tip = await height(); + final coinbase = (await _zebra.getAddressUtxos([_minerAddress])).firstWhere( + (coin) => + coin.height <= tip - coinbaseMaturity && + !_spentCoinbases.contains('${coin.txid}:${coin.outputIndex}'), + orElse: () => throw StateError('no matured coinbase is left to spend'), + ); + final tree = await _zebra.getTreeState('$tip'); + final built = zcash.buildNativeIronwoodTransaction( + network: zcash.ZcashNetwork.regtest, + targetHeight: tip + 1, + regtestNu63ActivationHeight: nu63ActivationHeight, + anchor: zcash.IronwoodAnchorSource.tree(tree.ironwood?.finalState ?? ''), + inputs: [ + zcash.TransparentBuildInput( + txid: coinbase.txid, + vout: coinbase.outputIndex, + valueZatoshis: coinbase.satoshis, + secretKeyHex: _minerSecretKey, + ), + ], + // No value: the whole input, less the fee. + ironwoodOutput: zcash.IronwoodBuildOutput(address: unifiedAddress), + allowExperimentalIronwoodBuild: true, + ); + final txid = await _zebra.sendRawTransaction(built.transactionHex); + if (txid != built.txid) { + throw StateError('zebrad accepted $txid, not the built ${built.txid}'); + } + _spentCoinbases.add('${coinbase.txid}:${coinbase.outputIndex}'); + await waitForMempool(txid); + return (txid: txid, zatoshis: coinbase.satoshis - built.feeZatoshis); + } + + /// Returns once zebrad would mine [txid] in its next block. + Future waitForMempool(String txid) => _until( + 'transaction $txid to reach the block template', + [_zebrad], + () async { + final template = await _zebra.getBlockTemplate(); + return template.transactions.any( + (entry) => entry['hash'] == txid || entry['txid'] == txid, + ); + }, + ); + + /// The last lines both nodes wrote, for a failure message. + String logs() => + '[zebrad]\n${_zebrad.tail()}\n[lightwalletd]\n${_lightwalletd.tail()}'; + + Future close() async { + if (_closed) return; + _closed = true; + await _lightwalletdClient.close(); + _zebra.close(); + await _lightwalletd.stop(); + await _zebrad.stop(); + await _root.delete(recursive: true); + } + + Future _mineOne() async { + final template = await _zebra.getBlockTemplate(); + final coinbase = template.coinbaseTxn; + final commitments = template.blockCommitmentsHash; + if (coinbase == null || commitments == null) { + throw StateError('zebrad returned an incomplete block template'); + } + final defaultMerkleRoot = template.defaultMerkleRoot; + final merkleRoot = + template.transactions.isEmpty && defaultMerkleRoot != null + ? zcash.BlockAssembler.reverseHash(_bytes(defaultMerkleRoot)) + : zcash.BlockAssembler.computeMerkleRoot([ + coinbase['hash'] as String, + for (final transaction in template.transactions) + transaction['hash'] as String, + ]); + final prefix = zcash.BlockAssembler.buildHeaderPrefix( + version: template.version, + prevBlockHash: zcash.BlockAssembler.reverseHash( + _bytes(template.previousBlockHash), + ), + merkleRoot: merkleRoot, + blockCommitments: zcash.BlockAssembler.reverseHash(_bytes(commitments)), + time: template.curTime ?? template.minTime, + bits: int.parse(template.bits, radix: 16), + ); + final solved = zcash.solveEquihash(prefix); + final rejection = await _zebra.submitBlock( + zcash.BlockAssembler.assembleBlockHex( + header: zcash.BlockAssembler.buildHeader( + headerPrefix: prefix, + nonce: solved.nonce, + solution: solved.solution, + ), + coinbaseHex: coinbase['data'] as String, + otherTxHex: [ + for (final transaction in template.transactions) + transaction['data'] as String, + ], + ), + ); + if (rejection != null && rejection.isNotEmpty) { + throw StateError('zebrad rejected the mined block: $rejection'); + } + } + + static String _zebradConfig({required int rpcPort, required int p2pPort}) => + ''' +[network] +network = "Regtest" +listen_addr = "127.0.0.1:$p2pPort" +peerset_initial_target_size = 0 +initial_mainnet_peers = [] +initial_testnet_peers = [] + +[network.testnet_parameters.activation_heights] +Overwinter = 1 +Sapling = 1 +Blossom = 1 +Heartwood = 1 +Canopy = 1 +NU5 = 1 +NU6 = 1 +"NU6.1" = 1 +"NU6.2" = 1 +"NU6.3" = $nu63ActivationHeight + +[rpc] +listen_addr = "127.0.0.1:$rpcPort" +enable_cookie_auth = false + +[state] +ephemeral = true + +[mining] +miner_address = "$_minerAddress" +'''; + + static Future> _freePorts(int count) async { + final sockets = [ + for (var i = 0; i < count; i++) + await ServerSocket.bind(InternetAddress.loopbackIPv4, 0), + ]; + final ports = [for (final socket in sockets) socket.port]; + await Future.wait(sockets.map((socket) => socket.close())); + return ports; + } + + /// Retries [ready] until it returns true, failing with the nodes' logs when + /// a node exits or the time runs out. + static Future _until( + String what, + List<_Node> nodes, + Future Function() ready, + ) async { + final deadline = DateTime.now().add(const Duration(seconds: 90)); + while (true) { + try { + if (await ready()) return; + } catch (_) { + // Not ready yet. + } + final exited = nodes.where((node) => node.exited); + if (exited.isNotEmpty || DateTime.now().isAfter(deadline)) { + final cause = exited.isEmpty + ? 'Timed out' + : '${exited.first.name} exited'; + final logs = [ + for (final node in nodes) '[${node.name}]\n${node.tail()}', + ]; + throw StateError('$cause waiting for $what\n${logs.join('\n')}'); + } + await Future.delayed(const Duration(milliseconds: 100)); + } + } + + static Uint8List _bytes(String hex) => Uint8List.fromList([ + for (var i = 0; i < hex.length; i += 2) + int.parse(hex.substring(i, i + 2), radix: 16), + ]); +} + +/// One node process and the last lines it wrote. +class _Node { + _Node._(this.name, this._process); + + static const _keptLines = 80; + + final String name; + final Process _process; + final _lines = []; + bool exited = false; + + static Future<_Node> start( + String name, + String executable, + List arguments, { + Map? environment, + }) async { + final process = await Process.start( + executable, + arguments, + environment: environment, + includeParentEnvironment: environment == null, + ); + final node = _Node._(name, process); + for (final stream in [process.stdout, process.stderr]) { + stream + .transform(utf8.decoder) + .transform(const LineSplitter()) + .listen(node._keep, onError: (_) {}); + } + unawaited(process.exitCode.then((_) => node.exited = true)); + return node; + } + + void _keep(String line) { + _lines.add(line); + if (_lines.length > _keptLines) _lines.removeAt(0); + } + + String tail() => _lines.join('\n'); + + Future stop() async { + if (exited) return; + _process.kill(); + await _process.exitCode.timeout( + const Duration(seconds: 10), + onTimeout: () { + _process.kill(ProcessSignal.sigkill); + return _process.exitCode; + }, + ); + } +} diff --git a/integration_test/zcash/zcash_regtest_test.dart b/integration_test/zcash/zcash_regtest_test.dart new file mode 100644 index 000000000..b43d30576 --- /dev/null +++ b/integration_test/zcash/zcash_regtest_test.dart @@ -0,0 +1,314 @@ +// Drives ZcashWallet against a private regtest chain: a real zebrad and a +// real lightwalletd, started by this test. Run it with +// scripts/zcash_e2e_test.sh (see docs/building/testing.md). + +import 'dart:io'; + +import 'package:bip39/bip39.dart' as bip39; +import 'package:flutter_test/flutter_test.dart'; +import 'package:integration_test/integration_test.dart'; +import 'package:isar_community/isar.dart'; +import 'package:logger/logger.dart'; +import 'package:path/path.dart' as p; +import 'package:stackwallet/app_config.dart'; +import 'package:stackwallet/db/hive/db.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/amount/amount.dart'; +import 'package:stackwallet/utilities/logger.dart'; +import 'package:stackwallet/utilities/prefs.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_wallet_state_controller.dart'; +import 'package:stackwallet/wallets/wallet/wallet.dart'; + +import '../../test/wallets/support/xelis_test_fakes.dart' show MemorySecrets; +import 'zcash_regtest_chain.dart'; + +const _zebrad = String.fromEnvironment('ZEBRAD_BIN'); +const _lightwalletd = String.fromEnvironment('LIGHTWALLETD_BIN'); + +final _coin = Zcash.regtest(); + +late ZcashRegtestChain chain; +late MemorySecrets secrets; +late Directory root; +final _open = []; +var _sequence = 0; + +/// The chain's lightwalletd as the only node there is. +class _Nodes extends Fake implements NodeService { + @override + NodeModel? getPrimaryNodeFor({required CryptoCurrency currency}) => + chain.node(_coin); +} + +Amount zec(int zatoshis) => + Amount(rawValue: BigInt.from(zatoshis), fractionDigits: 8); + +/// A wallet as the app makes it: a new one with a new recovery phrase, or one +/// restored from [mnemonic] that scans from [restoreHeight]. +Future wallet( + String name, { + String? mnemonic, + int restoreHeight = 0, +}) async { + final restore = mnemonic != null; + final wallet = await Wallet.create( + walletInfo: WalletInfo( + walletId: 'e2e-$name-${_sequence++}', + name: name, + mainAddressType: AddressType.zcashUnified, + coinName: _coin.identifier, + restoreHeight: restoreHeight, + ), + mainDB: MainDB.instance, + secureStorageInterface: secrets, + nodeService: _Nodes(), + prefs: Prefs.instance, + mnemonic: mnemonic ?? bip39.generateMnemonic(strength: 256), + mnemonicPassphrase: '', + ) as ZcashWallet; + _open.add(wallet); + wallet.configureRegtestConsensus( + nu63ActivationHeight: ZcashRegtestChain.nu63ActivationHeight, + ); + await wallet.init(isRestore: restore); + if (restore) await wallet.recover(isRescan: false); + return wallet; +} + +/// Refreshes as the app does, then updates height, history and balance with +/// errors surfaced. The base refresh only logs them. +Future sync(ZcashWallet wallet) async { + await wallet.refresh(); + await wallet.refreshMutex.protect(() async { + await wallet.updateChainHeight(); + await wallet.updateTransactions(); + await wallet.updateBalance(); + }); +} + +Future address(ZcashWallet wallet) async => + (await wallet.getCurrentReceivingAddress())!.value; + +Future> rows(ZcashWallet wallet) => MainDB + .instance + .isar + .transactionV2s + .where() + .walletIdEqualTo(wallet.walletId) + .findAll(); + +Future row(ZcashWallet wallet, String txid) async { + final matches = (await rows(wallet)).where((tx) => tx.txid == txid); + expect(matches, hasLength(1), reason: 'rows for $txid in ${wallet.walletId}'); + return matches.single; +} + +Amount received(TransactionV2 tx) => + tx.getAmountReceivedInThisWallet(fractionDigits: 8); + +Amount sent(TransactionV2 tx) => + tx.getAmountSentFromThisWallet(fractionDigits: 8, subtractFee: true); + +Amount fee(TransactionV2 tx) => tx.getFee(fractionDigits: 8); + +TxData payment(String address, Amount amount, {String? memo}) => TxData( + recipients: [ + TxRecipient( + address: address, + amount: amount, + isChange: false, + addressType: AddressType.zcashUnified, + ), + ], + memo: memo, +); + +void main() { + IntegrationTestWidgetsFlutterBinding.ensureInitialized(); + + setUpAll(() async { + if (!(Platform.isLinux || Platform.isMacOS)) { + fail('Run the Zcash regtest suite on a Linux or macOS host.'); + } + if (_zebrad.isEmpty || _lightwalletd.isEmpty) { + fail('Run this suite through scripts/zcash_e2e_test.sh.'); + } + // Zcash joins the app's coin list with its UI. Until then the suite lists + // the regtest coin itself. + AppConfig.coinsOverride = [_coin]; + root = await Directory.systemTemp.createTemp('stack_zcash_e2e_app_'); + StackFileSystem.setDesktopOverrideDir(root.path); + // A device run has no FLUTTER_TEST, so the logger needs its isolate. + final logs = Directory(p.join(root.path, 'logs'))..createSync(); + await Logging.instance.initialize(logs.path, level: Level.warning); + await MainDB.instance.initMainDB(); + final hive = DB.instance.hive..init(p.join(root.path, 'hive')); + hive.registerAdapter(NodeModelAdapter()); + await hive.openBox(DB.boxNamePrefs); + await hive.openBox(DB.boxNameNodeModels); + await Prefs.instance.init(); + secrets = MemorySecrets(); + chain = await ZcashRegtestChain.start( + zebradPath: _zebrad, + lightwalletdPath: _lightwalletd, + ); + }); + + tearDownAll(() async { + for (final wallet in _open.reversed) { + try { + await wallet.exit(); + } catch (_) {} + } + await chain.close(); + AppConfig.coinsOverride = null; + try { + await root.delete(recursive: true); + } catch (_) {} + }); + + testWidgets('receive, send and restore on a regtest chain', (tester) async { + await tester.runAsync(() async { + final alice = await wallet('alice'); + final bob = await wallet('bob'); + final aliceBirthday = alice.info.restoreHeight; + expect(aliceBirthday, await chain.height() + 1); + expect(await address(alice), startsWith('uregtest1')); + expect(await address(alice), isNot(await address(bob))); + + // Receive: a payment is not seen in the mempool, is counted with its + // first confirmation, and is spendable once it is below the anchor of + // a send. + final funding = await chain.fund(await address(alice)); + await sync(alice); + expect(alice.info.cachedBalance.total, zec(0)); + expect(await rows(alice), isEmpty); + + await chain.mine(1); + final fundedAt = await chain.height(); + await sync(alice); + expect(alice.info.cachedChainHeight, fundedAt); + expect(alice.info.cachedBalance.total, zec(funding.zatoshis)); + expect(alice.info.cachedBalance.spendable, zec(0)); + expect(alice.info.cachedBalance.pendingSpendable, zec(funding.zatoshis)); + await expectLater( + alice.prepareSend(txData: payment(await address(bob), zec(1000))), + throwsA(anything), + ); + await chain.mine(zcashAnchorDepth); + await sync(alice); + expect(alice.info.cachedBalance.spendable, zec(funding.zatoshis)); + final incoming = await row(alice, funding.txid); + expect(incoming.type, TransactionType.incoming); + expect(incoming.height, fundedAt); + expect(incoming.timestamp, await chain.blockTime(fundedAt)); + expect(received(incoming), zec(funding.zatoshis)); + + // Send: listed as unconfirmed once broadcast, then mined. + const amount = 100000000; + final prepared = await alice.prepareSend( + txData: payment(await address(bob), zec(amount), memo: 'for bob'), + ); + expect( + await alice.estimateFeeFor(zec(amount), BigInt.zero), + prepared.fee, + ); + final paidFee = prepared.fee!.raw.toInt(); + final change = funding.zatoshis - amount - paidFee; + final confirmed = await alice.confirmSend(txData: prepared); + final sendTxid = confirmed.txid!; + await chain.waitForMempool(sendTxid); + + await sync(alice); + // The payment and its fee have left the balance. The change cannot be + // spent until a block holds it. + expect(alice.info.cachedBalance.total, zec(change)); + expect(alice.info.cachedBalance.spendable, zec(0)); + expect(alice.info.cachedBalance.pendingSpendable, zec(change)); + final unmined = await row(alice, sendTxid); + expect(unmined.height, isNull); + expect(unmined.type, TransactionType.outgoing); + expect(sent(unmined), zec(amount)); + expect(fee(unmined), zec(paidFee)); + expect(await rows(alice), hasLength(2)); + + await chain.mine(1); + final sentAt = await chain.height(); + await sync(alice); + await sync(bob); + expect(alice.info.cachedBalance.total, zec(change)); + expect(alice.info.cachedBalance.spendable, zec(0)); + expect(alice.info.cachedBalance.pendingSpendable, zec(change)); + final mined = await row(alice, sendTxid); + expect(mined.id, unmined.id); + expect(mined.height, sentAt); + expect(mined.timestamp, await chain.blockTime(sentAt)); + expect(mined.type, TransactionType.outgoing); + expect(sent(mined), zec(amount)); + expect(fee(mined), zec(paidFee)); + expect(await rows(alice), hasLength(2)); + + expect(bob.info.cachedBalance.total, zec(amount)); + expect(bob.info.cachedBalance.spendable, zec(0)); + final bobIncoming = await row(bob, sendTxid); + expect(bobIncoming.type, TransactionType.incoming); + expect(bobIncoming.height, sentAt); + expect(received(bobIncoming), zec(amount)); + + // Bob can spend what he received, once it is below the anchor. + await chain.mine(zcashAnchorDepth); + await sync(alice); + await sync(bob); + expect(alice.info.cachedBalance.spendable, zec(change)); + expect(bob.info.cachedBalance.spendable, zec(amount)); + final back = await bob.prepareSend( + txData: payment(await address(alice), zec(amount ~/ 2)), + ); + final backTxid = (await bob.confirmSend(txData: back)).txid!; + await chain.waitForMempool(backTxid); + await chain.mine(1 + zcashAnchorDepth); + await sync(alice); + await sync(bob); + expect(alice.info.cachedBalance.spendable, zec(change + amount ~/ 2)); + expect( + bob.info.cachedBalance.spendable, + zec(amount - amount ~/ 2 - back.fee!.raw.toInt()), + ); + + // Restore: the recovery phrase and birthday find the same funds and + // history. + final restored = await wallet( + 'alice-restored', + mnemonic: await alice.getMnemonic(), + restoreHeight: aliceBirthday, + ); + await sync(restored); + expect(await address(restored), await address(alice)); + expect(restored.info.cachedBalance.total, alice.info.cachedBalance.total); + expect( + restored.info.cachedBalance.spendable, + alice.info.cachedBalance.spendable, + ); + expect( + {for (final tx in await rows(restored)) tx.txid: tx.height}, + {for (final tx in await rows(alice)) tx.txid: tx.height}, + ); + // The fee of a shielded send is known only to the wallet that made it, + // so a restored wallet shows it as part of the amount. + final restoredSend = await row(restored, sendTxid); + expect(restoredSend.type, TransactionType.outgoing); + expect(sent(restoredSend), zec(amount + paidFee)); + expect(fee(restoredSend), zec(0)); + }); + }, timeout: const Timeout(Duration(minutes: 15))); +} diff --git a/scripts/zcash_e2e_test.sh b/scripts/zcash_e2e_test.sh new file mode 100755 index 000000000..190c61e8a --- /dev/null +++ b/scripts/zcash_e2e_test.sh @@ -0,0 +1,66 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Runs the Zcash end-to-end suite (integration_test/zcash): ZcashWallet with +# the app's own zcash-ffi library against a private regtest chain. The suite +# starts a zebrad and a lightwalletd for itself, on free local ports and in a +# temporary directory, and stops them when it ends. +# +# It needs a zebrad and a lightwalletd executable. They are taken from +# ZEBRAD_BIN and LIGHTWALLETD_BIN, or from PATH. The suite is tested with +# zebrad 7.0.0 and lightwalletd 0.6.1. +# +# Usage: bash scripts/zcash_e2e_test.sh [device] [flutter test options] +# The device defaults to the host desktop: linux or macos. A Linux host +# without a display needs one, for example +# xvfb-run -a bash scripts/zcash_e2e_test.sh +# Set FLUTTER_BIN to use a Flutter executable other than the one on PATH. + +cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." + +flutter_bin="${FLUTTER_BIN:-flutter}" +case "$(uname -s)" in + Linux*) default_device=linux ;; + Darwin*) default_device=macos ;; + *) + printf 'The Zcash regtest suite runs on a Linux or macOS host.\n' >&2 + exit 1 + ;; +esac +device="${1:-$default_device}" +if (( $# > 0 )); then shift; fi + +if [[ ! -f pubspec.yaml ]]; then + printf 'pubspec.yaml not found. Configure the app first (scripts/build_app.sh).\n' >&2 + exit 1 +fi +# An app without the ZCASH flag depends on zcash_flutter but does not build +# its library. +if ! grep -A1 '^ zcash_flutter:$' pubspec.yaml | grep -q '^ enabled: true$'; then + printf 'The zcash_flutter library is not built. Configure an app with ZCASH enabled.\n' >&2 + exit 1 +fi + +# Prints the absolute path of the executable named by $1, or by $2 on PATH. +executable() { + local found + if [[ -n "$1" ]]; then + found="$1" + else + found="$(command -v "$2" || true)" + fi + if [[ -z "$found" || ! -x "$found" ]]; then + printf '%s not found. Install it or set %s.\n' "$2" "$3" >&2 + return 1 + fi + printf '%s/%s\n' "$(cd -- "$(dirname -- "$found")" && pwd)" "$(basename -- "$found")" +} + +zebrad="$(executable "${ZEBRAD_BIN:-}" zebrad ZEBRAD_BIN)" +lightwalletd="$(executable "${LIGHTWALLETD_BIN:-}" lightwalletd LIGHTWALLETD_BIN)" + +"$flutter_bin" test integration_test/zcash/zcash_regtest_test.dart \ + -d "$device" \ + --dart-define=ZEBRAD_BIN="$zebrad" \ + --dart-define=LIGHTWALLETD_BIN="$lightwalletd" \ + "$@"