diff --git a/docs/building/testing.md b/docs/building/testing.md index eaf2940f5..323a7fef3 100644 --- a/docs/building/testing.md +++ b/docs/building/testing.md @@ -46,9 +46,9 @@ 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, a restore from -the recovery phrase and birthday, and a payment to a Sapling address. Run it -through the wrapper, on a Linux -or macOS host with an app configured with `ZCASH` enabled: +the recovery phrase and birthday, a payment to a Sapling address, and moving +Sapling and transparent funds to Ironwood. 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 diff --git a/integration_test/zcash/zcash_regtest_test.dart b/integration_test/zcash/zcash_regtest_test.dart index 26b463f26..016cc9965 100644 --- a/integration_test/zcash/zcash_regtest_test.dart +++ b/integration_test/zcash/zcash_regtest_test.dart @@ -26,6 +26,7 @@ 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_send.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; @@ -354,6 +355,93 @@ void main() { expect(bob.info.cachedBalance.total, bobBefore.total + zec(amount ~/ 4)); expect(bob.info.cachedBalance.spendable, bobBefore.spendable); expect(received(await row(bob, saplingTxid)), zec(amount ~/ 4)); + + // Bob moves the Sapling funds to Ironwood, where a send can spend + // them, once they are below the anchor of a move. + expect((await bob.movableFunds())[ZcashMovablePool.sapling], zec(0)); + await chain.mine(zcashAnchorDepth); + await sync(bob); + expect( + (await bob.movableFunds())[ZcashMovablePool.sapling], + zec(amount ~/ 4), + ); + final fromSapling = await bob.prepareMoveToIronwood( + ZcashMovablePool.sapling, + ); + final saplingMoved = fromSapling.recipients!.single.amount; + expect(fromSapling.recipients!.single.address, await address(bob)); + // The move leaves one zatoshi of Sapling change. + expect(saplingMoved + fromSapling.fee!, zec(amount ~/ 4 - 1)); + final saplingMoveTxid = (await bob.confirmSend(txData: fromSapling)) + .txid!; + await chain.waitForMempool(saplingMoveTxid); + // The notes are held by the move until it is mined. + expect((await bob.movableFunds())[ZcashMovablePool.sapling], zec(0)); + await chain.mine(1); + await sync(bob); + expect( + bob.info.cachedBalance.total, + bobBefore.total + zec(amount ~/ 4) - fromSapling.fee!, + ); + // What was moved is pending until it is below the anchor of a send. + expect(bob.info.cachedBalance.spendable, bobBefore.spendable); + expect(bob.info.cachedBalance.pendingSpendable, saplingMoved); + await chain.mine(zcashAnchorDepth); + await sync(bob); + expect( + bob.info.cachedBalance.spendable, + bobBefore.spendable + saplingMoved, + ); + final saplingMove = await row(bob, saplingMoveTxid); + expect(saplingMove.type, TransactionType.sentToSelf); + expect(received(saplingMove), saplingMoved); + expect(fee(saplingMove), fromSapling.fee); + + // A payment to the transparent receiver of Bob's address, which he + // moves to Ironwood as well. + final bobTransparent = zcash + .inventoryUnifiedAddressReceivers( + address: await address(bob), + network: zcash.ZcashNetwork.regtest, + ) + .receivers + .firstWhere( + (receiver) => receiver.kind == zcash.ZcashAddressReceiverType.p2pkh, + ) + .address!; + await sync(alice); + final toTransparent = await alice.prepareSend( + txData: payment(bobTransparent, zec(amount ~/ 8)), + ); + final transparentTxid = (await alice.confirmSend(txData: toTransparent)) + .txid!; + await chain.waitForMempool(transparentTxid); + await chain.mine(1); + await sync(bob); + final bobShielded = bob.info.cachedBalance.spendable; + expect( + (await bob.movableFunds())[ZcashMovablePool.transparent], + zec(amount ~/ 8), + ); + final fromTransparent = await bob.prepareMoveToIronwood( + ZcashMovablePool.transparent, + ); + final transparentMoved = fromTransparent.recipients!.single.amount; + expect(transparentMoved + fromTransparent.fee!, zec(amount ~/ 8)); + final transparentMoveTxid = (await bob.confirmSend( + txData: fromTransparent, + )).txid!; + await chain.waitForMempool(transparentMoveTxid); + // The coins are held by the move until it is mined. + expect((await bob.movableFunds())[ZcashMovablePool.transparent], zec(0)); + await chain.mine(1 + zcashAnchorDepth); + await sync(bob); + expect(bob.info.cachedBalance.spendable, bobShielded + transparentMoved); + expect((await bob.movableFunds())[ZcashMovablePool.transparent], zec(0)); + final transparentMove = await row(bob, transparentMoveTxid); + expect(transparentMove.type, TransactionType.sentToSelf); + expect(received(transparentMove), transparentMoved); + expect(fee(transparentMove), fromTransparent.fee); }); }, timeout: const Timeout(Duration(minutes: 15))); } diff --git a/lib/wallets/wallet/impl/zcash_wallet.dart b/lib/wallets/wallet/impl/zcash_wallet.dart index e406100cb..3883a8036 100644 --- a/lib/wallets/wallet/impl/zcash_wallet.dart +++ b/lib/wallets/wallet/impl/zcash_wallet.dart @@ -358,60 +358,16 @@ class ZcashWallet extends Bip39Wallet { ), ); } - 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, - ), + final prepared = await _prepareLocked( + payments: [ + for (final payment in resolved) + ZcashSendPayment( + recipient: payment.address, + amountZatoshis: payment.amount.toInt(), + memo: payment.memo, + ), + ], ); - // 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'); @@ -433,6 +389,183 @@ class ZcashWallet extends Bip39Wallet { }, ); + /// Syncs, then prepares [payments], or a move of the funds of [moveFrom] + /// to Ironwood, and keeps the result as the wallet's one prepared + /// transaction. Call under [_sendMutex]. + Future _prepareLocked({ + required List payments, + ZcashMovablePool? moveFrom, + }) async { + 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 saplingChange = moveFrom == ZcashMovablePool.sapling + ? await _saplingChangeAddress() + : null; + 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: payments, + targetHeight: snapshot.chainHeight + 1, + expiryHeight: snapshot.chainHeight + 41, + resolveSaplingProvingParameters: _saplingParameterResolver, + regtestNu63ActivationHeight: _regtestNu63ActivationHeight, + moveFrom: moveFrom, + saplingChangeAddress: saplingChange, + unavailableOutpoints: await _unavailableOutpointsAt( + snapshot.chainHeight, + ), + ), + ); + // 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; + return prepared; + } + + /// What the wallet holds outside Ironwood, by pool, that + /// [prepareMoveToIronwood] can move there, as of the last sync. A send + /// spends Ironwood funds only. + Future> movableFunds() async { + final persisted = await _stateStore?.load(); + if (persisted == null) { + return {for (final pool in ZcashMovablePool.values) pool: _amount(0)}; + } + final height = persisted.observedChainHeight; + final sapling = ZcashProductionWalletSendService.movableSaplingNotes( + persisted.syncState, + await _pendingSendStore?.load(), + height, + holdPrepared: false, + ); + final transparent = + ZcashProductionWalletSendService.movableTransparentCoins( + persisted.syncState, + await _unavailableOutpointsAt(height), + height, + ); + // What could not pay the fee of its move is not offered. + Amount movable(ZcashMovablePool pool, Iterable values) => _amount( + ZcashProductionWalletSendService.movableZatoshis(pool, values.toList()), + ); + return { + ZcashMovablePool.sapling: movable( + ZcashMovablePool.sapling, + sapling.map((note) => note.value), + ), + ZcashMovablePool.transparent: movable( + ZcashMovablePool.transparent, + transparent.map((coin) => coin.valueZatoshis), + ), + }; + } + + /// Prepares a transaction that moves the funds of [pool] to the wallet's + /// own Ironwood receiver, less the fee (and less one zatoshi from Sapling, + /// see [ZcashProductionWalletSendService.saplingMoveChangeZatoshis]). It is + /// confirmed with [confirmSend] or dropped with [cancelSend], as a send is. + /// + /// One transaction moves at most the 50 largest notes or coins. What is + /// left takes another move. + Future prepareMoveToIronwood(ZcashMovablePool pool) async { + if (pool == ZcashMovablePool.sapling) { + // Spending Sapling notes is proven with the Sapling parameters. As for + // a send, a download of them happens before the send lock is taken. + await _saplingParameterResolver(); + } + return _sendMutex.protect(() async { + final prepared = await _prepareLocked(payments: const [], moveFrom: pool); + return TxData( + raw: prepared.transactionHex, + txid: prepared.txid, + fee: _amount(prepared.feeZatoshis), + recipients: [ + TxRecipient( + address: prepared.encodedRecipient, + amount: _amount(prepared.amountZatoshis), + isChange: false, + addressType: AddressType.zcashUnified, + ), + ], + vExtraData: _preparedDigest(prepared), + ); + }); + } + + /// The moves of transparent coins to Ironwood that were handed to a node, + /// by txid. They are kept with the pending sends, which have no record of + /// such a move. + Future> _transparentMoves() async => + await _pendingSendStore?.loadTransparentMoves() ?? const {}; + + /// Records [move], unless it is recorded already. Whether it did. Moves + /// that cannot be mined at [chainHeight] any more let go of their coins. + Future _recordTransparentMove( + ZcashPendingSendStore store, + ZcashPreparedTransparentMove move, + int chainHeight, + ) async { + final txid = move.txid.toLowerCase(); + var recorded = false; + await store.updateTransparentMoves((moves) { + for (final entry in moves.entries.toList()) { + if (chainHeight >= entry.value.expiryHeight && + entry.value.outpoints.isNotEmpty) { + moves[entry.key] = ZcashTransparentMoveRecord( + feeZatoshis: entry.value.feeZatoshis, + expiryHeight: entry.value.expiryHeight, + ); + } + } + if (moves.containsKey(txid)) return; + moves[txid] = ZcashTransparentMoveRecord( + feeZatoshis: move.feeZatoshis, + expiryHeight: move.expiryHeight, + outpoints: move.outpoints, + ); + recorded = true; + }); + return recorded; + } + + /// The coins of the transparent moves that may still be mined at + /// [chainHeight]. + Future> _unavailableOutpointsAt(int chainHeight) async => { + for (final move in (await _transparentMoves()).values) + if (chainHeight < move.expiryHeight) ...move.outpoints, + }; + /// 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. @@ -472,11 +605,13 @@ class ZcashWallet extends Bip39Wallet { } 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, + for (final note + in record.sourcePool == zcash.ShieldedPendingSourcePool.ironwood + ? persisted.syncState.ironwood.notes + : persisted.syncState.sapling.notes) + if (note.nullifier != null && + record.selectedNullifiers.contains(note.nullifier)) + note, ]; if (notes.length != record.selectedNullifiers.length) { throw StateError( @@ -545,9 +680,25 @@ class ZcashWallet extends Bip39Wallet { pendingSends: pending, chainHeight: chainHeight, persist: () => store.save(pending), - submit: (transactionHex) { + submit: (transactionHex) async { _requirePreparedSession(prepared, session); - return session.submitTransactionHex(transactionHex); + // As for a pending send, the record is written before the + // transaction leaves. + final recorded = + prepared is ZcashPreparedTransparentMove && + await _recordTransparentMove(store, prepared, chainHeight); + try { + return await session.submitTransactionHex(transactionHex); + } on ZcashBroadcastRejectedException { + // Only the refusal of a first submission says the coins are + // free: an earlier one may have reached the node. + if (recorded) { + await store.updateTransparentMoves( + (moves) => moves.remove(prepared.txid.toLowerCase()), + ); + } + rethrow; + } }, ); } catch (_) { @@ -561,7 +712,15 @@ class ZcashWallet extends Bip39Wallet { record.txid.toLowerCase() == prepared.txid.toLowerCase(), ) .firstOrNull; - if (left == null) { + if (prepared is ZcashPreparedTransparentMove) { + // It has no pending record. The wallet's own record of it says + // whether a submission may have reached the node. + final moves = await store.loadTransparentMoves(); + if (chainHeight >= prepared.expiryHeight || + !moves.containsKey(prepared.txid.toLowerCase())) { + _preparedSend = null; + } + } else if (left == null) { _preparedSend = null; } else if (left.broadcastState == zcash.IronwoodPendingBroadcastState.prepared && @@ -828,6 +987,11 @@ class ZcashWallet extends Bip39Wallet { pendingSends: pending, timestamps: timestamps, chainHeight: snapshot.chainHeight, + ownAddresses: {await _ironwoodChangeAddress()}, + moveFees: { + for (final entry in (await _transparentMoves()).entries) + entry.key: entry.value.feeZatoshis, + }, ); final current = {}; for (final transaction in transactions) { @@ -1057,6 +1221,15 @@ class ZcashWallet extends Bip39Wallet { _accountSession ?? (throw StateError('Zcash requires an initialized account session')); + Future _saplingChangeAddress() async { + final rows = await mainDB.getAddresses(walletId).findAll(); + final matches = rows.where((row) => row.type == AddressType.zcashSapling); + if (matches.length != 1) { + throw StateError('Zcash wallet has no unambiguous Sapling receiver'); + } + return matches.single.value; + } + Future _ironwoodChangeAddress() async { final rows = await mainDB.getAddresses(walletId).findAll(); final matches = rows.where((row) => row.type == AddressType.zcashUnified); diff --git a/lib/wallets/wallet/intermediate/zcash_pending_send_store.dart b/lib/wallets/wallet/intermediate/zcash_pending_send_store.dart index 020904d8b..b9c03dc53 100644 --- a/lib/wallets/wallet/intermediate/zcash_pending_send_store.dart +++ b/lib/wallets/wallet/intermediate/zcash_pending_send_store.dart @@ -8,10 +8,52 @@ import '../../../utilities/flutter_secure_storage_interface.dart'; import 'zcash_wallet_state.dart'; import 'zcash_wallet_persistence.dart'; +/// A move of transparent coins to Ironwood that was handed to the node. The +/// pending sends are for shielded notes, so such a move has no record there. +final class ZcashTransparentMoveRecord { + const ZcashTransparentMoveRecord({ + required this.feeZatoshis, + required this.expiryHeight, + this.outpoints = const {}, + }); + + factory ZcashTransparentMoveRecord.fromJson(Map json) => + ZcashTransparentMoveRecord( + feeZatoshis: json['fee'] as int, + expiryHeight: json['expiry'] as int, + outpoints: {...(json['outpoints'] as List).cast()}, + ); + + /// The node does not report the fee of the mined transaction. + final int feeZatoshis; + + /// The move cannot be mined from this height on. + final int expiryHeight; + + /// The coins the move spends, as `txid:index`. Empty once they are no + /// longer held back. + final Set outpoints; + + Map toJson() => { + 'fee': feeZatoshis, + 'expiry': expiryHeight, + 'outpoints': outpoints.toList(), + }; +} + abstract interface class ZcashPendingSendStore { Future load(); Future save(zcash.IronwoodPendingSendState state); + + /// The recorded moves of transparent coins, by lower-case txid. + Future> loadTransparentMoves(); + + /// Applies [change] to the recorded moves and stores the result, as one + /// step that no other load or save of this store runs into. + Future updateTransparentMoves( + void Function(Map moves) change, + ); } /// An account-bound store kept separate from the sync checkpoint. @@ -30,6 +72,9 @@ final class ZcashEncryptedPendingSendStore implements ZcashPendingSendStore { static const _envelopeVersion = 1; static const _payloadVersion = 1; + + /// Optional in the payload: absent until a transparent move is recorded. + static const _movesField = 'transparent_moves'; static final _cipher = AesGcm.with256bits(); final String path; @@ -47,17 +92,70 @@ final class ZcashEncryptedPendingSendStore implements ZcashPendingSendStore { @override Future load() => - withZcashFileLock(path, _load); + withZcashFileLock(path, () async => _pendingOf(await _loadPayload())); @override Future save(zcash.IronwoodPendingSendState state) => - withZcashFileLock(path, () => _save(state)); + withZcashFileLock(path, () async { + Object? moves; + try { + moves = (await _loadPayload())?[_movesField]; + } on ZcashStatePersistenceException { + // A file that cannot be read is replaced, as before it held moves. + } + await _save(pending: state.toJson(), moves: moves); + }); + + @override + Future> loadTransparentMoves() => + withZcashFileLock(path, () async => _movesOf(await _loadPayload())); - Future _load() async { + @override + Future updateTransparentMoves( + void Function(Map moves) change, + ) => withZcashFileLock(path, () async { + final payload = await _loadPayload(); + final moves = _movesOf(payload); + change(moves); + await _save( + pending: _pendingOf(payload).toJson(), + moves: {for (final move in moves.entries) move.key: move.value.toJson()}, + ); + }); + + static zcash.IronwoodPendingSendState _pendingOf( + Map? payload, + ) => payload == null + ? zcash.IronwoodPendingSendState() + : zcash.IronwoodPendingSendState.fromJson( + (payload['pending'] as Map).cast(), + ); + + static Map _movesOf( + Map? payload, + ) { + final stored = payload?[_movesField]; + try { + return { + if (stored is Map) + for (final move in stored.entries) + move.key as String: ZcashTransparentMoveRecord.fromJson( + (move.value as Map).cast(), + ), + }; + } on Object { + throw const ZcashStatePersistenceException( + 'pending-send state holds a malformed transparent move', + ); + } + } + + /// The decrypted payload, or null when nothing was saved yet. + Future?> _loadPayload() async { await _refuseSymlink(path); await _removeInterruptedWrite(); final file = File(path); - if (!await file.exists()) return zcash.IronwoodPendingSendState(); + if (!await file.exists()) return null; final encodedKey = await secureStorage.read(key: _keyName); if (encodedKey == null) { throw const ZcashStatePersistenceException( @@ -91,9 +189,9 @@ final class ZcashEncryptedPendingSendStore implements ZcashPendingSendStore { 'pending-send payload belongs to another wallet or is malformed', ); } - return zcash.IronwoodPendingSendState.fromJson( - (payload['pending'] as Map).cast(), - ); + // Read here, so that a malformed state is reported as a corrupt file. + _pendingOf(payload); + return payload; } on ZcashStatePersistenceException { rethrow; } on Object { @@ -104,7 +202,10 @@ final class ZcashEncryptedPendingSendStore implements ZcashPendingSendStore { } } - Future _save(zcash.IronwoodPendingSendState state) async { + Future _save({ + required Map pending, + required Object? moves, + }) async { await _refuseSymlink(path); await _refuseSymlink('$path.tmp'); var encodedKey = await secureStorage.read(key: _keyName); @@ -119,7 +220,8 @@ final class ZcashEncryptedPendingSendStore implements ZcashPendingSendStore { 'version': _payloadVersion, 'network': network, 'account_fingerprint': accountFingerprint, - 'pending': state.toJson(), + 'pending': pending, + _movesField: ?moves, }), ); final box = await _cipher.encrypt( diff --git a/lib/wallets/wallet/intermediate/zcash_send.dart b/lib/wallets/wallet/intermediate/zcash_send.dart index d153e63d1..1d7311c95 100644 --- a/lib/wallets/wallet/intermediate/zcash_send.dart +++ b/lib/wallets/wallet/intermediate/zcash_send.dart @@ -138,6 +138,84 @@ final class ZcashPreparedIronwoodBatch extends ZcashPreparedWalletSend { List.unmodifiable(prepared.plan.notes); } +/// Sapling notes moved to the wallet's own Ironwood receiver. +final class ZcashPreparedSaplingMove extends ZcashPreparedWalletSend { + ZcashPreparedSaplingMove({ + required this.prepared, + required super.sessionGeneration, + }) : super( + encodedRecipient: prepared.plan.output.encodedAddress, + selectedReceiver: prepared.plan.output.selectedReceiver, + selectedReceiverAddress: prepared.plan.output.receiverAddress, + actualOutputPool: prepared.plan.output.actualOutputPool, + memo: null, + ) { + requireValueConservation(); + } + + final zcash.SaplingPreparedPayment 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); +} + +/// Transparent coins moved to the wallet's own Ironwood receiver. +final class ZcashPreparedTransparentMove extends ZcashPreparedWalletSend { + ZcashPreparedTransparentMove({ + required this.prepared, + required this.expiryHeight, + required super.sessionGeneration, + required super.encodedRecipient, + }) : super( + selectedReceiver: zcash.ZcashAddressReceiverType.unified, + selectedReceiverAddress: encodedRecipient, + actualOutputPool: zcash.ProposalOutputPool.ironwood, + memo: null, + ) { + requireValueConservation(); + } + + final zcash.ShieldingPreparedSend prepared; + + @override + final int expiryHeight; + + /// The coins the transaction spends, as `txid:index`. + Set get outpoints => { + for (final coin in prepared.selection.coins) coin.outpoint, + }; + + @override + String get transactionHex => prepared.transactionHex; + @override + String get txid => prepared.txid; + @override + int get amountZatoshis => prepared.shieldedZatoshis; + @override + int get feeZatoshis => prepared.feeZatoshis; + @override + int get inputZatoshis => prepared.selection.inputZatoshis; + @override + int get changeZatoshis => prepared.selection.changeZatoshis; + @override + List get selectedNotes => const []; +} + final class ZcashRecoveredPreparedSend extends ZcashPreparedWalletSend { ZcashRecoveredPreparedSend({ required this.record, @@ -239,6 +317,10 @@ zcash.ProposalOutputPool _proposalPool(zcash.IronwoodDestinationPool pool) => zcash.ProposalOutputPool.ironwood, }; +/// A pool whose funds [ZcashSendPreparationRequest.moveFrom] moves to +/// Ironwood, the one pool the wallet pays from. +enum ZcashMovablePool { sapling, transparent } + class ZcashSendPayment { const ZcashSendPayment({ required this.recipient, @@ -266,6 +348,9 @@ class ZcashSendPreparationRequest { required this.expiryHeight, required this.resolveSaplingProvingParameters, this.regtestNu63ActivationHeight, + this.moveFrom, + this.saplingChangeAddress, + this.unavailableOutpoints = const {}, }); final zcash.ZcashNetwork network; @@ -282,6 +367,37 @@ class ZcashSendPreparationRequest { final Future Function() resolveSaplingProvingParameters; final int? regtestNu63ActivationHeight; + + /// When set, the request has no [payments]: it moves what the wallet + /// holds in this pool to [ironwoodChangeAddress], less the fee. + final ZcashMovablePool? moveFrom; + + /// Where a move from Sapling returns what it does not move. + final String? saplingChangeAddress; + + /// Transparent coins, as `txid:index`, that a move which may still be + /// mined already spends. + final Set unavailableOutpoints; +} + +/// Builds the transaction that moves [coins] to the Ironwood receiver of +/// [ZcashSendPreparationRequest.ironwoodChangeAddress]. [ironwoodFrontier] is +/// the Ironwood tree at the block before the target height, null while that +/// tree has no notes. +typedef ZcashTransparentMoveBuilder = zcash.ShieldingPreparedSend Function({ + required ZcashSendPreparationRequest request, + required zcash.TransparentCoinSet coins, + required String? ironwoodFrontier, +}); + +/// A move cannot be made as asked. [message] is shown to the user. +class ZcashMoveException implements Exception { + const ZcashMoveException(this.message); + + final String message; + + @override + String toString() => message; } abstract interface class ZcashIronwoodSpendMaterialProvider { @@ -339,6 +455,8 @@ final class ZcashProductionWalletSendService implements ZcashWalletSendService { this.spendMaterialProvider = const ZcashNativeIronwoodSpendMaterialProvider(), this.ironwoodPaymentBackend, + this.maxSaplingWitnessBlocks = 20000, + this.transparentMoveBuilder = buildNativeTransparentMove, }); final int maxSpendNotes; @@ -348,6 +466,51 @@ final class ZcashProductionWalletSendService implements ZcashWalletSendService { final ZcashIronwoodSpendMaterialProvider spendMaterialProvider; final zcash.IronwoodPaymentBackend? ironwoodPaymentBackend; + /// How many blocks a move from Sapling may download to witness its notes. + /// They are fetched in one request and held in memory, so a note older + /// than this is refused. + final int maxSaplingWitnessBlocks; + + final ZcashTransparentMoveBuilder transparentMoveBuilder; + + /// What a move from Sapling leaves behind as Sapling change. The backend + /// refuses a Sapling-funded transaction without change: its check of the + /// built transaction expects no Sapling outputs then, and the builder + /// always pads them to two. + static const saplingMoveChangeZatoshis = 1; + + /// What ZIP 317 charges for each input of a transaction. A note or coin + /// that holds no more costs as much to move as it is worth, so a move + /// leaves it where it is. + static const feePerInputZatoshis = 5000; + + /// The fee ZIP 317 sets for a move of [inputs] notes or coins from [pool]: + /// [feePerInputZatoshis] for each of them, of which a Sapling transaction + /// pays for two at least, and for the two actions of the Ironwood output. + static int moveFeeZatoshis(ZcashMovablePool pool, int inputs) => + feePerInputZatoshis * + (2 + + switch (pool) { + ZcashMovablePool.sapling => inputs < 2 ? 2 : inputs, + ZcashMovablePool.transparent => inputs, + }); + + /// What moves from [pool] can take of [values], the worth of each of its + /// movable notes or coins, largest first: all of it, or nothing when the + /// first move, of the [maxInputs] largest, could not pay its fee. + static int movableZatoshis( + ZcashMovablePool pool, + List values, { + int maxInputs = 50, + }) { + final first = values.take(maxInputs); + final needed = + moveFeeZatoshis(pool, first.length) + + (pool == ZcashMovablePool.sapling ? saplingMoveChangeZatoshis : 0); + final held = first.fold(0, (sum, value) => sum + value); + return held > needed ? values.fold(0, (sum, value) => sum + value) : 0; + } + @override Future broadcast({ required ZcashPreparedWalletSend prepared, @@ -402,6 +565,32 @@ final class ZcashProductionWalletSendService implements ZcashWalletSendService { pendingSends.markIndeterminate(prepared.txid); rethrow; } + case ZcashPreparedSaplingMove(): + pendingSends.requireBroadcastableSaplingPayment( + 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 ZcashPreparedTransparentMove(): + // It has no pending record: a node refuses a second transaction that + // spends the same coins, and the wallet holds them back meanwhile. + if (chainHeight >= prepared.expiryHeight) { + throw const ZcashMoveException( + 'This transaction can no longer be mined. Prepare it again.', + ); + } + await submit(prepared.transactionHex); case ZcashRecoveredPreparedSend(): // The stored record must still be the one that was reviewed, apart // from its broadcast state, which changes with each attempt. @@ -440,6 +629,14 @@ final class ZcashProductionWalletSendService implements ZcashWalletSendService { Future prepare( ZcashSendPreparationRequest request, ) async { + switch (request.moveFrom) { + case ZcashMovablePool.sapling: + return _prepareSaplingMove(request); + case ZcashMovablePool.transparent: + return _prepareTransparentMove(request); + case null: + break; + } final outputs = [ for (final payment in request.payments) _resolveOutput( @@ -524,8 +721,8 @@ final class ZcashProductionWalletSendService implements ZcashWalletSendService { ); } - /// Funds [outputs] from the wallet's Ironwood notes, the one pool this - /// wallet spends from. + /// Funds [outputs] from the wallet's Ironwood notes, the one pool a + /// payment spends from. Future _prepareIronwood( ZcashSendPreparationRequest request, List outputs, @@ -637,6 +834,469 @@ final class ZcashProductionWalletSendService implements ZcashWalletSendService { memo: output.memo, ); } + + /// The Sapling notes of [state] that are worth moving, not spent, and not + /// held by a transaction of [pendingSends] that may still be mined at + /// [chainHeight], largest first. + /// + /// Without [holdPrepared], a transaction that was prepared and never + /// submitted holds nothing: the next preparation releases it. + /// + /// A move spends from the tree [anchorDepth] blocks below the tip, as a + /// send does, so a note above that is left out. + static List movableSaplingNotes( + zcash.ZcashWalletSyncState state, + zcash.IronwoodPendingSendState? pendingSends, + int chainHeight, { + bool holdPrepared = true, + int anchorDepth = zcashAnchorDepth, + }) { + final spent = {for (final spend in state.sapling.spends) spend.nullifier}; + final reserved = { + for (final record + in pendingSends?.records ?? const []) + if (record.sourcePool == zcash.ShieldedPendingSourcePool.sapling && + !record.isExpiredAt(chainHeight) && + (holdPrepared || + record.broadcastState != + zcash.IronwoodPendingBroadcastState.prepared)) + ...record.selectedNullifiers, + }; + return [ + for (final note in state.sapling.notes) + if (note.nullifier != null && + note.commitmentPosition != null && + note.value > feePerInputZatoshis && + note.height <= chainHeight - anchorDepth && + !spent.contains(note.nullifier) && + !reserved.contains(note.nullifier)) + note, + ]..sort((left, right) => right.value.compareTo(left.value)); + } + + /// The transparent coins of [state] that are worth moving, can be spent + /// at [chainHeight] and are not among [unavailable], largest first. + static List movableTransparentCoins( + zcash.ZcashWalletSyncState state, + Set unavailable, + int chainHeight, + ) { + final outputs = { + for (final output in state.transparent.unspentOutputs) + '${output.txid}:${output.outputIndex}': output, + }; + final coins = zcash.TransparentCoinSet.fromUtxos( + utxos: outputs.values.map((output) => output.utxo), + chainHeight: chainHeight, + coinbaseOutpoints: { + for (final entry in outputs.entries) + if (entry.value.isCoinbase) entry.key, + }, + ); + return [ + for (final coin in coins.spendable) + if (!unavailable.contains(coin.outpoint) && + outputs[coin.outpoint]!.valueZatoshis > feePerInputZatoshis) + outputs[coin.outpoint]!, + ]..sort((left, right) => right.valueZatoshis.compareTo(left.valueZatoshis)); + } + + /// Moves the wallet's Sapling notes, the largest [maxSpendNotes] of them, + /// to its Ironwood receiver. + Future _prepareSaplingMove( + ZcashSendPreparationRequest request, + ) async { + final changeAddress = request.saplingChangeAddress; + if (changeAddress == null || changeAddress.isEmpty) { + throw StateError('A move from Sapling needs a Sapling change address'); + } + final chainHeight = request.targetHeight - 1; + final anchorHeight = chainHeight - anchorDepth; + final notes = movableSaplingNotes( + request.state, + request.pendingSends, + chainHeight, + anchorDepth: anchorDepth, + ); + if (notes.length > maxSpendNotes) { + notes.removeRange(maxSpendNotes, notes.length); + } + if (notes.isEmpty) { + throw const ZcashMoveException( + 'This wallet has no Sapling funds that are free to move.', + ); + } + final oldest = notes + .map((note) => note.height) + .reduce((a, b) => a < b ? a : b); + if (anchorHeight - oldest >= maxSaplingWitnessBlocks) { + throw ZcashMoveException( + 'These Sapling funds were received more than ' + '$maxSaplingWitnessBlocks blocks ago. This version cannot move ' + 'funds that old.', + ); + } + final scan = await acquireSaplingWitnesses( + network: request.network.ffiLabel, + client: request.syncClient, + scanExecutor: request.scanExecutor, + notes: notes, + anchorHeight: anchorHeight, + ); + final provingParameters = await request.resolveSaplingProvingParameters(); + final backend = ironwoodPaymentBackend; + + // What all the notes pay in fees. The amount is the rest less the + // change, so the planner selects every note. + final destination = _resolveOutput( + network: request.network, + payment: ZcashSendPayment( + recipient: request.ironwoodChangeAddress, + amountZatoshis: 1, + ), + targetHeight: request.targetHeight, + expiryHeight: request.expiryHeight, + ); + final saplingSpends = [ + for (final note in scan.notes) + zcash.IronwoodBuildSpendNote.fromScannedNote( + note, + anchorHex: scan.saplingAnchor!, + ), + ]; + final ironwoodOutput = zcash.IronwoodBuildOutput( + address: destination.receiverAddress, + ); + final change = [ + zcash.TransparentBuildOutput( + address: changeAddress, + valueZatoshis: saplingMoveChangeZatoshis, + ), + ]; + final fee = backend != null + ? backend + .quote( + zcash.IronwoodPaymentNativeRequest( + targetHeight: request.targetHeight, + expiryHeight: request.expiryHeight, + anchorHex: scan.ironwoodAnchor!, + saplingSpends: saplingSpends, + ironwoodSpends: const [], + outputs: change, + ironwoodOutput: ironwoodOutput, + provingParameters: provingParameters, + ), + ) + .feeZatoshis + : zcash + .quoteNativeIronwoodFee( + network: request.network, + targetHeight: request.targetHeight, + expiryHeight: request.expiryHeight, + regtestNu63ActivationHeight: + request.regtestNu63ActivationHeight, + anchor: zcash.IronwoodAnchorSource.anchor(scan.ironwoodAnchor!), + inputs: const [], + outputs: change, + saplingSpends: saplingSpends, + ironwoodOutput: ironwoodOutput, + seedHex: request.seedHex, + spendParamsPath: provingParameters.spendParamsPath, + outputParamsPath: provingParameters.outputParamsPath, + now: DateTime.now().toUtc(), + allowExperimentalIronwoodBuild: true, + ) + .feeZatoshis; + final total = scan.notes.fold(0, (sum, note) => sum + note.value); + if (total <= fee + saplingMoveChangeZatoshis) { + throw ZcashMoveException( + 'The Sapling funds of this wallet do not cover the $fee zatoshi fee ' + 'of moving them.', + ); + } + final prepared = zcash.prepareNativeSaplingPayment( + network: request.network, + scan: scan, + output: _resolveOutput( + network: request.network, + payment: ZcashSendPayment( + recipient: request.ironwoodChangeAddress, + amountZatoshis: total - fee - saplingMoveChangeZatoshis, + ), + targetHeight: request.targetHeight, + expiryHeight: request.expiryHeight, + ), + saplingChangeAddress: changeAddress, + targetHeight: request.targetHeight, + expiryHeight: request.expiryHeight, + provingParameters: provingParameters, + seedHex: request.seedHex, + reservations: request.pendingSends, + maxNotes: maxSpendNotes, + regtestNu63ActivationHeight: request.regtestNu63ActivationHeight, + now: DateTime.now().toUtc(), + allowExperimentalIronwoodBuild: true, + backend: backend, + ); + request.pendingSends.addPreparedSaplingPayment( + prepared, + createdHeight: chainHeight, + ); + return ZcashPreparedSaplingMove( + prepared: prepared, + sessionGeneration: request.sessionGeneration, + ); + } + + /// The witnesses of [notes] at [anchorHeight], with the Sapling and + /// Ironwood roots there, from a scan of the blocks since the oldest note. + /// + /// The sync does not keep witnesses. The result holds exactly [notes]: + /// the scan must find each one again, unspent, and the block at + /// [anchorHeight] must still be the one the scan ended on. + static Future acquireSaplingWitnesses({ + required String network, + required ZcashLightwalletdSyncClient client, + required ZcashScanExecutor scanExecutor, + required List notes, + required int anchorHeight, + }) async { + final start = notes + .map((note) => note.height) + .reduce((a, b) => a < b ? a : b); + if (start < 1 || notes.any((note) => note.height > anchorHeight)) { + throw StateError('Sapling notes cannot be witnessed at $anchorHeight'); + } + final cursor = zcash.ZcashLightwalletdSyncCursor.fromTreeState( + await client.getTreeState(start - 1), + ); + final served = await client.getBlockRange(start, anchorHeight); + final input = cursor.scanInputFor( + served, + network: network, + includeSaplingWitnesses: true, + includeOrchardWitnesses: true, + watchedNullifiers: zcash.ZcashWatchedNullifiers.forPool('sapling', [ + for (final note in notes) note.nullifier!, + ]), + ); + // Checks that the blocks continue the tree state they start from and end + // on the block of the tree state at the anchor. + final anchorState = await client.getTreeState(anchorHeight); + cursor.advance(scanned: served, treeState: anchorState); + final scanned = await scanExecutor.scan(input); + + final range = scanned.scannedHeightRange; + final saplingAnchor = scanned.saplingAnchor; + if (range == null || + range.start != start || + range.end != anchorHeight || + scanned.scannedBlocks != served.blocks.length || + saplingAnchor == null) { + throw StateError( + 'The Sapling witness scan did not cover blocks $start to ' + '$anchorHeight', + ); + } + final found = { + for (final note in scanned.notes) + if (note.pool == 'sapling') '${note.tx}:${note.output}': note, + }; + final witnessed = []; + for (final note in notes) { + final again = found['${note.tx}:${note.output}']; + if (again == null || + again.witness == null || + !zcash.ZcashSpendNoteIdentity.fromScannedNote(note).matches(again)) { + throw StateError( + 'The Sapling witness scan did not find a note of this wallet again', + ); + } + witnessed.add(again); + } + final nullifiers = {for (final note in notes) note.nullifier}; + if (scanned.spends.any( + (spend) => + spend.pool == 'sapling' && nullifiers.contains(spend.nullifier), + )) { + throw StateError('A Sapling note of this wallet is already spent'); + } + // The roots of the scan have to be those of the node's trees at the + // anchor: blocks that are short of an output give a root no node knows. + final saplingFrontier = anchorState.sapling?.finalState ?? ''; + final ironwoodFrontier = anchorState.ironwood?.finalState ?? ''; + if (saplingFrontier.isEmpty) { + throw StateError('The node reports no Sapling tree at $anchorHeight'); + } + final atAnchor = await scanExecutor.scan( + zcash.ScanInputEnvelope( + network: network, + includeSaplingWitnesses: true, + includeOrchardWitnesses: true, + priorSaplingFrontier: saplingFrontier, + priorIronwoodFrontier: ironwoodFrontier.isEmpty + ? null + : ironwoodFrontier, + blocks: const [], + ), + ); + // A scan reports no Ironwood root for a tree without notes. + final scannedIronwood = scanned.ironwoodAnchor ?? ''; + if (atAnchor.scannedBlocks != 0 || + atAnchor.saplingAnchor != saplingAnchor || + (ironwoodFrontier.isEmpty + ? scannedIronwood.isNotEmpty + : atAnchor.ironwoodAnchor != scannedIronwood)) { + throw StateError( + 'The Sapling witness scan ended on roots that are not those of the ' + "node's trees at $anchorHeight", + ); + } + final ironwoodAnchor = ironwoodFrontier.isEmpty + ? zcash.orchardFamilyEmptyTreeRootHex + : scannedIronwood; + + final repeated = await client.getBlockRange(anchorHeight, anchorHeight); + final repeatedState = await client.getTreeState(anchorHeight); + final stateHash = zcash.blockHashFromDisplayedHash(anchorState.hash); + if (served.lastBlockHash == null || + repeated.lastBlockHash != served.lastBlockHash || + stateHash == null || + zcash.blockHashFromDisplayedHash(repeatedState.hash) != stateHash || + repeatedState.sapling?.finalState != anchorState.sapling?.finalState || + repeatedState.ironwood?.finalState != + anchorState.ironwood?.finalState) { + throw StateError( + 'The chain changed while the Sapling witnesses were fetched', + ); + } + return zcash.ZcashScanResult( + scannedBlocks: scanned.scannedBlocks, + discoveredNotes: witnessed.length, + totalValue: witnessed.fold(0, (sum, note) => sum + note.value), + notes: witnessed, + scannedHeightRange: range, + saplingAnchor: saplingAnchor, + ironwoodAnchor: ironwoodAnchor, + ); + } + + /// Moves the wallet's transparent coins, the largest [maxSpendNotes] of + /// them, to its Ironwood receiver. + Future _prepareTransparentMove( + ZcashSendPreparationRequest request, + ) async { + final chainHeight = request.targetHeight - 1; + final outputs = movableTransparentCoins( + request.state, + request.unavailableOutpoints, + chainHeight, + ); + if (outputs.length > maxSpendNotes) { + outputs.removeRange(maxSpendNotes, outputs.length); + } + if (outputs.isEmpty) { + throw const ZcashMoveException( + 'This wallet has no transparent funds that are free to move.', + ); + } + // The transaction names a root of the Ironwood tree. As for a send, it + // is the one some blocks below the tip. + final frontier = (await request.syncClient.getTreeState( + chainHeight - anchorDepth, + )).ironwood?.finalState; + final zcash.ShieldingPreparedSend prepared; + try { + prepared = transparentMoveBuilder( + request: request, + coins: zcash.TransparentCoinSet.fromUtxos( + utxos: outputs.map((output) => output.utxo), + chainHeight: chainHeight, + coinbaseOutpoints: { + for (final output in outputs) + if (output.isCoinbase) '${output.txid}:${output.outputIndex}', + }, + ), + ironwoodFrontier: (frontier ?? '').isEmpty ? null : frontier, + ); + } on zcash.TransparentSelectionException catch (e) { + if (e.refusal == zcash.TransparentSelectionRefusal.insufficientFunds) { + throw const ZcashMoveException( + 'The transparent funds of this wallet do not cover the fee of ' + 'moving them.', + ); + } + rethrow; + } + return ZcashPreparedTransparentMove( + prepared: prepared, + // The builder sets the expiry itself, to its default. + expiryHeight: request.targetHeight + 40, + sessionGeneration: request.sessionGeneration, + encodedRecipient: request.ironwoodChangeAddress, + ); + } + + /// The native [ZcashTransparentMoveBuilder]: signs with the keys of the + /// receivers the coins were found on, derived from the request's seed. + static zcash.ShieldingPreparedSend buildNativeTransparentMove({ + required ZcashSendPreparationRequest request, + required zcash.TransparentCoinSet coins, + required String? ironwoodFrontier, + }) { + final receivers = { + for (final receiver in request.state.transparent.receivers) + receiver.address: receiver, + }; + final keys = {}; + try { + return zcash.prepareNativeShieldingSend( + network: request.network, + destination: zcash.ShieldingDestination.ironwood, + coins: coins, + toAddress: request.ironwoodChangeAddress, + targetHeight: request.targetHeight, + signingKeyForCoin: (coin) { + final receiver = receivers[coin.utxo.address]; + if (receiver == null) { + throw StateError('A transparent coin is on no known receiver'); + } + final key = keys.putIfAbsent(receiver.address, () { + final derived = zcash.deriveNativeTransparentSpendingKey( + seedHex: request.seedHex, + network: request.network, + childIndex: receiver.childIndex, + scope: + receiver.scope == zcash.ZcashTransparentReceiverScope.external + ? zcash.ZcashTransparentKeyScope.external + : zcash.ZcashTransparentKeyScope.internal, + ); + if (derived.address != receiver.address) { + derived.destroy(); + throw StateError( + 'The derived transparent key does not own the coin', + ); + } + return derived; + }); + return key.secretKeyHex; + }, + ironwoodAnchor: ironwoodFrontier == null + ? const zcash.IronwoodAnchorSource.anchor( + zcash.orchardFamilyEmptyTreeRootHex, + ) + : zcash.IronwoodAnchorSource.tree(ironwoodFrontier), + seedHex: request.seedHex, + regtestNu63ActivationHeight: request.regtestNu63ActivationHeight, + now: DateTime.now().toUtc(), + allowExperimentalBuild: true, + ); + } finally { + for (final key in keys.values) { + key.destroy(); + } + } + } } final class _StackSpendMaterialSource diff --git a/lib/wallets/wallet/intermediate/zcash_wallet_state_controller.dart b/lib/wallets/wallet/intermediate/zcash_wallet_state_controller.dart index 043054e34..7db3c1166 100644 --- a/lib/wallets/wallet/intermediate/zcash_wallet_state_controller.dart +++ b/lib/wallets/wallet/intermediate/zcash_wallet_state_controller.dart @@ -179,6 +179,7 @@ class ZcashWalletSnapshot { this.blockTimes = const {}, this.spendableNotes = const {}, this.unanchoredNotes = const {}, + this.saplingNotes = const {}, }); /// The [spendableNotes] of [state]. @@ -214,6 +215,21 @@ class ZcashWalletSnapshot { /// chain has grown past them. final Set unanchoredNotes; + /// The value of each unspent Sapling note, by nullifier. A send cannot + /// spend them. A move to Ironwood can, and while it is not mined its + /// record names them. + final Map saplingNotes; + + /// The [saplingNotes] of [state]. + static Map saplingNotesOf(zcash.ZcashWalletSyncState state) { + final spent = {for (final spend in state.sapling.spends) spend.nullifier}; + return { + for (final note in state.sapling.notes) + if (note.nullifier != null && !spent.contains(note.nullifier)) + note.nullifier!: note.value, + }; + } + /// The [unanchoredNotes] of [state] at [chainHeight]. static Set unanchoredNotesOf( zcash.ZcashWalletSyncState state, @@ -273,14 +289,23 @@ class ZcashStackStateMapper { snapshot.chainHeight, ); for (final record in unmined) { + // A move from Sapling spends notes that were never spendable: what it + // moves goes from the rest of the total to pending. + final fromSapling = + record.sourcePool == zcash.ShieldedPendingSourcePool.sapling; + final source = fromSapling + ? snapshot.saplingNotes + : snapshot.spendableNotes; 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; + final value = source[nullifier] ?? 0; notes += value; - if (!snapshot.unanchoredNotes.contains(nullifier)) held += value; + if (!fromSapling && !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; @@ -293,7 +318,7 @@ class ZcashStackStateMapper { .fold(0, (sum, output) => sum + output.amountZatoshis); total -= leaving; spendable -= held; - pendingChange += held - leaving; + pendingChange += (fromSapling ? notes : held) - leaving; } return Balance( total: amount(total), @@ -330,11 +355,17 @@ class ZcashStackStateMapper { /// /// [timestamps] is keyed by txid. Shielded history carries no block time, /// and a send that is not mined has none: the caller supplies both. + /// + /// A send that pays [ownAddresses] only, as a move of funds to Ironwood + /// does, is a transfer to self. [moveFees] has the fee of each move of + /// transparent coins, by txid: the wallet has no other record of them. List transactions( zcash.ZcashTransactionHistory history, { zcash.IronwoodPendingSendState? pendingSends, Map timestamps = const {}, int? chainHeight, + Set ownAddresses = const {}, + Map moveFees = const {}, }) { final pendingByTxid = { for (final record @@ -347,25 +378,45 @@ class ZcashStackStateMapper { entry, pendingByTxid[entry.txid.toLowerCase()], timestamps[entry.txid], + ownAddresses, + moveFees[entry.txid.toLowerCase()], ), if (chainHeight != null) for (final record in unminedSends(history, pendingSends, chainHeight)) - _unminedSend(record, timestamps[record.txid]), + _unminedSend(record, timestamps[record.txid], ownAddresses), ]; } + static bool _paysOnly( + zcash.IronwoodPendingSendRecord record, + Set addresses, + ) => record.paymentOutputs.every( + (output) => addresses.contains(output.encodedRecipient), + ); + TransactionV2 _transaction( zcash.ZcashHistoryEntry entry, zcash.IronwoodPendingSendRecord? pending, int? timestamp, + Set ownAddresses, + int? moveFee, ) { // 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; + // own sends and moves record theirs. When none does, the amount of a + // send includes its fee. + final feeZatoshis = entry.feeZatoshis ?? pending?.feeZatoshis ?? moveFee; final externalZatoshis = pending == null ? entry.spentZatoshis - entry.receivedZatoshis - (feeZatoshis ?? 0) + : _paysOnly(pending, ownAddresses) + ? 0 : _paymentTotal(pending); + // All that was spent came back, less a fee that is known. + final toSelf = + entry.spentZatoshis > 0 && + entry.unvaluedSpends == 0 && + entry.receivedZatoshis > 0 && + feeZatoshis != null && + externalZatoshis <= 0; return TransactionV2( walletId: walletId, blockHash: entry.blockHash, @@ -381,11 +432,16 @@ class ZcashStackStateMapper { outputs: [ if (entry.isOutgoing && externalZatoshis > 0) _output(externalZatoshis, walletOwns: false), - if (entry.receivedZatoshis > 0) + // What the wallet sent to itself, not the change with it. + if (toSelf && pending != null) + _output(_paymentTotal(pending), walletOwns: true) + else if (entry.receivedZatoshis > 0) _output(entry.receivedZatoshis, walletOwns: true), ], version: unknownVersionSentinel, - type: entry.isOutgoing + type: toSelf + ? TransactionType.sentToSelf + : entry.isOutgoing ? TransactionType.outgoing : TransactionType.incoming, subType: TransactionSubType.none, @@ -401,8 +457,10 @@ class ZcashStackStateMapper { TransactionV2 _unminedSend( zcash.IronwoodPendingSendRecord record, int? timestamp, + Set ownAddresses, ) { final paymentZatoshis = _paymentTotal(record); + final toSelf = _paysOnly(record, ownAddresses); return TransactionV2( walletId: walletId, blockHash: null, @@ -411,9 +469,9 @@ class ZcashStackStateMapper { timestamp: timestamp ?? unknownTimestampSentinel, height: null, inputs: [_input(paymentZatoshis + record.feeZatoshis)], - outputs: [_output(paymentZatoshis, walletOwns: false)], + outputs: [_output(paymentZatoshis, walletOwns: toSelf)], version: unknownVersionSentinel, - type: TransactionType.outgoing, + type: toSelf ? TransactionType.sentToSelf : TransactionType.outgoing, subType: TransactionSubType.none, otherData: _otherData( feeZatoshis: record.feeZatoshis, @@ -674,6 +732,7 @@ class ZcashWalletStateController { blockTimes: _blockTimes.toMap(), spendableNotes: spendableNotes, unanchoredNotes: unanchoredNotes, + saplingNotes: ZcashWalletSnapshot.saplingNotesOf(_state), ); /// See [ZcashWalletSnapshot.spendableNotes]. diff --git a/scripts/zcash_e2e_test.sh b/scripts/zcash_e2e_test.sh index 5d2bbc22a..38fcd2e2e 100755 --- a/scripts/zcash_e2e_test.sh +++ b/scripts/zcash_e2e_test.sh @@ -10,7 +10,8 @@ set -euo pipefail # ZEBRAD_BIN and LIGHTWALLETD_BIN, or from PATH. The suite is tested with # zebrad 7.0.0 and lightwalletd 0.6.1. # -# One payment needs the Sapling proving parameters. The wallets download them +# A payment to a Sapling address and a move of Sapling funds need the Sapling +# proving parameters. The wallets download them # unless SAPLING_PARAMS_DIR names a directory that holds sapling-spend.params # and sapling-output.params. # diff --git a/test/wallets/zcash_history_mapping_test.dart b/test/wallets/zcash_history_mapping_test.dart index 1c376c12b..fddd3706a 100644 --- a/test/wallets/zcash_history_mapping_test.dart +++ b/test/wallets/zcash_history_mapping_test.dart @@ -107,6 +107,7 @@ ZcashWalletSnapshot _snapshot({ zcash.IronwoodPendingSendState _pending({ String broadcastState = 'acknowledged', int expiryHeight = 200, + String sourcePool = 'ironwood', }) => zcash.IronwoodPendingSendState.fromJson({ 'pending_send_state_version': 2, 'records': [ @@ -115,7 +116,7 @@ zcash.IronwoodPendingSendState _pending({ 'transaction': '00', 'txid': _sendTxid, 'selected_nullifiers': ['11' * 32], - 'source_pool': 'ironwood', + 'source_pool': sourcePool, 'recipient': 'uregtest1destination', 'actual_destination_pool': 'ironwood', 'amount_zatoshis': 1000000, @@ -225,6 +226,67 @@ void main() { }); }); + test('a send that pays only the wallet\'s own address is a transfer to ' + 'self of the amount it paid', () { + BigInt received(TransactionV2 tx) => + tx.getAmountReceivedInThisWallet(fractionDigits: 8).raw; + + final unmined = _mapper + .transactions( + _history(), + pendingSends: _pending(), + chainHeight: 131, + ownAddresses: {'uregtest1destination'}, + ) + .last; + expect(unmined.txid, _sendTxid); + expect(unmined.type, TransactionType.sentToSelf); + expect(received(unmined), BigInt.from(1000000)); + expect(unmined.getFee(fractionDigits: 8).raw, BigInt.from(20000)); + + // Mined, the wallet also receives the change: the amount stays the + // payment. + final mined = _mapper + .transactions( + _history(sendMinedAt: 131), + pendingSends: _pending(), + chainHeight: 131, + ownAddresses: {'uregtest1destination'}, + ) + .first; + expect(mined.txid, _sendTxid); + expect(mined.type, TransactionType.sentToSelf); + expect(received(mined), BigInt.from(1000000)); + expect(mined.getFee(fractionDigits: 8).raw, BigInt.from(20000)); + + // To another address it is a send. + final other = _mapper + .transactions( + _history(sendMinedAt: 131), + pendingSends: _pending(), + chainHeight: 131, + ownAddresses: {'uregtest1other'}, + ) + .first; + expect(other.type, TransactionType.outgoing); + expect(_sent(other), BigInt.from(1000000)); + + // A move of transparent coins has no pending record, and the mapper has + // its fee from the wallet's record of it. This entry stands in for one: + // it spends 10000000 and receives 8980000, so with a fee of the + // difference all that was spent came back. The regtest suite maps a + // real move. + final move = _mapper + .transactions( + _history(sendMinedAt: 131), + moveFees: {_sendTxid: 1020000}, + ) + .first; + expect(move.type, TransactionType.sentToSelf); + expect(received(move), BigInt.from(8980000)); + expect(move.getFee(fractionDigits: 8).raw, BigInt.from(1020000)); + }); + test('a send without the wallet\'s record includes its fee in the ' 'amount', () { final send = _mapper.transactions(_history(sendMinedAt: 131)).first; @@ -385,6 +447,63 @@ void main() { expect(balance.blockedTotal.raw, BigInt.zero); }); + test('an unmined move from Sapling costs its fee, and what it moves is ' + 'pending', () { + // The wallet holds the Ironwood note of ten million and a Sapling + // note of two million, which a move to its own address spends. + final state = _state(); + state.sapling.apply( + zcash.ZcashScanResult( + scannedBlocks: 12, + discoveredNotes: 1, + totalValue: 2000000, + scannedHeightRange: const zcash.CompactBlockScanRange( + start: 120, + end: 131, + ), + notes: [ + zcash.ZcashScannedNote( + height: 120, + tx: _receiveTxid, + output: 0, + value: 2000000, + pool: 'sapling', + nullifier: _sourceNullifier, + commitmentPosition: 0, + blockHash: _blockHash, + ), + ], + ), + accountFingerprint: 'account-a', + ); + final snapshot = ZcashWalletSnapshot( + chainHeight: 131, + balance: state.balance(), + history: state.history(), + spendableNotes: ZcashWalletSnapshot.spendableNotesOf(state), + unanchoredNotes: ZcashWalletSnapshot.unanchoredNotesOf(state, 131), + saplingNotes: ZcashWalletSnapshot.saplingNotesOf(state), + ); + expect(snapshot.saplingNotes, {_sourceNullifier: 2000000}); + + final before = _mapper.balance(snapshot); + expect(before.total.raw, BigInt.from(12000000)); + expect(before.spendable.raw, BigInt.from(10000000)); + expect(before.blockedTotal.raw, BigInt.from(2000000)); + + // The record names the Sapling note, whose nullifier an Ironwood note + // of the wallet happens to share: only the Sapling one is its source. + final moving = _mapper.balance( + snapshot, + pendingSends: _pending(sourcePool: 'sapling'), + ownAddresses: {'uregtest1destination'}, + ); + expect(moving.total.raw, BigInt.from(11980000)); + expect(moving.spendable.raw, BigInt.from(10000000)); + expect(moving.pendingSpendable.raw, BigInt.from(1980000)); + expect(moving.blockedTotal.raw, BigInt.zero); + }); + test('keeps what an unmined send pays to the wallet itself', () { final snapshot = _snapshot(); diff --git a/test/wallets/zcash_pending_send_store_test.dart b/test/wallets/zcash_pending_send_store_test.dart index 4e2fd6642..d99ab2334 100644 --- a/test/wallets/zcash_pending_send_store_test.dart +++ b/test/wallets/zcash_pending_send_store_test.dart @@ -78,4 +78,57 @@ void main() { expect((await store().load()).records, isEmpty); expect(File('${directory.path}/wallet.pending.tmp').existsSync(), isFalse); }); + + test('transparent moves are kept with the pending sends, and saving one ' + 'keeps the other', () async { + final directory = await Directory.systemTemp.createTemp( + 'zcash_pending_store_', + ); + addTearDown(() => directory.delete(recursive: true)); + final secrets = MemorySecrets(); + final path = '${directory.path}/wallet.pending'; + ZcashEncryptedPendingSendStore store() => ZcashEncryptedPendingSendStore( + path: path, + walletId: 'wallet-id', + network: 'main', + accountFingerprint: 'account-a', + secureStorage: secrets, + ); + final outpoint = '${'51' * 32}:1'; + + // Nothing was saved yet. + expect(await store().loadTransparentMoves(), isEmpty); + await store().updateTransparentMoves( + (moves) => moves['77' * 32] = ZcashTransparentMoveRecord( + feeZatoshis: 15000, + expiryHeight: 83, + outpoints: {outpoint}, + ), + ); + expect((await store().load()).records, isEmpty); + expect(await File(path).readAsString(), isNot(contains('51' * 32))); + + // A save of the pending sends, as a refresh makes, keeps the moves. + await store().save(zcash.IronwoodPendingSendState()); + var moves = await store().loadTransparentMoves(); + expect(moves.keys, ['77' * 32]); + expect(moves.values.single.feeZatoshis, 15000); + expect(moves.values.single.expiryHeight, 83); + expect(moves.values.single.outpoints, {outpoint}); + + // Updates that start together each see what the other stored. + await Future.wait([ + for (final txid in ['88' * 32, '99' * 32]) + store().updateTransparentMoves( + (moves) => moves[txid] = const ZcashTransparentMoveRecord( + feeZatoshis: 20000, + expiryHeight: 90, + ), + ), + ]); + await store().updateTransparentMoves((moves) => moves.remove('77' * 32)); + moves = await store().loadTransparentMoves(); + expect(moves.keys.toSet(), {'88' * 32, '99' * 32}); + expect(moves.values.map((move) => move.outpoints), everyElement(isEmpty)); + }); } diff --git a/test/wallets/zcash_wallet_send_test.dart b/test/wallets/zcash_wallet_send_test.dart index 984d94fed..a939359c4 100644 --- a/test/wallets/zcash_wallet_send_test.dart +++ b/test/wallets/zcash_wallet_send_test.dart @@ -1,9 +1,11 @@ import 'dart:async'; import 'dart:convert'; import 'dart:io'; +import 'dart:math'; import 'dart:typed_data'; import 'package:crypto/crypto.dart'; +import 'package:fixnum/fixnum.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:path/path.dart' as path; import 'package:stackwallet/db/isar/main_db.dart'; @@ -459,6 +461,245 @@ final class FixtureParameterSource implements zcash.SaplingParameterSource { Stream.value(bytes[artifact.fileName]!); } +/// A chain of empty blocks, with a tree state for each. +final class MoveChainClient extends SendClient { + MoveChainClient() : super(chainName: 'test'); + + /// A height whose block differs each time it is served. + int? unstableHeight; + + /// A height whose trees differ each time they are served. + int? unstableTreeHeight; + + /// Whether the Ironwood tree has notes. + bool ironwoodNotes = true; + int _served = 0; + int _trees = 0; + final List<(int, int)> ranges = []; + + static String hashOf(int height, [int salt = 0]) => + (height * 256 + salt).toRadixString(16).padLeft(64, '0'); + + static List _bytes(String hex) => [ + for (var i = 0; i < hex.length; i += 2) + int.parse(hex.substring(i, i + 2), radix: 16), + ]; + + @override + Future getBlockRange( + int start, + int end, + ) async { + ranges.add((start, end)); + final salt = _served++; + return zcash.ZcashLightwalletdScanSource([ + for (var height = start; height <= end; height++) + zcash.CompactBlock() + ..height = Int64(height) + ..time = 1700000000 + height + ..hash = _bytes( + hashOf(height, height == unstableHeight && salt > 0 ? 1 : 0), + ) + ..prevHash = _bytes(hashOf(height - 1)), + ]); + } + + @override + Future getTreeState(int height) async { + final version = height == unstableTreeHeight ? '-${_trees++}' : ''; + return zcash.TreeState( + hash: zcash.reverseTxidByteOrder(hashOf(height)), + height: height, + time: 1, + sapling: zcash.ShieldedTree(finalState: 'sapling-tree-$height$version'), + ironwood: ironwoodNotes + ? zcash.ShieldedTree(finalState: 'ironwood-tree-$height') + : null, + ); + } +} + +/// Answers a witness scan with [notes] and [spends], and a scan of no blocks +/// with the roots of the trees it starts from. +final class WitnessScanExecutor implements ZcashScanExecutor { + WitnessScanExecutor({ + required this.notes, + this.spends = const [], + this.ironwoodAnchor = _ironwoodRoot, + this.treeSaplingRoot = _saplingRoot, + }); + + static const _saplingRoot = + 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; + static const _ironwoodRoot = + 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'; + + final List notes; + final List spends; + + /// The Ironwood root the scan of the blocks ends on. + final String? ironwoodAnchor; + + /// The root of the node's Sapling tree at the anchor. + final String treeSaplingRoot; + final List envelopes = []; + + @override + Future scan(zcash.ScanInputEnvelope envelope) async { + envelopes.add(envelope); + if (envelope.blocks.isEmpty) { + return zcash.ZcashScanResult( + scannedBlocks: 0, + discoveredNotes: 0, + totalValue: 0, + notes: const [], + saplingAnchor: treeSaplingRoot, + ironwoodAnchor: envelope.priorIronwoodFrontier == null + ? null + : _ironwoodRoot, + ); + } + return zcash.ZcashScanResult( + scannedBlocks: envelope.blocks.length, + discoveredNotes: notes.length, + totalValue: notes.fold(0, (sum, note) => sum + note.value), + notes: notes, + spends: spends, + scannedHeightRange: envelope.range, + saplingAnchor: _saplingRoot, + ironwoodAnchor: ironwoodAnchor, + ); + } +} + +/// Prices and builds a transaction that spends Sapling notes as ZIP 317 +/// does: 5000 zatoshis for each note, for two at least, and 10000 for the +/// Ironwood output. +final class SaplingMoveBackend implements zcash.IronwoodPaymentBackend { + final List builds = []; + + static int _fee(zcash.IronwoodPaymentNativeRequest request) => + 5000 * max(request.saplingSpends.length, 2) + 10000; + + static int _input(zcash.IronwoodPaymentNativeRequest request) => + request.saplingSpends.fold(0, (sum, spend) => sum + spend.valueZatoshis); + + static int _change(zcash.IronwoodPaymentNativeRequest request) => + request.outputs.fold(0, (sum, output) => sum + output.valueZatoshis); + + @override + zcash.IronwoodFeeQuote quote(zcash.IronwoodPaymentNativeRequest request) => + zcash.IronwoodFeeQuote( + network: zcash.ZcashAddressNetwork.regtest, + feeZatoshis: _fee(request), + feeRule: 'zip317', + consensusBranchId: 'nu6.3', + totalInputZatoshis: _input(request), + nonIronwoodOutputZatoshis: _change(request), + maxIronwoodOutputZatoshis: + _input(request) - _change(request) - _fee(request), + ironwoodSpends: 0, + orchardSpends: 0, + saplingSpends: request.saplingSpends.length, + transparentInputs: 0, + ); + + @override + zcash.IronwoodBuildResult build(zcash.IronwoodPaymentNativeRequest request) { + builds.add(request); + return zcash.IronwoodBuildResult( + network: zcash.ZcashAddressNetwork.regtest, + transactionHex: 'ab' * 20, + txid: 'cd' * 32, + version: 'v6', + expiryHeight: request.expiryHeight!, + feeZatoshis: _fee(request), + feeRule: 'zip317', + proofValidity: 'real', + ironwoodAnchor: request.anchorHex, + ironwoodAnchorSource: 'anchor', + vin: 0, + vout: 0, + saplingSpends: request.saplingSpends.length, + // The builder pads the Sapling outputs to two. + saplingOutputs: 2, + ironwoodActions: 2, + totalInputZatoshis: _input(request), + saplingInputZatoshis: _input(request), + nonIronwoodOutputZatoshis: _change(request), + ironwoodOutputZatoshis: request.ironwoodOutput.valueZatoshis!, + rng: 'system', + ); + } +} + +/// A send service whose prepared transaction is a move of one transparent +/// coin, and whose broadcast is the production one. +final class TransparentMoveSendService implements ZcashWalletSendService { + static const coinTxid = + '5151515151515151515151515151515151515151515151515151515151515151'; + + final List requests = []; + + @override + Future prepare( + ZcashSendPreparationRequest request, + ) async { + requests.add(request); + return ZcashPreparedTransparentMove( + prepared: zcash.ShieldingPreparedSend( + destination: zcash.ShieldingDestination.ironwood, + selection: const zcash.TransparentInputSelection( + coins: [ + zcash.TrackedTransparentCoin( + utxo: zcash.AddressUtxo( + address: 't1fixture', + txid: coinTxid, + outputIndex: 1, + script: '51', + satoshis: 50000, + height: 40, + ), + isCoinbase: false, + status: zcash.TransparentCoinStatus.spendable, + spendableAtHeight: 40, + ), + ], + amountZatoshis: 40000, + feeZatoshis: 10000, + changeZatoshis: 0, + spendsCoinbase: false, + ), + transactionHex: '00ff20', + txid: '77' * 32, + feeZatoshis: 10000, + shieldedZatoshis: 40000, + ), + expiryHeight: request.targetHeight + 40, + sessionGeneration: request.sessionGeneration, + encodedRecipient: request.ironwoodChangeAddress, + ); + } + + @override + Future broadcast({ + required ZcashPreparedWalletSend prepared, + required zcash.IronwoodPendingSendState pendingSends, + required int chainHeight, + required Future Function() persist, + required Future Function( + String transactionHex, + ) + submit, + }) => const ZcashProductionWalletSendService().broadcast( + prepared: prepared, + pendingSends: pendingSends, + chainHeight: chainHeight, + persist: persist, + submit: submit, + ); +} + /// A node that refuses every transaction while [refuse] is set, and gives /// no answer to one while [lose] is. final class RefusingSendClient extends SendClient { @@ -1628,6 +1869,657 @@ void main() { await restored.exit(); }); } + + group('moving funds to Ironwood', () { + const phrase = + 'abandon abandon abandon abandon abandon abandon abandon abandon ' + 'abandon abandon abandon about'; + late zcash.UnifiedAddressSet address; + late String seedHex; + + late zcash.SaplingProvingParameters parameters; + + setUp(() async { + final spend = [1, 2, 3]; + final output = [4, 5, 6]; + final manifest = zcash.SaplingParameterManifest( + version: 'fixture-v1', + spend: zcash.SaplingParameterArtifact( + fileName: 'spend.params', + expectedBytes: spend.length, + sha256Hex: sha256.convert(spend).toString(), + ), + output: zcash.SaplingParameterArtifact( + fileName: 'output.params', + expectedBytes: output.length, + sha256Hex: sha256.convert(output).toString(), + ), + ); + parameters = + await zcash.SaplingProvingParameterCache( + cacheRoot: Directory(path.join(root.path, 'move_parameters')), + manifest: manifest, + ).resolve( + source: FixtureParameterSource({ + manifest.spend.fileName: spend, + manifest.output.fileName: output, + }), + ); + seedHex = zcash.nativeMnemonicToSeed(phrase).seedHex; + address = await zcash.deriveAddress( + seedHex: seedHex, + network: zcash.ZcashNetwork.regtest, + ); + }); + + ZcashSendPreparationRequest request({ + required zcash.ZcashWalletSyncState state, + required zcash.IronwoodPendingSendState pending, + required ZcashMovablePool pool, + SendClient? client, + ZcashScanExecutor? scanExecutor, + Set unavailableOutpoints = const {}, + }) => ZcashSendPreparationRequest( + network: zcash.ZcashNetwork.regtest, + sessionGeneration: 1, + state: state, + pendingSends: pending, + syncClient: client ?? MoveChainClient(), + scanExecutor: scanExecutor ?? UnusedScanExecutor(), + seedHex: seedHex, + ironwoodChangeAddress: address.ua, + payments: const [], + // The tip is block 45, so a move anchors to block 42. + targetHeight: 43 + zcashAnchorDepth, + expiryHeight: 83 + zcashAnchorDepth, + resolveSaplingProvingParameters: () async => parameters, + regtestNu63ActivationHeight: 40, + moveFrom: pool, + saplingChangeAddress: address.saplingAddress, + unavailableOutpoints: unavailableOutpoints, + ); + + test('a move from Sapling witnesses the notes with a scan since the ' + 'oldest one and moves all but the change zatoshi', () async { + final state = _saplingFundedState(); + final pending = zcash.IronwoodPendingSendState(); + final client = MoveChainClient(); + final scans = WitnessScanExecutor( + notes: [for (final note in state.sapling.notes) _witnessed(note)], + ); + final backend = SaplingMoveBackend(); + final service = ZcashProductionWalletSendService( + ironwoodPaymentBackend: backend, + ); + + final prepared = await service.prepare( + request( + state: state, + pending: pending, + pool: ZcashMovablePool.sapling, + client: client, + scanExecutor: scans, + ), + ); + + // The blocks from the oldest note to the anchor, then the anchor block + // again to see that it did not change. + expect(client.ranges, [(40, 42), (42, 42)]); + final envelope = scans.envelopes.first; + expect(envelope.includeSaplingWitnesses, isTrue); + expect(envelope.range!.start, 40); + expect(envelope.range!.end, 42); + // Then the roots of the node's trees at the anchor, to compare. + expect(scans.envelopes, hasLength(2)); + expect(scans.envelopes.last.blocks, isEmpty); + expect(scans.envelopes.last.priorSaplingFrontier, 'sapling-tree-42'); + expect(scans.envelopes.last.priorIronwoodFrontier, 'ironwood-tree-42'); + + // Two notes of 60000 and 30000 pay a 20000 fee and leave one zatoshi. + // The note of 5000 would cost what it holds and stays. + expect(prepared, isA()); + expect(prepared.encodedRecipient, address.ua); + expect(prepared.actualOutputPool, zcash.ProposalOutputPool.ironwood); + expect(prepared.feeZatoshis, 20000); + expect(prepared.amountZatoshis, 69999); + expect( + prepared.changeZatoshis, + ZcashProductionWalletSendService.saplingMoveChangeZatoshis, + ); + final build = backend.builds.single; + expect( + build.saplingSpends.map((spend) => spend.valueZatoshis), + unorderedEquals([60000, 30000]), + ); + expect(build.ironwoodSpends, isEmpty); + expect(build.anchorHex, 'bb' * 32); + expect(build.saplingSpends.first.anchorHex, 'aa' * 32); + expect(build.outputs.single.address, address.saplingAddress); + expect(build.outputs.single.valueZatoshis, 1); + expect(build.ironwoodOutput.valueZatoshis, 69999); + + // The notes are held by the transaction. + final record = pending.records.single; + expect(record.sourcePool, zcash.ShieldedPendingSourcePool.sapling); + expect(record.selectedNullifiers, { + for (final note in state.sapling.notes) + if (note.value > 5000) note.nullifier!, + }); + // A transaction that was prepared and not submitted holds its notes + // against another preparation, and is not counted as holding them + // when the funds are shown: the next preparation releases it. + expect( + ZcashProductionWalletSendService.movableSaplingNotes( + state, + pending, + 45, + holdPrepared: false, + ).map((note) => note.value), + [60000, 30000], + ); + expect( + ZcashProductionWalletSendService.movableSaplingNotes( + state, + pending, + 45, + ), + isEmpty, + ); + // A note above the anchor of a move is not offered: with the tip at + // block 43 the anchor is block 40, and the note of 30000 is in 41. + expect( + ZcashProductionWalletSendService.movableSaplingNotes( + state, + null, + 43, + ).map((note) => note.value), + [60000], + ); + await expectLater( + service.prepare( + request( + state: state, + pending: pending, + pool: ZcashMovablePool.sapling, + client: client, + scanExecutor: scans, + ), + ), + throwsA(isA()), + ); + }); + + test('a move from Sapling is refused when the scan does not witness a ' + 'note, finds it spent, or the chain changes', () async { + final state = _saplingFundedState(); + final notes = [ + for (final note in state.sapling.notes) + if (note.value > 5000) note, + ]; + Matcher refuses(String reason) => throwsA( + isA().having((e) => e.message, 'message', contains(reason)), + ); + Future acquire( + WitnessScanExecutor scans, { + MoveChainClient? client, + }) => ZcashProductionWalletSendService.acquireSaplingWitnesses( + network: 'regtest', + client: client ?? MoveChainClient(), + scanExecutor: scans, + notes: notes, + anchorHeight: 42, + ); + final witnessed = [for (final note in notes) _witnessed(note)]; + + final complete = await acquire(WitnessScanExecutor(notes: witnessed)); + expect( + complete.notes.map((note) => note.witness), + everyElement(isNotNull), + ); + expect(complete.saplingAnchor, 'aa' * 32); + + // A note without its witness. + await expectLater( + acquire(WitnessScanExecutor(notes: [witnessed.first, notes.last])), + refuses('did not find a note of this wallet again'), + ); + // A note the scan does not find. + await expectLater( + acquire(WitnessScanExecutor(notes: [witnessed.first])), + refuses('did not find a note of this wallet again'), + ); + // A note of another value at the same place. + await expectLater( + acquire( + WitnessScanExecutor( + notes: [witnessed.first, _witnessed(notes.last, value: 1)], + ), + ), + refuses('did not find a note of this wallet again'), + ); + // A note that a block of the range spends. + await expectLater( + acquire( + WitnessScanExecutor( + notes: witnessed, + spends: [ + zcash.ZcashObservedSpend( + height: 42, + tx: 'ee' * 32, + pool: 'sapling', + nullifier: notes.first.nullifier!, + index: 0, + ), + ], + ), + ), + refuses('already spent'), + ); + // The anchor block is another one when it is fetched again. + await expectLater( + acquire( + WitnessScanExecutor(notes: witnessed), + client: MoveChainClient()..unstableHeight = 42, + ), + refuses('The chain changed'), + ); + // So are the trees at the anchor. + await expectLater( + acquire( + WitnessScanExecutor(notes: witnessed), + client: MoveChainClient()..unstableTreeHeight = 42, + ), + refuses('The chain changed'), + ); + // The scan ends on a Sapling root that is not the node's. + await expectLater( + acquire( + WitnessScanExecutor(notes: witnessed, treeSaplingRoot: 'dd' * 32), + ), + refuses("not those of the node's trees"), + ); + // The scan reports no Ironwood root for a tree the node has notes in. + await expectLater( + acquire(WitnessScanExecutor(notes: witnessed, ironwoodAnchor: null)), + refuses("not those of the node's trees"), + ); + // An Ironwood tree without notes has the root of an empty tree. + final early = await acquire( + WitnessScanExecutor(notes: witnessed, ironwoodAnchor: null), + client: MoveChainClient()..ironwoodNotes = false, + ); + expect(early.ironwoodAnchor, zcash.orchardFamilyEmptyTreeRootHex); + await expectLater( + acquire( + WitnessScanExecutor(notes: witnessed), + client: MoveChainClient()..ironwoodNotes = false, + ), + refuses("not those of the node's trees"), + ); + }); + + test('a move from Sapling refuses notes older than the witness limit ' + 'before it downloads anything', () async { + final client = MoveChainClient(); + await expectLater( + const ZcashProductionWalletSendService(maxSaplingWitnessBlocks: 2) + .prepare( + request( + state: _saplingFundedState(), + pending: zcash.IronwoodPendingSendState(), + pool: ZcashMovablePool.sapling, + client: client, + ), + ), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('more than 2 blocks ago'), + ), + ), + ); + expect(client.ranges, isEmpty); + }); + + test('a move of transparent coins spends the mature coins that no ' + 'submitted move holds', () async { + final state = _transparentFundedState(seedHex); + final free = ZcashProductionWalletSendService.movableTransparentCoins( + state, + const {}, + 42, + ); + // The coinbase output is not mature at height 42, and the coin of 5000 + // would cost what it holds. + expect(free.map((coin) => coin.valueZatoshis), [50000, 30000]); + final held = '${free.first.txid}:${free.first.outputIndex}'; + + zcash.TransparentCoinSet? offered; + String? frontier; + final service = ZcashProductionWalletSendService( + transparentMoveBuilder: + ({required request, required coins, required ironwoodFrontier}) { + offered = coins; + frontier = ironwoodFrontier; + return zcash.ShieldingPreparedSend( + destination: zcash.ShieldingDestination.ironwood, + selection: zcash.TransparentInputSelection( + coins: coins.spendable, + amountZatoshis: coins.spendableZatoshis - 10000, + feeZatoshis: 10000, + changeZatoshis: 0, + spendsCoinbase: false, + ), + transactionHex: '00ff30', + txid: '88' * 32, + feeZatoshis: 10000, + shieldedZatoshis: coins.spendableZatoshis - 10000, + ); + }, + ); + final pending = zcash.IronwoodPendingSendState(); + + final prepared = await service.prepare( + request( + state: state, + pending: pending, + pool: ZcashMovablePool.transparent, + unavailableOutpoints: {held}, + ), + ); + + expect(offered!.spendable.map((coin) => coin.satoshis), [30000]); + expect(frontier, 'ironwood-tree-42'); + expect(prepared, isA()); + expect(prepared.encodedRecipient, address.ua); + expect(prepared.amountZatoshis, 20000); + expect(prepared.feeZatoshis, 10000); + expect(prepared.expiryHeight, 83 + zcashAnchorDepth); + // A transparent move has no pending record. + expect(pending.records, isEmpty); + + // Nothing left to move: refused before a transaction is built. + offered = null; + await expectLater( + service.prepare( + request( + state: state, + pending: pending, + pool: ZcashMovablePool.transparent, + unavailableOutpoints: { + for (final coin in free) '${coin.txid}:${coin.outputIndex}', + }, + ), + ), + throwsA(isA()), + ); + expect(offered, isNull); + + // While the Ironwood tree has no notes there is no tree to pass on. + await service.prepare( + request( + state: state, + pending: pending, + pool: ZcashMovablePool.transparent, + client: MoveChainClient()..ironwoodNotes = false, + ), + ); + expect(frontier, isNull); + }); + + test('funds that could not pay the fee of their move are not offered', () { + int movable(ZcashMovablePool pool, List values, {int max = 50}) => + ZcashProductionWalletSendService.movableZatoshis( + pool, + values, + maxInputs: max, + ); + + // One transparent coin costs 15000 to move, two cost 20000. + expect(movable(ZcashMovablePool.transparent, []), 0); + expect(movable(ZcashMovablePool.transparent, [15000]), 0); + expect(movable(ZcashMovablePool.transparent, [15001]), 15001); + expect(movable(ZcashMovablePool.transparent, [10000, 10000]), 0); + expect(movable(ZcashMovablePool.transparent, [10001, 10000]), 20001); + // Up to two Sapling notes cost 20000, and one zatoshi stays as change. + expect(movable(ZcashMovablePool.sapling, [20001]), 0); + expect(movable(ZcashMovablePool.sapling, [20002]), 20002); + expect(movable(ZcashMovablePool.sapling, [10001, 10000]), 0); + expect(movable(ZcashMovablePool.sapling, [10001, 10001]), 20002); + expect(movable(ZcashMovablePool.sapling, [9000, 9000, 9000]), 27000); + expect(movable(ZcashMovablePool.sapling, [8000, 8000, 8000]), 0); + // The first move decides, and what later moves take is counted. + expect( + movable(ZcashMovablePool.transparent, [20000, 9000, 9000], max: 1), + 38000, + ); + expect( + movable(ZcashMovablePool.transparent, [15000, 9000, 9000], max: 1), + 0, + ); + }); + + test('the wallet prepares a move to its own address and holds the coins ' + 'of a transparent move that may have reached the node', () async { + final client = RefusingSendClient(); + final service = TransparentMoveSendService(); + final wallet = await _wallet(client, service, 'transparent-move'); + final own = (await wallet.getCurrentReceivingAddress())!.value; + const outpoint = '${TransparentMoveSendService.coinTxid}:1'; + + // A move the node refuses holds nothing. + client.refuse = true; + final refused = await wallet.prepareMoveToIronwood( + ZcashMovablePool.transparent, + ); + expect(service.requests.single.moveFrom, ZcashMovablePool.transparent); + expect(service.requests.single.payments, isEmpty); + expect(service.requests.single.saplingChangeAddress, isNull); + expect(refused.recipients!.single.address, own); + expect(refused.recipients!.single.amount.raw, BigInt.from(40000)); + expect(refused.fee!.raw, BigInt.from(10000)); + await expectLater( + wallet.confirmSend(txData: refused), + throwsA(isA()), + ); + client.refuse = false; + // It is no longer the prepared transaction. + await expectLater( + wallet.confirmSend(txData: refused), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('exact prepared transaction artifact'), + ), + ), + ); + + // A submission without an answer may have reached the node: the move + // holds its coins. + client.lose = true; + final lost = await wallet.prepareMoveToIronwood( + ZcashMovablePool.transparent, + ); + expect(service.requests.last.unavailableOutpoints, isEmpty); + await expectLater(wallet.confirmSend(txData: lost), throwsStateError); + // It stays prepared: confirming it again submits it again. + await expectLater( + wallet.confirmSend(txData: lost), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'the connection was lost', + ), + ), + ); + client.lose = false; + final again = await wallet.prepareMoveToIronwood( + ZcashMovablePool.transparent, + ); + expect(service.requests.last.unavailableOutpoints, {outpoint}); + + // A refusal of the same transaction afterwards does not free them: the + // node may refuse what it already has. + client.refuse = true; + await expectLater( + wallet.confirmSend(txData: again), + throwsA(isA()), + ); + client.refuse = false; + final accepted = await wallet.prepareMoveToIronwood( + ZcashMovablePool.transparent, + ); + expect(service.requests.last.unavailableOutpoints, {outpoint}); + + // One that the node takes holds its coins too. + await wallet.confirmSend(txData: accepted); + expect(client.submitted.single, Uint8List.fromList([0, 255, 32])); + await wallet.prepareMoveToIronwood(ZcashMovablePool.transparent); + expect(service.requests.last.unavailableOutpoints, {outpoint}); + await wallet.exit(); + }); + + test('a move from Sapling fetches the Sapling parameters before it ' + 'takes the send lock', () async { + final fetching = Completer(); + final fetched = Completer(); + final service = TransparentMoveSendService(); + final wallet = await _wallet( + SendClient(), + service, + 'sapling-move-parameters-first', + saplingParameterResolver: () { + fetching.complete(); + return fetched.future; + }, + ); + + // A move of transparent coins has no Sapling part: no download. + await wallet.prepareMoveToIronwood(ZcashMovablePool.transparent); + expect(fetching.isCompleted, isFalse); + + final preparing = wallet.prepareMoveToIronwood(ZcashMovablePool.sapling); + await fetching.future; + await wallet.exit().timeout(const Duration(seconds: 1)); + fetched.completeError(StateError('the download failed')); + await expectLater(preparing, throwsStateError); + expect(service.requests, hasLength(1)); + }); + }); +} + +/// Three unspent Sapling notes, of 60000 at height 40 and of 30000 and 5000 +/// at height 41, as a sync stores them: without witnesses. +zcash.ZcashWalletSyncState _saplingFundedState() { + const fingerprint = 'fixture-account'; + final state = zcash.ZcashWalletSyncState.atBirthday( + cursor: zcash.ZcashLightwalletdSyncCursor.origin(height: 1), + network: zcash.ZcashAddressNetwork.regtest, + accountFingerprint: fingerprint, + ); + zcash.ZcashScannedNote note(int height, String tx, int value, int position) => + zcash.ZcashScannedNote( + height: height, + tx: tx * 32, + output: 0, + value: value, + pool: 'sapling', + nullifier: '${tx}00' * 16, + commitmentPosition: position, + recipient: 'zregtestsapling1-wallet-note', + rseed: '11' * 32, + ); + state.sapling.apply( + zcash.ZcashScanResult( + scannedBlocks: 2, + discoveredNotes: 3, + totalValue: 95000, + notes: [ + note(40, 'a1', 60000, 0), + note(41, 'a2', 30000, 1), + note(41, 'a3', 5000, 2), + ], + scannedHeightRange: const zcash.CompactBlockScanRange(start: 40, end: 41), + saplingAnchor: 'cc' * 32, + ), + accountFingerprint: fingerprint, + ); + return state; +} + +/// [note] as a witness scan returns it, or with another [value]. +zcash.ZcashScannedNote _witnessed(zcash.ZcashScannedNote note, {int? value}) => + zcash.ZcashScannedNote( + height: note.height, + tx: note.tx, + output: note.output, + value: value ?? note.value, + pool: note.pool, + nullifier: note.nullifier, + commitmentPosition: note.commitmentPosition, + recipient: note.recipient, + rseed: note.rseed, + witness: '33' * 40, + ); + +/// Transparent coins of 50000, 30000 and 5000 from height 40, and a +/// coinbase output of 70000 from height 41, as of height 42. +zcash.ZcashWalletSyncState _transparentFundedState(String seedHex) { + final account = zcash.deriveNativeAccountMetadata( + seedHex: seedHex, + network: zcash.ZcashNetwork.regtest, + ); + final viewingKeys = zcash.deriveNativeViewingKeys( + seedHex: seedHex, + network: zcash.ZcashNetwork.regtest, + ); + final own = viewingKeys.transparent.defaultExternalAddress!; + zcash.ZcashTransparentOutputObservation coin( + String tx, + int value, { + int height = 40, + bool coinbase = false, + }) => zcash.ZcashTransparentOutputObservation( + address: own, + protocolTxid: tx * 32, + outputIndex: 0, + scriptHex: '51', + valueZatoshis: value, + minedHeight: height, + blockHash: '22' * 32, + blockTime: 1700000000, + isCoinbase: coinbase, + ); + final transparent = + zcash.ZcashTransparentState.fromAccount( + account: account, + viewingKeys: viewingKeys, + )..applyRefresh( + zcash.ZcashTransparentRefresh( + network: zcash.ZcashAddressNetwork.regtest, + accountFingerprint: account.fingerprint, + queriedAddresses: [own], + chainHeight: 42, + chainTipHash: '99' * 32, + canonicalBlockHashes: {40: '22' * 32, 41: '22' * 32, 42: '99' * 32}, + unspentOutputs: [ + coin('b1', 50000), + coin('b2', 30000), + coin('b4', 5000), + coin('b3', 70000, height: 41, coinbase: true), + ], + observedSpends: const [], + ), + ); + return zcash.ZcashWalletSyncState.atBirthday( + cursor: zcash.ZcashLightwalletdSyncCursor.origin(height: 1), + network: zcash.ZcashAddressNetwork.regtest, + accountFingerprint: account.fingerprint, + transparent: transparent, + ); } zcash.ZcashWalletSyncState _ironwoodFundedState({int noteHeight = 39}) {