1use 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 let value = Zatoshis::const_from_u64(50000);
53 let (h1, _, _) = st.add_a_single_note_checking_balance(value);
54
55 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 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 st.mine_decoy_blocks(1u8..41, value);
75 st.scan_cached_blocks(h1 + 1, 40);
76
77 st.expect_insufficient_funds(&to, amount_retry, nothing_available, retry_required);
79
80 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 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 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 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 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 let notes = st.wallet().get_notes(T::SHIELDED_PROTOCOL).unwrap();
122 assert_eq!(notes.len(), 1);
123 let note = ¬es[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 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 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 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 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 assert!(st.wallet_mut().unlock_output(&output_ref, owner).unwrap());
173
174 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 let amount_sent = Zatoshis::const_from_u64(15000);
184 st.spend_to(&to, amount_sent);
185}
186
187pub 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 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 let chain_tip = st.latest_cached_block().unwrap().height();
208 let target_height = chain_tip + 1;
209
210 let output_ref = st.sole_note_ref();
212
213 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 assert_eq!(
235 st.wallet_mut()
236 .lock_outputs(&[output_ref], owner, target_height - 1)
237 .unwrap(),
238 1
239 );
240
241 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
255pub 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 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 let output_ref = st.sole_note_ref();
274
275 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 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 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 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 let funding_note_ref = st.sole_note_ref();
328
329 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 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 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 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 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 assert_eq!(
387 st.wallet_mut()
388 .lock_outputs(&[funding_note_ref], owner, BlockHeight::from(u32::MAX))
389 .unwrap(),
390 1
391 );
392 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
405pub 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 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 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 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
449pub 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 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 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 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 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 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 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
544pub 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 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 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 assert_eq!(
576 st.wallet_mut()
577 .lock_outputs(&[r1], owner_a, far_expiry)
578 .unwrap(),
579 1
580 );
581
582 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 assert_matches!(
598 st.wallet_mut().lock_outputs(&[r1], owner_b, far_expiry),
599 Err(LockError::LockFailure(r)) if r == r1
600 );
601
602 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 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 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 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 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
669pub 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 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 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 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 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 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 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
751pub 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 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 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 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 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 assert!(
865 st.wallet()
866 .get_locked_outputs(account_id)
867 .unwrap()
868 .contains(&locked_b_ref)
869 );
870}
871
872#[derive(Clone, Debug)]
874pub enum LockOp {
875 Lock {
883 notes: Vec<usize>,
884 owner: usize,
885 expiry_delta: u32,
886 },
887 Unlock { note: usize, owner: usize },
890 ClearLocked,
892 MineBlocks { count: usize },
895}
896
897const MODEL_OWNERS: [LockOwner; 2] = [LockOwner::new([0xA1; 32]), LockOwner::new([0xB2; 32])];
899
900pub 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
925pub 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 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 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 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 assert_matches!(result, Err(LockError::LockFailure(r)) if r == refs[i]);
1008 }
1009 }
1010 }
1011 LockOp::Unlock { note, owner } => {
1012 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 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 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#[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 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 assert_matches!(
1139 st.wallet()
1140 .get_unspent_transparent_output(&outpoint, target_height),
1141 Ok(Some(_))
1142 );
1143
1144 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 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 assert_matches!(
1164 st.wallet()
1165 .get_unspent_transparent_output(&outpoint, target_height),
1166 Ok(Some(_))
1167 );
1168
1169 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 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 assert_eq!(
1210 st.wallet().get_locked_outputs(account_id).unwrap(),
1211 vec![output_ref]
1212 );
1213
1214 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 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
1256pub 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 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 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 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 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 assert_eq!(
1326 select(&LockedInputPolicy::Exclude).total_value().unwrap(),
1327 newer_unlocked_value,
1328 "Exclude must never surface a locked note"
1329 );
1330}