Skip to main content

zcash_client_backend/data_api/testing/pool/
locking.rs

1//! The shared, backend-agnostic test suite for the note-locking feature.
2//!
3//! Every scenario here is generic over a [`ShieldedPoolTester`] (or a
4//! [`DataStoreFactory`] for the transparent scenario) and is instantiated per
5//! pool by the concrete backends (see `zcash_client_sqlite`). The semantics
6//! under test are specified in [`crate::data_api::locking`].
7
8use std::convert::Infallible;
9
10use assert_matches::assert_matches;
11use proptest::prelude::{Just, Strategy, prop_oneof};
12
13use zcash_protocol::{PoolType, TxId, consensus::BlockHeight, value::Zatoshis};
14use zip321::Payment;
15
16use crate::{
17    data_api::{
18        self, Account as _, InputSource, OutputLockStore, WalletRead, WalletTest,
19        error::LockError,
20        testing::{DataStoreFactory, TestCache, single_output_change_strategy},
21        wallet::{
22            ConfirmationsPolicy, TargetHeight,
23            input_selection::{
24                GreedyInputSelector, LockFilter, LockedInputPolicy, NonEmptyBTreeSet, SpendPolicy,
25            },
26        },
27    },
28    fees::StandardFeeRule,
29    wallet::{LockOwner, OutputRef, OvkPolicy},
30};
31
32use super::{ShieldedPoolTester, dsl::TestDsl};
33
34#[cfg(feature = "transparent-inputs")]
35use {
36    crate::{
37        data_api::{CoinbaseFilter, WalletWrite, testing::TestBuilder},
38        wallet::WalletTransparentOutput,
39    },
40    transparent::bundle::{OutPoint, TxOut},
41    zcash_keys::keys::{UnifiedAddressRequest, transparent::TransparentKeyScope},
42    zcash_primitives::block::BlockHash,
43};
44
45pub fn spend_fails_on_locked_notes<T: ShieldedPoolTester>(
46    ds_factory: impl DataStoreFactory,
47    cache: impl TestCache,
48) {
49    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
50
51    // Add funds to the wallet in a single note
52    let value = Zatoshis::const_from_u64(50000);
53    let (h1, _, _) = st.add_a_single_note_checking_balance(value);
54
55    // Send some of the funds to another address, but don't mine the tx.
56    let extsk2 = T::sk(&[0xf5; 32]);
57    let to = T::sk_default_address(&extsk2);
58    let account_id = st.test_account().unwrap().id();
59    let amount_sent1 = Zatoshis::const_from_u64(15000);
60    st.spend_to(&to, amount_sent1);
61
62    // A second proposal fails because there are no usable notes: the sole note is
63    // committed to the unmined first transaction, so nothing is available even
64    // though the request plus the ZIP 317 fee would require `retry_required`.
65    let amount_retry = Zatoshis::const_from_u64(2000);
66    let zip317_fee = Zatoshis::const_from_u64(10000);
67    let nothing_available = Zatoshis::ZERO;
68    let retry_required = (amount_retry + zip317_fee).unwrap();
69    st.expect_insufficient_funds(&to, amount_retry, nothing_available, retry_required);
70
71    // Mine and scan 40 blocks that don't send us funds, up to just before the first
72    // transaction expires. Every mined block is scanned: an unscanned block below the tip
73    // would itself withhold spendability.
74    st.mine_decoy_blocks(1u8..41, value);
75    st.scan_cached_blocks(h1 + 1, 40);
76
77    // Second proposal still fails
78    st.expect_insufficient_funds(&to, amount_retry, nothing_available, retry_required);
79
80    // Mine the block at which the first transaction expires.
81    let expiring_block_seed = 42;
82    let expiry_height = st.mine_decoy_block(expiring_block_seed, value);
83    st.scan_cached_blocks(expiry_height, 1);
84
85    // Spendable balance matches total balance at 1 confirmation.
86    assert_eq!(st.get_total_balance(account_id), value);
87    assert_eq!(
88        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
89        value
90    );
91
92    // Second spend should now succeed
93    let amount_sent2 = amount_retry;
94    let txid2 = st.spend_to(&to, amount_sent2);
95
96    let (h, _) = st.generate_next_block_including(txid2);
97    st.scan_cached_blocks(h, 1);
98
99    // TODO: send to an account so that we can check its balance.
100    assert_eq!(
101        st.get_total_balance(account_id),
102        (value - (amount_sent2 + zip317_fee).unwrap()).unwrap()
103    );
104}
105
106pub fn explicit_note_locking<T: ShieldedPoolTester>(
107    ds_factory: impl DataStoreFactory,
108    cache: impl TestCache,
109) {
110    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
111
112    let fee_rule = StandardFeeRule::Zip317;
113
114    // Add funds to the wallet in a single note
115    let value = Zatoshis::const_from_u64(50000);
116    let (_, _, _) = st.add_a_single_note_checking_balance(value);
117
118    let account_id = st.test_account().unwrap().id();
119
120    // Find the received note and construct an OutputRef for it
121    let notes = st.wallet().get_notes(T::SHIELDED_PROTOCOL).unwrap();
122    assert_eq!(notes.len(), 1);
123    let note = &notes[0];
124    let output_ref = OutputRef::new(
125        *note.txid(),
126        PoolType::Shielded(note.note().pool()),
127        u32::from(note.output_index()),
128    );
129
130    // Balance is available before locking
131    assert_eq!(st.get_total_balance(account_id), value);
132    assert_eq!(
133        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
134        value
135    );
136
137    // Lock the note with a far-future expiry so it's active during the test
138    let owner = LockOwner::new([1; 32]);
139    assert_eq!(
140        st.wallet_mut()
141            .lock_outputs(&[output_ref], owner, BlockHeight::from(u32::MAX))
142            .unwrap(),
143        1
144    );
145
146    // Total balance is unchanged, but spendable is zero and locked equals the full value
147    assert_eq!(st.get_total_balance(account_id), value);
148    assert_eq!(st.get_locked_balance(account_id), value);
149    assert_eq!(
150        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
151        Zatoshis::ZERO
152    );
153
154    // Proposal should fail because there are no spendable notes
155    let extsk2 = T::sk(&[0xf5; 32]);
156    let to = T::sk_default_address(&extsk2);
157    assert_matches!(
158        st.propose_standard_transfer::<Infallible>(
159            account_id,
160            fee_rule,
161            ConfirmationsPolicy::MIN,
162            &to,
163            Zatoshis::const_from_u64(15000),
164            None,
165            None,
166            T::SHIELDED_PROTOCOL,
167        ),
168        Err(data_api::error::Error::InsufficientFunds { .. })
169    );
170
171    // Unlock the note
172    assert!(st.wallet_mut().unlock_output(&output_ref, owner).unwrap());
173
174    // Balance should be restored: spendable equals the full value, locked is zero
175    assert_eq!(st.get_total_balance(account_id), value);
176    assert_eq!(st.get_locked_balance(account_id), Zatoshis::ZERO);
177    assert_eq!(
178        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
179        value
180    );
181
182    // Proposal should now succeed
183    let amount_sent = Zatoshis::const_from_u64(15000);
184    st.spend_to(&to, amount_sent);
185}
186
187/// Exercises the exact height boundary of the note-locking semantics.
188///
189/// A lock with `lock_expiry_height == target_height` must keep the output locked (excluded from
190/// selection, counted as locked balance), whereas a lock with `lock_expiry_height ==
191/// target_height - 1` must leave the output spendable. Balance computation uses
192/// `target_height = chain_tip + 1`, so we derive the boundary from the current chain tip.
193pub fn note_locking_height_boundary<T: ShieldedPoolTester>(
194    ds_factory: impl DataStoreFactory,
195    cache: impl TestCache,
196) {
197    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
198
199    // Add funds to the wallet in a single note
200    let value = Zatoshis::const_from_u64(50000);
201    let (_, _, _) = st.add_a_single_note_checking_balance(value);
202
203    let account = st.test_account().cloned().unwrap();
204    let account_id = account.id();
205
206    // Balance computation targets `chain_tip + 1`.
207    let chain_tip = st.latest_cached_block().unwrap().height();
208    let target_height = chain_tip + 1;
209
210    // Find the received note and construct an OutputRef for it
211    let output_ref = st.sole_note_ref();
212
213    // Lock with expiry exactly at the target height: the output must be treated as locked.
214    let owner = LockOwner::new([1; 32]);
215    assert_eq!(
216        st.wallet_mut()
217            .lock_outputs(&[output_ref], owner, target_height)
218            .unwrap(),
219        1
220    );
221    assert_eq!(st.get_locked_balance(account_id), value);
222    assert_eq!(
223        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
224        Zatoshis::ZERO
225    );
226    assert_eq!(
227        st.wallet().get_locked_outputs(account_id).unwrap(),
228        vec![output_ref]
229    );
230
231    // Re-lock with expiry one block below the target height. The existing lock is not yet
232    // expired as of the chain tip, but the same owner may re-acquire (and here, shorten) its
233    // own lock directly, with no explicit unlock.
234    assert_eq!(
235        st.wallet_mut()
236            .lock_outputs(&[output_ref], owner, target_height - 1)
237            .unwrap(),
238        1
239    );
240
241    // With expiry strictly below the target height, the output is spendable again.
242    assert_eq!(st.get_locked_balance(account_id), Zatoshis::ZERO);
243    assert_eq!(
244        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
245        value
246    );
247    assert!(
248        st.wallet()
249            .get_locked_outputs(account_id)
250            .unwrap()
251            .is_empty()
252    );
253}
254
255/// Verifies that [`OutputLockStore::clear_locked_outputs`] unlocks every locked output for an account
256/// regardless of expiry height, as required by the lost-proposal recovery path.
257///
258/// [`OutputLockStore::clear_locked_outputs`]: crate::data_api::OutputLockStore::clear_locked_outputs
259pub fn clear_locked_outputs<T: ShieldedPoolTester>(
260    ds_factory: impl DataStoreFactory,
261    cache: impl TestCache,
262) {
263    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
264
265    // Add funds to the wallet in a single note
266    let value = Zatoshis::const_from_u64(50000);
267    let (_, _, _) = st.add_a_single_note_checking_balance(value);
268
269    let account = st.test_account().cloned().unwrap();
270    let account_id = account.id();
271
272    // Find the received note and construct an OutputRef for it
273    let output_ref = st.sole_note_ref();
274
275    // Lock the note with a far-future expiry.
276    let owner = LockOwner::new([1; 32]);
277    assert_eq!(
278        st.wallet_mut()
279            .lock_outputs(&[output_ref], owner, BlockHeight::from(u32::MAX))
280            .unwrap(),
281        1
282    );
283    assert_eq!(st.get_locked_balance(account_id), value);
284    assert_eq!(
285        st.wallet().get_locked_outputs(account_id).unwrap(),
286        vec![output_ref]
287    );
288
289    // Clearing all locks for the account unlocks the output even though its expiry height is far
290    // in the future (and regardless of its owner).
291    assert_eq!(st.wallet_mut().clear_locked_outputs(account_id).unwrap(), 1);
292    assert_eq!(st.get_locked_balance(account_id), Zatoshis::ZERO);
293    assert_eq!(
294        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
295        value
296    );
297    assert!(
298        st.wallet()
299            .get_locked_outputs(account_id)
300            .unwrap()
301            .is_empty()
302    );
303
304    // Clearing again is a no-op and reports zero unlocked outputs.
305    assert_eq!(st.wallet_mut().clear_locked_outputs(account_id).unwrap(), 0);
306}
307
308pub fn proposal_level_note_locking<T: ShieldedPoolTester>(
309    ds_factory: impl DataStoreFactory,
310    cache: impl TestCache,
311) {
312    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
313
314    let fee_rule = StandardFeeRule::Zip317;
315
316    // Add funds to the wallet in a single note
317    let value = Zatoshis::const_from_u64(50000);
318    let (_, _, _) = st.add_a_single_note_checking_balance(value);
319
320    let account = st.test_account().cloned().unwrap();
321    let account_id = account.id();
322    let extsk2 = T::sk(&[0xf5; 32]);
323    let to = T::sk_default_address(&extsk2);
324
325    // Remember the funding note's reference; it is spent at the end of this test, where the
326    // lock-a-spent-note behavior is pinned.
327    let funding_note_ref = st.sole_note_ref();
328
329    // Create a proposal with lock_for_blocks: Some(100) using propose_transfer
330    let owner = LockOwner::new([1; 32]);
331    let amount_sent = Zatoshis::const_from_u64(15000);
332    let proposal = st.propose_locking_transfer(&to, amount_sent, owner, 100);
333
334    // Notes should now be locked; a second proposal should fail
335    assert_matches!(
336        st.propose_standard_transfer::<Infallible>(
337            account_id,
338            fee_rule,
339            ConfirmationsPolicy::MIN,
340            &to,
341            Zatoshis::const_from_u64(2000),
342            None,
343            None,
344            T::SHIELDED_PROTOCOL,
345        ),
346        Err(data_api::error::Error::InsufficientFunds { .. })
347    );
348
349    // Execute the proposal; this should unlock the notes (they become spent)
350    assert_matches!(
351        st.create_proposed_transactions::<Infallible, _, Infallible, _>(
352            account.usk(),
353            OvkPolicy::Sender,
354            &proposal,
355        ),
356        Ok(txids) if txids.len() == 1
357    );
358
359    // All notes should now be unlocked (spent via spends table, lock cleared)
360    let locked = st.wallet().get_locked_outputs(account_id).unwrap();
361    assert!(
362        locked.is_empty(),
363        "all notes should be unlocked after create_proposed_transactions"
364    );
365
366    // Pin two lock-target edge behaviors:
367    //
368    // Locking an output the wallet does not know fails with `LockFailure` (the "not found"
369    // and "already locked" cases are deliberately indistinguishable to the caller).
370    let unknown = OutputRef::new(
371        TxId::from_bytes([0xEE; 32]),
372        PoolType::Shielded(T::SHIELDED_PROTOCOL),
373        0,
374    );
375    assert_matches!(
376        st.wallet_mut()
377            .lock_outputs(&[unknown], owner, BlockHeight::from(u32::MAX)),
378        Err(LockError::LockFailure(r)) if r == unknown
379    );
380
381    // Locking an already-spent note currently SUCCEEDS: `lock_outputs` checks only for an
382    // existing active lock, not for spend status. This is harmless in the proposal flow
383    // (spent notes never enter selection, and the lock has no balance effect because balance
384    // computation only considers unspent notes), but it is pinned here so that any future
385    // tightening of the contract is a visible, deliberate change.
386    assert_eq!(
387        st.wallet_mut()
388            .lock_outputs(&[funding_note_ref], owner, BlockHeight::from(u32::MAX))
389            .unwrap(),
390        1
391    );
392    // The stale lock is visible in the raw lock listing but has no balance effect.
393    assert_eq!(
394        st.wallet().get_locked_outputs(account_id).unwrap(),
395        vec![funding_note_ref]
396    );
397    assert_eq!(st.get_locked_balance(account_id), Zatoshis::ZERO);
398    assert!(
399        st.wallet_mut()
400            .unlock_output(&funding_note_ref, owner)
401            .unwrap()
402    );
403}
404
405/// Verifies that a proposal created with `lock_for_blocks: Some(_)` round-trips through its
406/// serialized (proto) form.
407///
408/// A locking proposal locks its own inputs, and decoding re-retrieves each input from the wallet.
409/// Input retrieval during decoding must therefore not filter out locked outputs; otherwise a
410/// wallet that persists a locking proposal (for example around an app restart, while a PCZT is
411/// out for signing) could never decode it again.
412pub fn locked_proposal_proto_roundtrip<T: ShieldedPoolTester>(
413    ds_factory: impl DataStoreFactory,
414    cache: impl TestCache,
415) {
416    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
417
418    // Add funds to the wallet in a single note
419    let value = Zatoshis::const_from_u64(50000);
420    let (_, _, _) = st.add_a_single_note_checking_balance(value);
421
422    let account_id = st.test_account().unwrap().id();
423    let extsk2 = T::sk(&[0xf5; 32]);
424    let to = T::sk_default_address(&extsk2);
425
426    let owner = LockOwner::new([1; 32]);
427    let amount_sent = Zatoshis::const_from_u64(15000);
428    let proposal = st.propose_locking_transfer(&to, amount_sent, owner, 100);
429
430    // The proposal's input is locked.
431    assert!(
432        !st.wallet()
433            .get_locked_outputs(account_id)
434            .unwrap()
435            .is_empty(),
436        "the proposal's input must be locked before the round-trip"
437    );
438
439    // The serialized proposal must decode back to an identical proposal even though its inputs
440    // are locked (a proposal legitimately references its own locked inputs).
441    let network = *st.network();
442    let proto = crate::proto::proposal::Proposal::from_standard_proposal(&proposal);
443    let decoded = proto
444        .try_into_standard_proposal(&network, st.wallet())
445        .expect("a proposal with locked inputs must decode from its serialized form");
446    assert_eq!(decoded, proposal);
447}
448
449/// Exercises the passed-expiry semantics of note locking under chain advance.
450///
451/// A lock names an expiry height `h`; balance and selection evaluate it against
452/// `target_height = chain_tip + 1`, so the note stays locked while `chain_tip < h` and becomes
453/// spendable again, with no unlock call, as soon as the chain tip reaches `h`. The stale
454/// `lock_expiry_height` value remains in the row, and a subsequent `lock_outputs` replaces it
455/// (the expired-lock branch of the lock-acquisition guard).
456pub fn lock_expiry_restores_spendability<T: ShieldedPoolTester>(
457    ds_factory: impl DataStoreFactory,
458    cache: impl TestCache,
459) {
460    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
461
462    // Add funds to the wallet in a single note
463    let value = Zatoshis::const_from_u64(50000);
464    let (_, _, _) = st.add_a_single_note_checking_balance(value);
465
466    let account_id = st.test_account().unwrap().id();
467    let tip = st.latest_cached_block().unwrap().height();
468
469    let output_ref = st.sole_note_ref();
470
471    // Lock the note until three blocks past the current tip.
472    let owner = LockOwner::new([1; 32]);
473    let expiry = tip + 3;
474    assert_eq!(
475        st.wallet_mut()
476            .lock_outputs(&[output_ref], owner, expiry)
477            .unwrap(),
478        1
479    );
480    assert_eq!(st.get_locked_balance(account_id), value);
481
482    // Advance the chain to two blocks below the expiry... still locked: the balance target
483    // height is now `expiry` itself, and a lock covers its expiry height inclusively.
484    st.add_empty_blocks(2);
485    assert_eq!(st.get_locked_balance(account_id), value);
486    assert_eq!(
487        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
488        Zatoshis::ZERO
489    );
490    assert_eq!(
491        st.wallet().get_locked_outputs(account_id).unwrap(),
492        vec![output_ref]
493    );
494
495    // One more block reaches the expiry height: the lock has now been passed, and the note is
496    // spendable again without any unlock call. The stale lock_expiry_height column value is
497    // simply ignored by selection and balance.
498    st.add_empty_blocks(1);
499    assert_eq!(st.get_locked_balance(account_id), Zatoshis::ZERO);
500    assert_eq!(
501        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
502        value
503    );
504    assert!(
505        st.wallet()
506            .get_locked_outputs(account_id)
507            .unwrap()
508            .is_empty()
509    );
510
511    // A spend proposal succeeds now that the lock has expired.
512    let extsk2 = T::sk(&[0xf5; 32]);
513    let to = T::sk_default_address(&extsk2);
514    st.propose_standard_transfer::<Infallible>(
515        account_id,
516        StandardFeeRule::Zip317,
517        ConfirmationsPolicy::MIN,
518        &to,
519        Zatoshis::const_from_u64(15000),
520        None,
521        None,
522        T::SHIELDED_PROTOCOL,
523    )
524    .expect("an expired lock must not block proposal creation");
525
526    // The expired lock is replaceable, even by a DIFFERENT owner: a fresh lock_outputs call
527    // succeeds without an explicit unlock, overwriting the stale expiry value and taking over
528    // ownership of the lock.
529    let other_owner = LockOwner::new([2; 32]);
530    let new_tip = st.latest_cached_block().unwrap().height();
531    assert_eq!(
532        st.wallet_mut()
533            .lock_outputs(&[output_ref], other_owner, new_tip + 5)
534            .unwrap(),
535        1
536    );
537    assert_eq!(st.get_locked_balance(account_id), value);
538    assert_eq!(
539        st.wallet().get_locked_outputs(account_id).unwrap(),
540        vec![output_ref]
541    );
542}
543
544/// Exercises lock-conflict detection and the all-or-nothing batch contract of
545/// [`OutputLockStore::lock_outputs`], along with the `unlock_output` return-value semantics.
546///
547/// [`OutputLockStore::lock_outputs`]: crate::data_api::OutputLockStore::lock_outputs
548pub fn lock_conflict_and_batch_atomicity<T: ShieldedPoolTester>(
549    ds_factory: impl DataStoreFactory,
550    cache: impl TestCache,
551) {
552    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
553
554    // Fund the wallet with two notes of distinct values in a single block, so that each note
555    // can be identified by its value below.
556    let value1 = Zatoshis::const_from_u64(60000);
557    let value2 = Zatoshis::const_from_u64(40000);
558    st.add_notes_checking_balance([[value1, value2]]);
559
560    let account_id = st.test_account().unwrap().id();
561    let far_expiry = BlockHeight::from(u32::MAX);
562
563    // Each note is identified by its (distinct) value.
564    assert_eq!(
565        st.wallet().get_notes(T::SHIELDED_PROTOCOL).unwrap().len(),
566        2
567    );
568    let r1 = st.note_ref_by_value(value1);
569    let r2 = st.note_ref_by_value(value2);
570
571    let owner_a = LockOwner::new([0xA1; 32]);
572    let owner_b = LockOwner::new([0xB2; 32]);
573
574    // The first lock on a note succeeds.
575    assert_eq!(
576        st.wallet_mut()
577            .lock_outputs(&[r1], owner_a, far_expiry)
578            .unwrap(),
579        1
580    );
581
582    // Re-locking under the SAME owner succeeds while the lock is active: acquisition is
583    // idempotent for the holding flow (this is the crash-retry path), and may extend or
584    // shorten the expiry.
585    assert_eq!(
586        st.wallet_mut()
587            .lock_outputs(&[r1], owner_a, far_expiry)
588            .unwrap(),
589        1
590    );
591    assert_eq!(
592        st.wallet().get_locked_outputs(account_id).unwrap(),
593        vec![r1]
594    );
595
596    // A lock by a DIFFERENT owner fails while the first lock is active.
597    assert_matches!(
598        st.wallet_mut().lock_outputs(&[r1], owner_b, far_expiry),
599        Err(LockError::LockFailure(r)) if r == r1
600    );
601
602    // A batch containing a foreign-locked output fails all-or-nothing: r2 precedes the
603    // conflicting r1 in the batch, but the failure must leave r2 unlocked.
604    assert_matches!(
605        st.wallet_mut().lock_outputs(&[r2, r1], owner_b, far_expiry),
606        Err(LockError::LockFailure(r)) if r == r1
607    );
608    assert_eq!(
609        st.wallet().get_locked_outputs(account_id).unwrap(),
610        vec![r1],
611        "a failed batch lock must not leave any of its outputs locked"
612    );
613    assert_eq!(st.get_locked_balance(account_id), value1);
614    assert_eq!(
615        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
616        value2
617    );
618
619    // A batch containing the same output twice under one owner succeeds: the second occurrence
620    // re-acquires the lock taken by the first (both row updates are counted).
621    assert_eq!(
622        st.wallet_mut()
623            .lock_outputs(&[r2, r2], owner_b, far_expiry)
624            .unwrap(),
625        2
626    );
627    {
628        let mut locked = st.wallet().get_locked_outputs(account_id).unwrap();
629        locked.sort();
630        let mut expected = vec![r1, r2];
631        expected.sort();
632        assert_eq!(locked, expected);
633    }
634
635    // Unlocking is owner-scoped: owner A cannot release owner B's lock on r2, and unlocking
636    // an unknown output reports `false`.
637    assert!(!st.wallet_mut().unlock_output(&r2, owner_a).unwrap());
638    assert_eq!(
639        st.get_locked_balance(account_id),
640        (value1 + value2).unwrap()
641    );
642    let unknown = OutputRef::new(
643        TxId::from_bytes([0xEE; 32]),
644        PoolType::Shielded(T::SHIELDED_PROTOCOL),
645        0,
646    );
647    assert!(!st.wallet_mut().unlock_output(&unknown, owner_a).unwrap());
648
649    // Each owner releases its own lock; unlocking an output that holds no lock reports
650    // `false`.
651    assert!(st.wallet_mut().unlock_output(&r2, owner_b).unwrap());
652    assert!(!st.wallet_mut().unlock_output(&r2, owner_b).unwrap());
653    assert!(st.wallet_mut().unlock_output(&r1, owner_a).unwrap());
654    assert_eq!(st.get_locked_balance(account_id), Zatoshis::ZERO);
655
656    // With everything released, a single owner can lock both notes in one batch.
657    assert_eq!(
658        st.wallet_mut()
659            .lock_outputs(&[r1, r2], owner_a, far_expiry)
660            .unwrap(),
661        2
662    );
663    assert_eq!(
664        st.get_locked_balance(account_id),
665        (value1 + value2).unwrap()
666    );
667}
668
669/// Verifies that [`unlock_proposal_inputs`] releases the locks taken by a proposal created with
670/// a [`LockRequest`], restoring spendability for a subsequent proposal (the abandoned-proposal
671/// recovery path), and that the release is scoped to the owner that took the locks.
672///
673/// [`unlock_proposal_inputs`]: crate::data_api::wallet::unlock_proposal_inputs
674/// [`LockRequest`]: crate::data_api::wallet::LockRequest
675pub fn unlock_proposal_inputs_releases_locks<T: ShieldedPoolTester>(
676    ds_factory: impl DataStoreFactory,
677    cache: impl TestCache,
678) {
679    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
680
681    let fee_rule = StandardFeeRule::Zip317;
682
683    // Add funds to the wallet in a single note
684    let value = Zatoshis::const_from_u64(50000);
685    let (_, _, _) = st.add_a_single_note_checking_balance(value);
686
687    let account_id = st.test_account().unwrap().id();
688    let extsk2 = T::sk(&[0xf5; 32]);
689    let to = T::sk_default_address(&extsk2);
690
691    let owner = LockOwner::new([1; 32]);
692    let amount_sent = Zatoshis::const_from_u64(15000);
693    let proposal = st.propose_locking_transfer(&to, amount_sent, owner, 100);
694
695    // The proposal's input is locked; a competing proposal cannot be created.
696    assert_eq!(st.get_locked_balance(account_id), value);
697    assert_matches!(
698        st.propose_standard_transfer::<Infallible>(
699            account_id,
700            fee_rule,
701            ConfirmationsPolicy::MIN,
702            &to,
703            Zatoshis::const_from_u64(2000),
704            None,
705            None,
706            T::SHIELDED_PROTOCOL,
707        ),
708        Err(data_api::error::Error::InsufficientFunds { .. })
709    );
710
711    // Attempting to release the locks under the WRONG owner is a no-op: the locks are scoped
712    // to the owner that took them.
713    let other_owner = LockOwner::new([2; 32]);
714    crate::data_api::wallet::unlock_proposal_inputs(st.wallet_mut(), &proposal, other_owner)
715        .unwrap();
716    assert_eq!(st.get_locked_balance(account_id), value);
717
718    // Abandon the proposal: releasing its inputs under the correct owner restores spendable
719    // balance...
720    crate::data_api::wallet::unlock_proposal_inputs(st.wallet_mut(), &proposal, owner).unwrap();
721    assert_eq!(st.get_locked_balance(account_id), Zatoshis::ZERO);
722    assert_eq!(
723        st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
724        value
725    );
726    assert!(
727        st.wallet()
728            .get_locked_outputs(account_id)
729            .unwrap()
730            .is_empty()
731    );
732
733    // ... and a subsequent proposal can select the released inputs.
734    st.propose_standard_transfer::<Infallible>(
735        account_id,
736        fee_rule,
737        ConfirmationsPolicy::MIN,
738        &to,
739        Zatoshis::const_from_u64(2000),
740        None,
741        None,
742        T::SHIELDED_PROTOCOL,
743    )
744    .expect("released inputs must be selectable by a new proposal");
745
746    // Releasing an already-released proposal is a no-op.
747    crate::data_api::wallet::unlock_proposal_inputs(st.wallet_mut(), &proposal, owner).unwrap();
748    assert_eq!(st.get_locked_balance(account_id), Zatoshis::ZERO);
749}
750
751/// Verifies that `SpendPolicy::with_locked_input_policy` actually reaches note selection in
752/// `GreedyInputSelector::propose_transaction`, end to end.
753///
754/// With the default policy (`LockedInputPolicy::Exclude`), a proposal that needs more than the
755/// unlocked balance fails with `InsufficientFunds`, even though a locked note could cover it.
756/// With `LockedInputPolicy::PreferUnlocked` naming the lock's owner, the same proposal succeeds
757/// and its selected inputs include the note that owner locked. A note locked by a DIFFERENT
758/// owner — one the policy does not name — is never selected, under either policy.
759pub fn spend_policy_locked_input_policy_reaches_selection<T: ShieldedPoolTester>(
760    ds_factory: impl DataStoreFactory,
761    cache: impl TestCache,
762) {
763    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
764
765    let fee_rule = StandardFeeRule::Zip317;
766
767    // Fund the account with three notes of distinct values in a single block, so that each can
768    // be identified by its value below: `unlocked_value` is left unlocked, `locked_a_value` is
769    // locked by owner A, and `locked_b_value` is locked by a DIFFERENT owner B.
770    let unlocked_value = Zatoshis::const_from_u64(20_000);
771    let locked_a_value = Zatoshis::const_from_u64(60_000);
772    let locked_b_value = Zatoshis::const_from_u64(70_000);
773    st.add_notes_checking_balance([[unlocked_value, locked_a_value, locked_b_value]]);
774
775    let account = st.test_account().cloned().unwrap();
776    let account_id = account.id();
777
778    assert_eq!(
779        st.wallet().get_notes(T::SHIELDED_PROTOCOL).unwrap().len(),
780        3
781    );
782    let locked_a_ref = st.note_ref_by_value(locked_a_value);
783    let locked_b_ref = st.note_ref_by_value(locked_b_value);
784
785    let owner_a = LockOwner::new([0xA1; 32]);
786    let owner_b = LockOwner::new([0xB2; 32]);
787    let far_expiry = BlockHeight::from(u32::MAX);
788    assert_eq!(
789        st.wallet_mut()
790            .lock_outputs(&[locked_a_ref], owner_a, far_expiry)
791            .unwrap(),
792        1
793    );
794    assert_eq!(
795        st.wallet_mut()
796            .lock_outputs(&[locked_b_ref], owner_b, far_expiry)
797            .unwrap(),
798        1
799    );
800
801    // The unlocked note alone cannot cover this request (plus fee); a locked note is required.
802    let request_amount = Zatoshis::const_from_u64(50_000);
803    let extsk2 = T::sk(&[0xf5; 32]);
804    let to = T::sk_default_address(&extsk2);
805    let request = zip321::TransactionRequest::new(vec![Payment::without_memo(
806        to.to_zcash_address(st.network()),
807        request_amount,
808    )])
809    .unwrap();
810
811    let input_selector = GreedyInputSelector::new();
812    let change_strategy = single_output_change_strategy(fee_rule, None, T::SHIELDED_PROTOCOL);
813
814    // With the default `Exclude` policy, both locked notes are ineligible, and the unlocked
815    // note alone is insufficient: the A-locked note is NOT drawn upon.
816    assert_matches!(
817        st.propose_transfer_with_policy(
818            account_id,
819            &input_selector,
820            &change_strategy,
821            request.clone(),
822            ConfirmationsPolicy::MIN,
823            &SpendPolicy::default(),
824        ),
825        Err(data_api::error::Error::InsufficientFunds { .. })
826    );
827
828    // With `PreferUnlocked` naming owner A, the proposal succeeds and draws on the note owner A
829    // locked, but never on the note locked by owner B (who the policy does not name).
830    let policy = SpendPolicy::default().with_locked_input_policy(
831        LockedInputPolicy::PreferUnlocked(NonEmptyBTreeSet::singleton(owner_a)),
832    );
833    let proposal = st
834        .propose_transfer_with_policy(
835            account_id,
836            &input_selector,
837            &change_strategy,
838            request,
839            ConfirmationsPolicy::MIN,
840            &policy,
841        )
842        .expect("a note locked by a permitted owner must be selectable to cover the request");
843
844    assert_eq!(proposal.steps().len(), 1);
845    let selected_values: Vec<Zatoshis> = proposal
846        .steps()
847        .head
848        .shielded_inputs()
849        .expect("the proposal must spend shielded notes")
850        .notes()
851        .iter()
852        .map(|rn| rn.note().value())
853        .collect();
854    assert!(
855        selected_values.contains(&locked_a_value),
856        "the note locked by the permitted owner must be selected: {selected_values:?}"
857    );
858    assert!(
859        !selected_values.contains(&locked_b_value),
860        "a note locked by a different owner must never be selected: {selected_values:?}"
861    );
862
863    // The owner-B lock is untouched by this proposal.
864    assert!(
865        st.wallet()
866            .get_locked_outputs(account_id)
867            .unwrap()
868            .contains(&locked_b_ref)
869    );
870}
871
872/// An operation in the note-locking model test; see [`check_note_locking_model`].
873#[derive(Clone, Debug)]
874pub enum LockOp {
875    /// Attempt to lock the notes at the given indices on behalf of the given owner
876    /// (duplicates permitted: a duplicated index re-acquires the lock taken by its own first
877    /// occurrence, which succeeds because it is held by the same owner) with expiry height
878    /// `chain_tip + expiry_delta`.
879    ///
880    /// An `expiry_delta` of zero produces a lock that is expired from the moment it is taken:
881    /// balance and selection evaluate locks against `target_height = chain_tip + 1`.
882    Lock {
883        notes: Vec<usize>,
884        owner: usize,
885        expiry_delta: u32,
886    },
887    /// Unlock the note at the given index on behalf of the given owner; only a lock held by
888    /// that owner is released.
889    Unlock { note: usize, owner: usize },
890    /// Clear every lock for the account, regardless of expiry or owner.
891    ClearLocked,
892    /// Mine the given number of empty blocks, advancing the chain tip (and thereby expiring
893    /// any lock whose expiry height the tip reaches).
894    MineBlocks { count: usize },
895}
896
897/// The owner-index pool used by [`arb_lock_ops`] and [`check_note_locking_model`].
898const MODEL_OWNERS: [LockOwner; 2] = [LockOwner::new([0xA1; 32]), LockOwner::new([0xB2; 32])];
899
900/// A `proptest` strategy over sequences of [`LockOp`] for a wallet holding `n_notes` notes.
901///
902/// Expiry deltas and mining counts are drawn from small ranges so that sequences routinely
903/// cross lock-expiry boundaries.
904pub fn arb_lock_ops(n_notes: usize, max_ops: usize) -> impl Strategy<Value = Vec<LockOp>> {
905    let n_owners = MODEL_OWNERS.len();
906    let op = prop_oneof![
907        3 => (
908            proptest::collection::vec(0..n_notes, 1..=n_notes + 1),
909            0..n_owners,
910            0u32..=4,
911        )
912            .prop_map(|(notes, owner, expiry_delta)| LockOp::Lock {
913                notes,
914                owner,
915                expiry_delta
916            }),
917        2 => (0..n_notes, 0..n_owners)
918            .prop_map(|(note, owner)| LockOp::Unlock { note, owner }),
919        1 => Just(LockOp::ClearLocked),
920        2 => (1usize..=3).prop_map(|count| LockOp::MineBlocks { count }),
921    ];
922    proptest::collection::vec(op, 1..=max_ops)
923}
924
925/// Model-based test of the note-locking storage operations.
926///
927/// Funds a wallet with three notes, then applies the given operation sequence both to the real
928/// data store and to a trivial in-memory model (per-note `Option<(lock_expiry_height, owner)>`
929/// plus the chain tip). After every operation, the store must agree with the model on:
930///
931/// - the outcome of the operation itself, including the all-or-nothing failure of a `Lock`
932///   batch containing a conflict (an active, unexpired lock held by a different owner on any
933///   requested note), same-owner re-lock idempotency, and owner-scoped unlocking;
934/// - the set reported by `get_locked_outputs` (a note is locked while
935///   `lock_expiry_height >= chain_tip + 1`);
936/// - the account balance decomposition: locked value is exactly the sum of model-locked note
937///   values, spendable value is the remainder, and the total is unaffected by lock state.
938pub fn check_note_locking_model<T: ShieldedPoolTester>(
939    ds_factory: impl DataStoreFactory,
940    cache: impl TestCache,
941    ops: &[LockOp],
942) {
943    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
944
945    // Fund the wallet with three notes of distinct values in a single block, so that notes can
946    // be matched to model indices by value.
947    let values = [
948        Zatoshis::const_from_u64(60000),
949        Zatoshis::const_from_u64(70000),
950        Zatoshis::const_from_u64(80000),
951    ];
952    st.add_notes_checking_balance([values]);
953    let total = values
954        .iter()
955        .try_fold(Zatoshis::ZERO, |acc, v| acc + *v)
956        .unwrap();
957
958    let account_id = st.test_account().unwrap().id();
959
960    assert_eq!(
961        st.wallet().get_notes(T::SHIELDED_PROTOCOL).unwrap().len(),
962        values.len()
963    );
964    let refs: Vec<OutputRef> = values.iter().map(|v| st.note_ref_by_value(*v)).collect();
965
966    // The model: per-note lock expiry height and owner index, and the chain tip.
967    let mut model: Vec<Option<(u32, usize)>> = vec![None; refs.len()];
968    let mut tip = u32::from(st.latest_cached_block().unwrap().height());
969
970    for op in ops {
971        match op {
972            LockOp::Lock {
973                notes,
974                owner,
975                expiry_delta,
976            } => {
977                let expiry = tip + expiry_delta;
978                // Predict the outcome by simulating the store's sequential update: each
979                // requested note may be locked when it holds no lock, when its lock has
980                // expired as of the chain tip, or when its lock is held by the requesting
981                // owner; the first conflict (an active foreign lock) fails the whole batch.
982                let mut scratch = model.clone();
983                let mut conflict = None;
984                for &i in notes {
985                    if scratch[i].is_none_or(|(h, o)| h <= tip || o == *owner) {
986                        scratch[i] = Some((expiry, *owner));
987                    } else {
988                        conflict = Some(i);
989                        break;
990                    }
991                }
992
993                let batch: Vec<OutputRef> = notes.iter().map(|&i| refs[i]).collect();
994                let result = st.wallet_mut().lock_outputs(
995                    &batch,
996                    MODEL_OWNERS[*owner],
997                    BlockHeight::from(expiry),
998                );
999                match conflict {
1000                    None => {
1001                        assert_matches!(result, Ok(n) if n == notes.len());
1002                        model = scratch;
1003                    }
1004                    Some(i) => {
1005                        // The batch fails naming the conflicting note, and (checked by the
1006                        // post-operation invariants below) locks nothing.
1007                        assert_matches!(result, Err(LockError::LockFailure(r)) if r == refs[i]);
1008                    }
1009                }
1010            }
1011            LockOp::Unlock { note, owner } => {
1012                // Unlocking releases only a lock held by the requesting owner (expired or
1013                // not), and reports whether one was released.
1014                let expected = model[*note].is_some_and(|(_, o)| o == *owner);
1015                assert_eq!(
1016                    st.wallet_mut()
1017                        .unlock_output(&refs[*note], MODEL_OWNERS[*owner])
1018                        .unwrap(),
1019                    expected
1020                );
1021                if expected {
1022                    model[*note] = None;
1023                }
1024            }
1025            LockOp::ClearLocked => {
1026                // Clearing removes every lock record, expired or not and regardless of
1027                // owner, and reports how many rows it touched.
1028                let expected = model.iter().filter(|h| h.is_some()).count();
1029                assert_eq!(
1030                    st.wallet_mut().clear_locked_outputs(account_id).unwrap(),
1031                    expected
1032                );
1033                model.iter_mut().for_each(|h| *h = None);
1034            }
1035            LockOp::MineBlocks { count } => {
1036                st.add_empty_blocks(*count);
1037                tip += *count as u32;
1038            }
1039        }
1040
1041        // Invariants, checked after every operation. Balance and selection evaluate lock
1042        // state against the next block to be mined.
1043        let target = tip + 1;
1044        let locked_value = model
1045            .iter()
1046            .zip(values.iter())
1047            .filter(|(h, _)| h.is_some_and(|(h, _)| h >= target))
1048            .try_fold(Zatoshis::ZERO, |acc, (_, v)| acc + *v)
1049            .unwrap();
1050
1051        let mut expected_locked: Vec<OutputRef> = model
1052            .iter()
1053            .zip(refs.iter())
1054            .filter(|(h, _)| h.is_some_and(|(h, _)| h >= target))
1055            .map(|(_, r)| *r)
1056            .collect();
1057        expected_locked.sort();
1058        let mut actual_locked = st.wallet().get_locked_outputs(account_id).unwrap();
1059        actual_locked.sort();
1060        assert_eq!(
1061            actual_locked, expected_locked,
1062            "locked-output set diverged from the model after {op:?}"
1063        );
1064
1065        assert_eq!(
1066            st.get_locked_balance(account_id),
1067            locked_value,
1068            "locked balance diverged from the model after {op:?}"
1069        );
1070        assert_eq!(
1071            st.get_spendable_balance(account_id, ConfirmationsPolicy::MIN),
1072            (total - locked_value).unwrap(),
1073            "spendable balance diverged from the model after {op:?}"
1074        );
1075        assert_eq!(
1076            st.get_total_balance(account_id),
1077            total,
1078            "lock state must never change the total balance (after {op:?})"
1079        );
1080    }
1081}
1082
1083/// Exercises note locking for transparent outputs.
1084///
1085/// A locked UTXO is still returned by a by-outpoint lookup (which is not a selection query and
1086/// so does not filter by lock state), but is excluded from spendable-output listing unless the
1087/// query passes `LockFilter::Unfiltered`, is reported as locked (not spendable) value in the
1088/// per-address balances, conflicts with a second lock, and returns to spendability when the
1089/// chain tip passes the lock expiry height, with no unlock call.
1090#[cfg(feature = "transparent-inputs")]
1091pub fn transparent_note_locking<DSF>(dsf: DSF)
1092where
1093    DSF: DataStoreFactory,
1094    <<DSF as DataStoreFactory>::DataStore as WalletWrite>::UtxoRef: std::fmt::Debug,
1095{
1096    let mut st = TestBuilder::new()
1097        .with_data_store_factory(dsf)
1098        .with_account_from_sapling_activation(BlockHash([0; 32]))
1099        .build();
1100
1101    let birthday = st.test_account().unwrap().birthday().height();
1102    let account_id = st.test_account().unwrap().id();
1103    let uaddr = st
1104        .wallet()
1105        .get_last_generated_address_matching(account_id, UnifiedAddressRequest::AllAvailableKeys)
1106        .unwrap()
1107        .unwrap();
1108    let taddr = uaddr.transparent().unwrap();
1109
1110    let height = birthday + 12345;
1111    st.wallet_mut().update_chain_tip(height).unwrap();
1112
1113    // Create a fake transparent output mined at `height`.
1114    let value = Zatoshis::const_from_u64(100000);
1115    let outpoint = OutPoint::fake();
1116    let txout = TxOut::new(value, taddr.script().into());
1117    let utxo = WalletTransparentOutput::from_parts(
1118        outpoint.clone(),
1119        txout,
1120        Some(height),
1121        Some(account_id),
1122        Some(TransparentKeyScope::EXTERNAL),
1123        None,
1124    )
1125    .unwrap();
1126    st.wallet_mut()
1127        .put_received_transparent_utxo(&utxo)
1128        .unwrap();
1129
1130    let target_height = TargetHeight::from(height + 1);
1131    let output_ref = OutputRef::new(
1132        TxId::from_bytes(*outpoint.hash()),
1133        PoolType::TRANSPARENT,
1134        outpoint.n(),
1135    );
1136
1137    // The output is retrievable and spendable before locking.
1138    assert_matches!(
1139        st.wallet()
1140            .get_unspent_transparent_output(&outpoint, target_height),
1141        Ok(Some(_))
1142    );
1143
1144    // Lock the UTXO until ten blocks past the tip.
1145    let owner = LockOwner::new([1; 32]);
1146    assert_eq!(
1147        st.wallet_mut()
1148            .lock_outputs(&[output_ref], owner, height + 10)
1149            .unwrap(),
1150        1
1151    );
1152
1153    // A lock by a different owner conflicts while the first is active.
1154    let other_owner = LockOwner::new([2; 32]);
1155    assert_matches!(
1156        st.wallet_mut().lock_outputs(&[output_ref], other_owner, height + 20),
1157        Err(LockError::LockFailure(r)) if r == output_ref
1158    );
1159
1160    // A by-outpoint lookup of a known output is not a selection query, so it does not filter by
1161    // lock state: the output is still returned even though it is locked. Lock exclusion is
1162    // verified via `get_spendable_transparent_outputs`, below.
1163    assert_matches!(
1164        st.wallet()
1165            .get_unspent_transparent_output(&outpoint, target_height),
1166        Ok(Some(_))
1167    );
1168
1169    // ... and from the spendable-outputs listing unless the query is unfiltered.
1170    assert_matches!(
1171        st.wallet()
1172            .get_spendable_transparent_outputs(
1173                taddr,
1174                target_height,
1175                ConfirmationsPolicy::MIN,
1176                CoinbaseFilter::AllTransparentOutputs,
1177                LockFilter::Policy(&LockedInputPolicy::Exclude),
1178            )
1179            .as_deref(),
1180        Ok(&[])
1181    );
1182    assert_matches!(
1183        st.wallet()
1184            .get_spendable_transparent_outputs(
1185                taddr,
1186                target_height,
1187                ConfirmationsPolicy::MIN,
1188                CoinbaseFilter::AllTransparentOutputs,
1189                LockFilter::Unfiltered,
1190            )
1191            .as_deref(),
1192        Ok([_])
1193    );
1194
1195    // The per-address balances report the value as locked, not spendable; the total is
1196    // unaffected by lock state.
1197    let balances = st
1198        .wallet()
1199        .get_transparent_balances(account_id, target_height, ConfirmationsPolicy::MIN)
1200        .unwrap();
1201    let (_, bal) = balances
1202        .get(taddr)
1203        .expect("the address has a balance entry");
1204    assert_eq!(bal.locked_value(), value);
1205    assert_eq!(bal.spendable_value(), Zatoshis::ZERO);
1206    assert_eq!(bal.total(), value);
1207
1208    // The locked-outputs listing includes the transparent lock.
1209    assert_eq!(
1210        st.wallet().get_locked_outputs(account_id).unwrap(),
1211        vec![output_ref]
1212    );
1213
1214    // Advancing the chain tip to the expiry height restores spendability with no unlock call.
1215    st.wallet_mut().update_chain_tip(height + 10).unwrap();
1216    let expired_target = TargetHeight::from(height + 11);
1217    let balances = st
1218        .wallet()
1219        .get_transparent_balances(account_id, expired_target, ConfirmationsPolicy::MIN)
1220        .unwrap();
1221    let (_, bal) = balances
1222        .get(taddr)
1223        .expect("the address has a balance entry");
1224    assert_eq!(bal.spendable_value(), value);
1225    assert_eq!(bal.locked_value(), Zatoshis::ZERO);
1226    assert!(
1227        st.wallet()
1228            .get_locked_outputs(account_id)
1229            .unwrap()
1230            .is_empty()
1231    );
1232
1233    // The expired lock is replaceable without an explicit unlock, even by a different owner,
1234    // and the new holder can then release it.
1235    assert_eq!(
1236        st.wallet_mut()
1237            .lock_outputs(&[output_ref], other_owner, height + 30)
1238            .unwrap(),
1239        1
1240    );
1241    assert!(
1242        st.wallet_mut()
1243            .unlock_output(&output_ref, other_owner)
1244            .unwrap()
1245    );
1246    let balances = st
1247        .wallet()
1248        .get_transparent_balances(account_id, expired_target, ConfirmationsPolicy::MIN)
1249        .unwrap();
1250    let (_, bal) = balances
1251        .get(taddr)
1252        .expect("the address has a balance entry");
1253    assert_eq!(bal.spendable_value(), value);
1254}
1255
1256/// Single-note selection preserves the caller's lock-tier preference: the lock tier is the
1257/// primary sort key and chain age the secondary, matching the accumulation path's window order.
1258/// Without this, when `PreferUnlocked` or `PreferLocked` admits both tiers, the single oldest
1259/// covering note can come from the NON-preferred tier — in particular, `PreferUnlocked` could
1260/// reuse an acknowledged in-flight locked input merely because it is older than an unlocked
1261/// alternative.
1262pub fn single_note_selection_honors_lock_tier_preference<T: ShieldedPoolTester>(
1263    ds_factory: impl DataStoreFactory,
1264    cache: impl TestCache,
1265) {
1266    let mut st = TestDsl::with_sapling_birthday_account(ds_factory, cache).build::<T>();
1267
1268    // Two notes in successive blocks, each singly covering the target below. The OLDER note is
1269    // then locked, so tier preference and age preference disagree about which note to pick.
1270    let older_locked_value = Zatoshis::const_from_u64(50_000);
1271    let newer_unlocked_value = Zatoshis::const_from_u64(40_000);
1272    st.add_notes_checking_balance([[older_locked_value], [newer_unlocked_value]]);
1273
1274    let account_id = st.test_account().unwrap().id();
1275    let older_ref = st.note_ref_by_value(older_locked_value);
1276    let owner = LockOwner::new([0xA1; 32]);
1277    assert_eq!(
1278        st.wallet_mut()
1279            .lock_outputs(&[older_ref], owner, BlockHeight::from(u32::MAX))
1280            .unwrap(),
1281        1
1282    );
1283
1284    let target_height = TargetHeight::from(
1285        st.wallet()
1286            .chain_height()
1287            .unwrap()
1288            .expect("the chain has been scanned")
1289            + 1,
1290    );
1291    // Below either note's value, so both are covering candidates.
1292    let value = Zatoshis::const_from_u64(30_000);
1293    let select = |policy: &LockedInputPolicy| {
1294        st.wallet()
1295            .select_single_spendable_note(
1296                account_id,
1297                value,
1298                &[T::SHIELDED_PROTOCOL],
1299                target_height,
1300                ConfirmationsPolicy::MIN,
1301                &[],
1302                LockFilter::Policy(policy),
1303            )
1304            .unwrap()
1305    };
1306
1307    // `PreferUnlocked` admits both tiers, but must draw the unlocked tier first even though the
1308    // locked note is older.
1309    let unlocked_pref = LockedInputPolicy::PreferUnlocked(NonEmptyBTreeSet::singleton(owner));
1310    assert_eq!(
1311        select(&unlocked_pref).total_value().unwrap(),
1312        newer_unlocked_value,
1313        "PreferUnlocked must not reach for an older locked note past an unlocked alternative"
1314    );
1315
1316    // `PreferLocked` draws the locked tier first.
1317    let locked_pref = LockedInputPolicy::PreferLocked(NonEmptyBTreeSet::singleton(owner));
1318    assert_eq!(
1319        select(&locked_pref).total_value().unwrap(),
1320        older_locked_value,
1321        "PreferLocked must draw the locked tier first"
1322    );
1323
1324    // `Exclude` admits only the unlocked note at all.
1325    assert_eq!(
1326        select(&LockedInputPolicy::Exclude).total_value().unwrap(),
1327        newer_unlocked_value,
1328        "Exclude must never surface a locked note"
1329    );
1330}