zakura-client-backend 0.1.0-rc2

APIs for creating shielded Zcash light clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
//! Structs representing transaction data scanned from the block chain by a wallet or
//! light client.
use std::fmt::Debug;

use incrementalmerkletree::Position;

use ::transparent::{
    address::TransparentAddress,
    bundle::{OutPoint, TxOut},
    keys::TransparentKeyScope,
};
use zcash_address::ZcashAddress;
use zcash_keys::{address::Receiver, keys::OutgoingViewingKey};
use zcash_note_encryption::EphemeralKeyBytes;
use zcash_primitives::transaction::{TxId, fees::transparent as transparent_fees};
use zcash_protocol::{
    PoolType, ShieldedPool,
    consensus::{BlockHeight, TxIndex},
    value::{BalanceError, Zatoshis},
};
#[cfg(feature = "transparent-key-import")]
use zcash_script::script;
use zip32::Scope;

use crate::{TransferType, fees::sapling as sapling_fees};

#[cfg(feature = "orchard")]
use crate::fees::orchard as orchard_fees;

#[cfg(feature = "transparent-inputs")]
use {::transparent::keys::NonHardenedChildIndex, std::time::SystemTime};

/// A unique identifier for a shielded transaction output
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NoteId {
    txid: TxId,
    protocol: ShieldedPool,
    output_index: u16,
}

impl NoteId {
    /// Constructs a new `NoteId` from its parts.
    pub fn new(txid: TxId, protocol: ShieldedPool, output_index: u16) -> Self {
        Self {
            txid,
            protocol,
            output_index,
        }
    }

    /// Returns the ID of the transaction containing this note.
    pub fn txid(&self) -> &TxId {
        &self.txid
    }

    /// Returns the shielded protocol used by this note.
    pub fn protocol(&self) -> ShieldedPool {
        self.protocol
    }

    /// Returns the index of this note within its transaction's corresponding list of
    /// shielded outputs.
    pub fn output_index(&self) -> u16 {
        self.output_index
    }
}

/// A reference to a transaction output received by the wallet, across all pools.
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct OutputRef {
    txid: TxId,
    pool: PoolType,
    output_index: u32,
}

impl OutputRef {
    /// Constructs a new `OutputRef` from its parts.
    pub fn new(txid: TxId, pool: PoolType, output_index: u32) -> Self {
        Self {
            txid,
            pool,
            output_index,
        }
    }

    /// Returns the ID of the transaction containing this output.
    pub fn txid(&self) -> &TxId {
        &self.txid
    }

    /// Returns the pool type of this output.
    pub fn pool(&self) -> PoolType {
        self.pool
    }

    /// Returns the index of this output within its transaction.
    pub fn output_index(&self) -> u32 {
        self.output_index
    }
}

impl From<NoteId> for OutputRef {
    fn from(note_id: NoteId) -> Self {
        Self {
            txid: note_id.txid,
            pool: PoolType::Shielded(note_id.protocol),
            output_index: note_id.output_index.into(),
        }
    }
}

pub use crate::data_api::locking::LockOwner;

/// A type that represents the recipient of a transaction output.
///
/// Variants vary along two independent axes:
///
/// * **Relationship to the wallet**: whether the recipient address is [`Self::External`] to
///   the wallet, an [`Self::EphemeralTransparent`] address of a wallet account (used
///   transiently as a middle hop), or otherwise internal to a wallet account (recorded as
///   [`Self::InternalShielded`] or [`Self::InternalTransparent`], depending on payload
///   domain).
/// * **Payload domain**: whether the output is shielded (in which case what is recorded is
///   the decrypted [`Note`], since the recipient address is not itself externally
///   meaningful) or transparent (in which case what is recorded is the on-chain-observable
///   recipient address, since transparent outputs carry no analogous decryptable payload).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Recipient<AccountId> {
    /// An output sent to a recipient external to the wallet.
    External {
        recipient_address: ZcashAddress,
        output_pool: PoolType,
    },
    /// A transparent output sent to an ephemeral address of a wallet account
    /// (e.g. the middle hop of a ZIP 320 / TEX flow). The `outpoint` is
    /// recorded so the wallet can later detect when this output is spent
    /// without relying on a continuous address watch.
    #[cfg(feature = "transparent-inputs")]
    EphemeralTransparent {
        receiving_account: AccountId,
        ephemeral_address: TransparentAddress,
        outpoint: OutPoint,
    },
    /// A transparent output sent to a non-ephemeral transparent address belonging to
    /// a wallet account. Used to record the send side of a transparent output that
    /// the wallet both funded and received.
    ///
    /// Distinct from [`Self::InternalShielded`] because for transparent outputs
    /// the recipient address is observable on chain and must be recorded;
    /// additionally, the receiving account may not be known at the point the
    /// send is recorded. For shielded outputs the recipient address is not
    /// externally meaningful, so wallet-internal sends are recorded against
    /// the receiving account alone.
    #[cfg(feature = "transparent-inputs")]
    InternalTransparent {
        receiving_account: AccountId,
        recipient_address: TransparentAddress,
    },
    /// A shielded output recorded against a wallet account. Used for
    /// same-account outputs such as change (`external_address` is `None`) and
    /// for outputs received via an external IVK but funded by another wallet
    /// account, in which case `external_address` is the address that was paid.
    InternalShielded {
        receiving_account: AccountId,
        external_address: Option<ZcashAddress>,
        note: Box<Note>,
    },
}

/// The shielded subset of a [`Transaction`]'s data that is relevant to a particular wallet.
///
/// [`Transaction`]: zcash_primitives::transaction::Transaction
#[derive(Clone)]
pub struct WalletTx<AccountId> {
    txid: TxId,
    block_index: TxIndex,
    transparent_outputs: Vec<WalletTransparentOutput<AccountId>>,
    sapling_spends: Vec<WalletSaplingSpend<AccountId>>,
    sapling_outputs: Vec<WalletSaplingOutput<AccountId>>,
    #[cfg(feature = "orchard")]
    orchard_spends: Vec<WalletOrchardSpend<AccountId>>,
    #[cfg(feature = "orchard")]
    orchard_outputs: Vec<WalletOrchardOutput<AccountId>>,
    #[cfg(feature = "orchard")]
    ironwood_spends: Vec<WalletIronwoodSpend<AccountId>>,
    #[cfg(feature = "orchard")]
    ironwood_outputs: Vec<WalletIronwoodOutput<AccountId>>,
}

impl<AccountId> WalletTx<AccountId> {
    /// Constructs a new [`WalletTx`] from its constituent parts.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        txid: TxId,
        block_index: TxIndex,
        transparent_outputs: Vec<WalletTransparentOutput<AccountId>>,
        sapling_spends: Vec<WalletSaplingSpend<AccountId>>,
        sapling_outputs: Vec<WalletSaplingOutput<AccountId>>,
        #[cfg(feature = "orchard")] orchard_spends: Vec<
            WalletSpend<orchard::note::Nullifier, AccountId>,
        >,
        #[cfg(feature = "orchard")] orchard_outputs: Vec<WalletOrchardOutput<AccountId>>,
        #[cfg(feature = "orchard")] ironwood_spends: Vec<
            WalletSpend<orchard::note::Nullifier, AccountId>,
        >,
        #[cfg(feature = "orchard")] ironwood_outputs: Vec<WalletIronwoodOutput<AccountId>>,
    ) -> Self {
        Self {
            txid,
            block_index,
            transparent_outputs,
            sapling_spends,
            sapling_outputs,
            #[cfg(feature = "orchard")]
            orchard_spends,
            #[cfg(feature = "orchard")]
            orchard_outputs,
            #[cfg(feature = "orchard")]
            ironwood_spends,
            #[cfg(feature = "orchard")]
            ironwood_outputs,
        }
    }

    /// Returns the [`TxId`] for the corresponding [`Transaction`].
    ///
    /// [`Transaction`]: zcash_primitives::transaction::Transaction
    pub fn txid(&self) -> TxId {
        self.txid
    }

    /// Returns the index of the transaction in the containing block.
    pub fn block_index(&self) -> TxIndex {
        self.block_index
    }

    /// Returns a record for each transparent coin received or produced by the wallet.
    pub fn transparent_outputs(&self) -> &[WalletTransparentOutput<AccountId>] {
        &self.transparent_outputs
    }

    /// Returns a record for each Sapling note belonging to the wallet that was spent in the
    /// transaction.
    pub fn sapling_spends(&self) -> &[WalletSaplingSpend<AccountId>] {
        self.sapling_spends.as_ref()
    }

    /// Returns a record for each Sapling note received or produced by the wallet in the
    /// transaction.
    pub fn sapling_outputs(&self) -> &[WalletSaplingOutput<AccountId>] {
        self.sapling_outputs.as_ref()
    }

    /// Returns a record for each Orchard note belonging to the wallet that was spent in the
    /// transaction.
    #[cfg(feature = "orchard")]
    pub fn orchard_spends(&self) -> &[WalletOrchardSpend<AccountId>] {
        self.orchard_spends.as_ref()
    }

    /// Returns a record for each Orchard note received or produced by the wallet in the
    /// transaction.
    #[cfg(feature = "orchard")]
    pub fn orchard_outputs(&self) -> &[WalletOrchardOutput<AccountId>] {
        self.orchard_outputs.as_ref()
    }

    /// Returns a record for each Ironwood note belonging to the wallet that was spent in the
    /// transaction.
    #[cfg(feature = "orchard")]
    pub fn ironwood_spends(&self) -> &[WalletIronwoodSpend<AccountId>] {
        self.ironwood_spends.as_ref()
    }

    /// Returns a record for each Ironwood note received or produced by the wallet in the
    /// transaction.
    #[cfg(feature = "orchard")]
    pub fn ironwood_outputs(&self) -> &[WalletIronwoodOutput<AccountId>] {
        self.ironwood_outputs.as_ref()
    }
}

/// A transparent output controlled by the wallet.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WalletTransparentOutput<AccountId> {
    outpoint: OutPoint,
    txout: TxOut,
    mined_height: Option<BlockHeight>,
    recipient_account: Option<AccountId>,
    recipient_key_scope: Option<TransparentKeyScope>,
    recipient_address: TransparentAddress,
    funding_account: Option<AccountId>,
    /// The known serialized input size for this output, if available.
    /// This is set for P2SH outputs where the redeem script is known.
    known_input_size: Option<usize>,
}

impl<AccountId> WalletTransparentOutput<AccountId> {
    /// Constructs a new [`WalletTransparentOutput`] from its constituent parts.
    ///
    /// Returns `None` if the recipient address for the provided [`TxOut`] cannot be
    /// determined based on the set of output script patterns understood by this wallet.
    pub fn from_parts(
        outpoint: OutPoint,
        txout: TxOut,
        mined_height: Option<BlockHeight>,
        recipient_account: Option<AccountId>,
        recipient_key_scope: Option<TransparentKeyScope>,
        funding_account: Option<AccountId>,
    ) -> Option<Self> {
        txout
            .recipient_address()
            .map(|recipient_address| WalletTransparentOutput {
                outpoint,
                txout,
                mined_height,
                recipient_account,
                recipient_key_scope,
                recipient_address,
                funding_account,
                known_input_size: None,
            })
    }

    /// Returns a copy of this output with account-identifying data redacted,
    /// for inclusion in a [`Proposal`].
    ///
    /// Specifically:
    /// - The `AccountId` type parameter is replaced with `()`, erasing the value
    ///   of `recipient_account` while preserving whether the output is
    ///   wallet-owned (the `Some` / `None` distinction is retained).
    /// - `funding_account` is cleared to `None`, since a proposal does not
    ///   carry information about which account funded prior outputs.
    ///
    /// Used when constructing or reconstructing a [`Proposal`], whose
    /// transparent inputs are deliberately account-agnostic so that proposals
    /// can be wire-encoded and shared without revealing wallet account
    /// structure.
    ///
    /// [`Proposal`]: crate::proposal::Proposal
    #[cfg(feature = "transparent-inputs")]
    pub(crate) fn redact_account_data(self) -> WalletTransparentOutput<()> {
        WalletTransparentOutput {
            outpoint: self.outpoint,
            txout: self.txout,
            mined_height: self.mined_height,
            recipient_account: self.recipient_account.map(|_| ()),
            recipient_key_scope: self.recipient_key_scope,
            recipient_address: self.recipient_address,
            funding_account: None,
            known_input_size: self.known_input_size,
        }
    }

    /// Sets the known serialized input size for this output.
    ///
    /// This should be used for P2SH outputs where the wallet knows the redeem script
    /// and can compute the expected input size for fee calculation.
    pub fn with_known_input_size(mut self, size: usize) -> Self {
        self.known_input_size = Some(size);
        self
    }

    /// Returns the [`OutPoint`] corresponding to the output.
    pub fn outpoint(&self) -> &OutPoint {
        &self.outpoint
    }

    /// The index of the output in the transaction that created this output.
    pub fn index(&self) -> usize {
        self.outpoint.n() as usize
    }

    /// Returns the transaction output itself.
    pub fn txout(&self) -> &TxOut {
        &self.txout
    }

    /// Returns the height at which the UTXO was mined, if any.
    pub fn mined_height(&self) -> Option<BlockHeight> {
        self.mined_height
    }

    /// Returns the transparent key scope at which this address was derived, if known.
    ///
    /// This metadata MUST be returned for any transparent address derived by the wallet;
    /// this metadata is used by `propose_shielding` to ensure that shielding transactions
    /// do not inadvertently link ephemeral addresses to other wallet activity on-chain.
    pub fn recipient_key_scope(&self) -> Option<TransparentKeyScope> {
        self.recipient_key_scope
    }

    /// Returns the [`TransferType`] for this output, derived from the recipient,
    /// recipient-key-scope, and funding-account information stored on the output:
    ///
    /// - [`TransferType::Outgoing`] when [`recipient_account`](Self::recipient_account)
    ///   is `None` (the recipient is external to the wallet).
    /// - [`TransferType::AccountInternal`] when the recipient is a wallet account and
    ///   the output is a same-account self-transfer. This is detected either
    ///   structurally, when [`recipient_key_scope`](Self::recipient_key_scope) is
    ///   `INTERNAL` or `EPHEMERAL` (those key scopes exist only within a single
    ///   account), or by observation, when the recipient account is also the
    ///   [`funding_account`](Self::funding_account). The latter case also covers
    ///   standalone addresses, which have no key scope.
    /// - [`TransferType::WalletInternal`] when the recipient is a wallet account and
    ///   the [`funding_account`](Self::funding_account) is a different wallet account
    ///   (a cross-account transfer within the wallet).
    /// - [`TransferType::Incoming`] when the recipient is a wallet account and no
    ///   wallet funding account is known.
    pub fn transfer_type(&self) -> TransferType
    where
        AccountId: PartialEq,
    {
        match (
            self.recipient_account.as_ref(),
            self.recipient_key_scope,
            self.funding_account.as_ref(),
        ) {
            (None, _, _) => TransferType::Outgoing,
            (Some(_), Some(TransparentKeyScope::INTERNAL | TransparentKeyScope::EPHEMERAL), _) => {
                TransferType::AccountInternal
            }
            (Some(r), _, Some(r0)) if r == r0 => TransferType::AccountInternal,
            (Some(_), _, Some(_)) => TransferType::WalletInternal,
            (Some(_), _, _) => TransferType::Incoming,
        }
    }

    /// The identifier for the account that received this output, if known to belong to the
    /// wallet. Returns `None` for outputs sent to addresses outside the wallet.
    pub fn recipient_account(&self) -> Option<&AccountId> {
        self.recipient_account.as_ref()
    }

    /// Returns the wallet address that received the UTXO.
    pub fn recipient_address(&self) -> &TransparentAddress {
        &self.recipient_address
    }

    /// The identifier for the wallet account that provided funds in the transaction
    /// that created the output, if known.
    ///
    /// Note: the Zcash protocol permits construction of transactions where multiple distinct
    /// accounts provide funds; however, `zcash_client_backend` does not currently support the
    /// construction of transactions of this form. In cases where multiple funding accounts are
    /// detected, the account that provided the most significant source of funds should be selected
    /// if possible; in the future, this should be either expanded to support a set of funding
    /// accounts (which will require potentially invasive storage backend changes).
    pub fn funding_account(&self) -> Option<&AccountId> {
        self.funding_account.as_ref()
    }

    /// Returns the value of the UTXO
    pub fn value(&self) -> Zatoshis {
        self.txout.value()
    }
}

impl<AccountId: Debug> transparent_fees::InputView for WalletTransparentOutput<AccountId> {
    fn outpoint(&self) -> &OutPoint {
        &self.outpoint
    }
    fn coin(&self) -> &TxOut {
        &self.txout
    }
    fn serialized_size(&self) -> transparent_fees::InputSize {
        match self.known_input_size {
            Some(size) => transparent_fees::InputSize::Known(size),
            None => {
                // Fall back to default: only P2PKH is recognized.
                match zcash_script::script::PubKey::parse(&self.txout.script_pubkey().0)
                    .ok()
                    .as_ref()
                    .and_then(zcash_script::solver::standard)
                {
                    Some(zcash_script::solver::ScriptKind::PubKeyHash { .. }) => {
                        transparent_fees::InputSize::STANDARD_P2PKH
                    }
                    _ => transparent_fees::InputSize::Unknown(self.outpoint.clone()),
                }
            }
        }
    }
}

/// A reference to a spent note belonging to the wallet within a transaction.
#[derive(Clone)]
pub struct WalletSpend<Nf, AccountId> {
    index: usize,
    nf: Nf,
    account_id: AccountId,
}

impl<Nf, AccountId> WalletSpend<Nf, AccountId> {
    /// Constructs a `WalletSpend` from its constituent parts.
    pub fn from_parts(index: usize, nf: Nf, account_id: AccountId) -> Self {
        Self {
            index,
            nf,
            account_id,
        }
    }

    /// Returns the index of the Sapling spend or Orchard action within the transaction that
    /// created this spend.
    pub fn index(&self) -> usize {
        self.index
    }
    /// Returns the nullifier of the spent note.
    pub fn nf(&self) -> &Nf {
        &self.nf
    }
    /// Returns the identifier to the account_id to which the note belonged.
    pub fn account_id(&self) -> &AccountId {
        &self.account_id
    }
}

/// A type alias for Sapling [`WalletSpend`]s.
pub type WalletSaplingSpend<AccountId> = WalletSpend<sapling::Nullifier, AccountId>;

/// A type alias for Orchard [`WalletSpend`]s.
#[cfg(feature = "orchard")]
pub type WalletOrchardSpend<AccountId> = WalletSpend<orchard::note::Nullifier, AccountId>;

/// A type alias for Ironwood [`WalletSpend`]s.
///
/// Ironwood notes are Orchard-shaped and therefore share the Orchard nullifier type, but Ironwood
/// is a distinct pool from Orchard.
#[cfg(feature = "orchard")]
pub type WalletIronwoodSpend<AccountId> = WalletSpend<orchard::note::Nullifier, AccountId>;

/// An output that was successfully decrypted in the process of wallet scanning.
#[derive(Clone)]
pub struct WalletOutput<Note, Nullifier, AccountId> {
    index: usize,
    ephemeral_key: EphemeralKeyBytes,
    note: Note,
    is_change: bool,
    note_commitment_tree_position: Position,
    nf: Option<Nullifier>,
    account_id: AccountId,
    recipient_key_scope: Option<zip32::Scope>,
}

impl<Note, Nullifier, AccountId> WalletOutput<Note, Nullifier, AccountId> {
    /// Constructs a new `WalletOutput` value from its constituent parts.
    #[allow(clippy::too_many_arguments)]
    pub fn from_parts(
        index: usize,
        ephemeral_key: EphemeralKeyBytes,
        note: Note,
        is_change: bool,
        note_commitment_tree_position: Position,
        nf: Option<Nullifier>,
        account_id: AccountId,
        recipient_key_scope: Option<zip32::Scope>,
    ) -> Self {
        Self {
            index,
            ephemeral_key,
            note,
            is_change,
            note_commitment_tree_position,
            nf,
            account_id,
            recipient_key_scope,
        }
    }

    /// The index of the output or action in the transaction that created this output.
    pub fn index(&self) -> usize {
        self.index
    }
    /// The [`EphemeralKeyBytes`] used in the decryption of the note.
    pub fn ephemeral_key(&self) -> &EphemeralKeyBytes {
        &self.ephemeral_key
    }
    /// The note.
    pub fn note(&self) -> &Note {
        &self.note
    }
    /// A flag indicating whether the process of note decryption determined that this
    /// output should be classified as change.
    pub fn is_change(&self) -> bool {
        self.is_change
    }
    /// The position of the note in the global note commitment tree.
    pub fn note_commitment_tree_position(&self) -> Position {
        self.note_commitment_tree_position
    }
    /// The nullifier for the note, if the key used to decrypt the note was able to compute it.
    pub fn nf(&self) -> Option<&Nullifier> {
        self.nf.as_ref()
    }
    /// The identifier for the account to which the output belongs.
    pub fn account_id(&self) -> &AccountId {
        &self.account_id
    }
    /// The ZIP 32 scope for which the viewing key that decrypted this output was derived, if
    /// known.
    pub fn recipient_key_scope(&self) -> Option<zip32::Scope> {
        self.recipient_key_scope
    }
}

/// A subset of an [`OutputDescription`] relevant to wallets and light clients.
///
/// [`OutputDescription`]: sapling::bundle::OutputDescription
pub type WalletSaplingOutput<AccountId> =
    WalletOutput<sapling::Note, sapling::Nullifier, AccountId>;

/// The output part of an Orchard [`Action`] that was decrypted in the process of scanning.
///
/// [`Action`]: orchard::Action
#[cfg(feature = "orchard")]
pub type WalletOrchardOutput<AccountId> =
    WalletOutput<(orchard::note::Note, orchard::ValuePool), orchard::note::Nullifier, AccountId>;

/// The output part of an Ironwood [`Action`] that was decrypted in the process of scanning.
///
/// [`Action`]: orchard::Action
#[cfg(feature = "orchard")]
pub type WalletIronwoodOutput<AccountId> =
    WalletOutput<(orchard::note::Note, orchard::ValuePool), orchard::note::Nullifier, AccountId>;

/// An enumeration of supported shielded note types for use in [`ReceivedNote`]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Note {
    Sapling(sapling::Note),
    #[cfg(feature = "orchard")]
    Orchard {
        note: orchard::Note,
        pool: orchard::ValuePool,
    },
}

impl Note {
    /// Returns the receiver of this note.
    pub fn receiver(&self) -> Receiver {
        match self {
            Note::Sapling(n) => Receiver::Sapling(n.recipient()),
            #[cfg(feature = "orchard")]
            Note::Orchard { note, .. } => Receiver::Orchard(note.recipient()),
        }
    }

    pub fn value(&self) -> Zatoshis {
        match self {
            Note::Sapling(n) => n.value().inner().try_into().expect(
                "Sapling notes must have values in the range of valid non-negative ZEC values.",
            ),
            #[cfg(feature = "orchard")]
            Note::Orchard { note, .. } => Zatoshis::from_u64(note.value().inner()).expect(
                "Orchard notes must have values in the range of valid non-negative ZEC values.",
            ),
        }
    }

    /// Returns the shielded value pool to which this note belongs.
    pub fn pool(&self) -> ShieldedPool {
        match self {
            Note::Sapling(_) => ShieldedPool::Sapling,
            #[cfg(feature = "orchard")]
            Note::Orchard { pool, .. } => shielded_pool_for_value_pool(*pool),
        }
    }
}

/// Returns the shielded pool corresponding to an Orchard-protocol value pool. The Orchard protocol
/// serves both the Orchard pool (version-2 notes) and the Ironwood pool (version-3 notes); this is
/// the single point at which that classification is made.
#[cfg(feature = "orchard")]
pub(crate) fn shielded_pool_for_value_pool(pool: orchard::ValuePool) -> ShieldedPool {
    match pool {
        orchard::ValuePool::Orchard => ShieldedPool::Orchard,
        orchard::ValuePool::Ironwood => ShieldedPool::Ironwood,
    }
}

/// A note that was received by the wallet, along with contextual information about the output that
/// generated the note and the key that is required to spend it.
#[derive(Clone, PartialEq, Eq)]
pub struct ReceivedNote<NoteRef, NoteT> {
    note_id: NoteRef,
    txid: TxId,
    output_index: u16,
    note: NoteT,
    spending_key_scope: Scope,
    note_commitment_tree_position: Position,
    mined_height: Option<BlockHeight>,
    max_shielding_input_height: Option<BlockHeight>,
}

impl<NoteRef, NoteT> ReceivedNote<NoteRef, NoteT> {
    /// Constructs a new [`ReceivedNote`] from its constituent parts.
    #[allow(clippy::too_many_arguments)]
    pub fn from_parts(
        note_id: NoteRef,
        txid: TxId,
        output_index: u16,
        note: NoteT,
        spending_key_scope: Scope,
        note_commitment_tree_position: Position,
        mined_height: Option<BlockHeight>,
        max_shielding_input_height: Option<BlockHeight>,
    ) -> Self {
        ReceivedNote {
            note_id,
            txid,
            output_index,
            note,
            spending_key_scope,
            note_commitment_tree_position,
            mined_height,
            max_shielding_input_height,
        }
    }

    /// Returns the storage backend's internal identifier for the note.
    pub fn internal_note_id(&self) -> &NoteRef {
        &self.note_id
    }
    /// Returns the txid of the transaction that constructed the note.
    pub fn txid(&self) -> &TxId {
        &self.txid
    }
    /// Returns the output index of the note within the transaction, according to the note's
    /// shielded protocol.
    pub fn output_index(&self) -> u16 {
        self.output_index
    }
    /// Returns the note data.
    pub fn note(&self) -> &NoteT {
        &self.note
    }
    /// Returns the [`Scope`] of the spending key required to make spend authorizing signatures for
    /// the note.
    pub fn spending_key_scope(&self) -> Scope {
        self.spending_key_scope
    }
    /// Returns the position of the note in the note commitment tree.
    pub fn note_commitment_tree_position(&self) -> Position {
        self.note_commitment_tree_position
    }
    /// Returns the block height at which the transaction that produced the note was mined.
    pub fn mined_height(&self) -> Option<BlockHeight> {
        self.mined_height
    }
    /// Returns the maximum block height among those at which transparent inputs to the transaction
    /// that produced the note were created, considering only transparent inputs that belong to the
    /// same wallet account as the note. This height is used in determining the effective number of
    /// confirmations for externally-received value. See [`ZIP 315`] for additional information.
    ///
    /// [`ZIP 315`]: https://zips.z.cash/zip-0315
    pub fn max_shielding_input_height(&self) -> Option<BlockHeight> {
        self.max_shielding_input_height
    }

    /// Map over the `note` field of this data structure.
    ///
    /// Consume this value, applying the provided function to the value of its `note` field and
    /// returning a new `ReceivedNote` with the result as its `note` field value.
    pub fn map_note<N, F: Fn(NoteT) -> N>(self, f: F) -> ReceivedNote<NoteRef, N> {
        ReceivedNote {
            note_id: self.note_id,
            txid: self.txid,
            output_index: self.output_index,
            note: f(self.note),
            spending_key_scope: self.spending_key_scope,
            note_commitment_tree_position: self.note_commitment_tree_position,
            mined_height: self.mined_height,
            max_shielding_input_height: self.max_shielding_input_height,
        }
    }
}

impl<NoteRef: Debug> Debug for ReceivedNote<NoteRef, sapling::Note> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ReceivedNote")
            .field("note_id", &self.note_id)
            .field("txid", &self.txid)
            .field("output_index", &self.output_index)
            .field("note_value", &self.note_value())
            .field("spending_key_scope", &self.spending_key_scope)
            .field(
                "note_commitment_tree_position",
                &self.note_commitment_tree_position,
            )
            .field("mined_height", &self.mined_height)
            .finish()
    }
}

#[cfg(feature = "orchard")]
impl<NoteRef: Debug> Debug for ReceivedNote<NoteRef, orchard::note::Note> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ReceivedNote")
            .field("note_id", &self.note_id)
            .field("txid", &self.txid)
            .field("output_index", &self.output_index)
            .field("note_value", &self.note_value())
            .field("spending_key_scope", &self.spending_key_scope)
            .field(
                "note_commitment_tree_position",
                &self.note_commitment_tree_position,
            )
            .field("mined_height", &self.mined_height)
            .finish()
    }
}

impl<NoteRef> ReceivedNote<NoteRef, sapling::Note> {
    pub fn note_value(&self) -> Result<Zatoshis, BalanceError> {
        self.note.value().inner().try_into()
    }
}

#[cfg(feature = "orchard")]
impl<NoteRef> ReceivedNote<NoteRef, orchard::note::Note> {
    pub fn note_value(&self) -> Result<Zatoshis, BalanceError> {
        self.note.value().inner().try_into()
    }
}

impl<NoteRef> sapling_fees::InputView<NoteRef> for (NoteRef, sapling::value::NoteValue) {
    fn note_id(&self) -> &NoteRef {
        &self.0
    }

    fn value(&self) -> Zatoshis {
        self.1
            .inner()
            .try_into()
            .expect("Sapling note values are indirectly checked by consensus.")
    }
}

impl<NoteRef> sapling_fees::InputView<NoteRef> for ReceivedNote<NoteRef, sapling::Note> {
    fn note_id(&self) -> &NoteRef {
        &self.note_id
    }

    fn value(&self) -> Zatoshis {
        self.note
            .value()
            .inner()
            .try_into()
            .expect("Sapling note values are indirectly checked by consensus.")
    }
}

#[cfg(feature = "orchard")]
impl<NoteRef> orchard_fees::InputView<NoteRef> for (NoteRef, orchard::value::NoteValue) {
    fn note_id(&self) -> &NoteRef {
        &self.0
    }

    fn value(&self) -> Zatoshis {
        self.1
            .inner()
            .try_into()
            .expect("Orchard note values are indirectly checked by consensus.")
    }
}

#[cfg(feature = "orchard")]
impl<NoteRef> orchard_fees::InputView<NoteRef> for ReceivedNote<NoteRef, orchard::Note> {
    fn note_id(&self) -> &NoteRef {
        &self.note_id
    }

    fn value(&self) -> Zatoshis {
        self.note
            .value()
            .inner()
            .try_into()
            .expect("Orchard note values are indirectly checked by consensus.")
    }
}

/// Describes a policy for which outgoing viewing key should be able to decrypt
/// transaction outputs.
///
/// For details on what transaction information is visible to the holder of an outgoing
/// viewing key, refer to [ZIP 310].
///
/// [ZIP 310]: https://zips.z.cash/zip-0310
#[derive(Debug, Clone)]
pub enum OvkPolicy {
    /// Use an outgoing viewing key produced from the sender's [`UnifiedFullViewingKey`],
    /// selected via the policy documented in [`UnifiedFullViewingKey::select_ovk`].
    ///
    /// External transaction outputs will be decryptable by the sender, in addition to the
    /// recipients. Wallet-internal transaction outputs will be decryptable only with the wallet's
    /// internal-scoped incoming viewing key.
    ///
    /// [`UnifiedFullViewingKey`]: zcash_keys::keys::UnifiedFullViewingKey
    /// [`UnifiedFullViewingKey::select_ovk`]: zcash_keys::keys::UnifiedFullViewingKey::select_ovk
    Sender,

    /// Use custom outgoing viewing keys. These might for instance be derived from a
    /// different seed than the wallet's spending keys.
    ///
    /// Transaction outputs will be decryptable by the recipients, and whoever controls
    /// the provided outgoing viewing keys.
    Custom {
        external_ovk: OutgoingViewingKey,
        internal_ovk: Option<OutgoingViewingKey>,
    },
    /// Use no outgoing viewing keys. Transaction outputs will be decryptable by their
    /// recipients, but not by the sender.
    Discard,
}

impl OvkPolicy {
    /// Constructs an [`OvkPolicy::Custom`] value from a single arbitrary 32-byte key with both the
    /// external_ovk and internal_ovk components set to the same key.
    ///
    /// Outputs of transactions created with this OVK policy will be recoverable using this key
    /// irrespective of whether they are external outputs or wallet-internal change outputs.
    pub fn custom_from_common_bytes(key: &[u8; 32]) -> Self {
        let k = OutgoingViewingKey::from(*key);
        OvkPolicy::Custom {
            external_ovk: k,
            internal_ovk: Some(k),
        }
    }
}

/// Metadata describing the gap limit position of a transparent address.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg(feature = "transparent-inputs")]
pub enum GapMetadata {
    /// The address, or an address at a greater child index, has received transparent funds and
    /// will be discovered by wallet recovery by exploration over the space of
    /// [`NonHardenedChildIndex`]es using the provided gap limit.
    GapRecoverable { gap_limit: u32 },
    /// The address exists within an address gap of the given limit size, and will be discovered by
    /// wallet recovery by exploration using the provided gap limit. In the view of the wallet, no
    /// addresses at the given position or greater (up to the gap limit) have received funds. The
    /// number of addresses remaining within the gap limit before no additional addresses can be
    /// allocated is given by `gap_limit - (gap_position + 1)`.
    InGap {
        /// A zero-based index over the child indices in the gap.
        gap_position: u32,
        /// The maximum number of sequential child indices that can be allocated to addresses
        /// without any of those addresses having received funds.
        gap_limit: u32,
    },
    /// The wallet does not contain derivation information for the associated address, and so its
    /// relationship to other addresses in the wallet cannot be determined.
    DerivationUnknown,
}

/// Metadata describing whether and when a transparent address was exposed by the wallet.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg(feature = "transparent-inputs")]
pub enum Exposure {
    /// The address has been exposed by the wallet.
    Exposed {
        /// The address was first exposed to the wider ecosystem at this height, to the best
        /// of our knowledge.
        ///
        /// - For user-generated addresses, this is the chain tip height at the time that the
        ///   address was generated by an explicit request by the user or reserved for use in
        ///   a ZIP 320 transaction. These heights are not recoverable from chain.
        /// - In the case of an address with its first use discovered in a transaction
        ///   obtained by scanning the chain, this will be set to the mined height of that
        ///   transaction. In recover from seed cases, this is what user-generated addresses
        ///   will be assigned.
        at_height: BlockHeight,
        /// Transparent address gap metadata, as of the time the query that produced this exposure
        /// metadata was executed.
        gap_metadata: GapMetadata,
    },
    /// The address is not known to have been exposed to an external caller by the wallet.
    ///
    /// The wallet makes its determination based on observed chain data and inference from
    /// standard wallet address generation patterns. In particular, this is the state that
    /// an address is in when it has been generated by the advancement of the transparent
    /// address gap. This judgement may be incorrect for restored wallets.
    Unknown,
    /// It is not possible for the wallet to determine whether the address has been exposed,
    /// given the information the wallet has access to.
    CannotKnow,
}

/// Information about a transparent address controlled by the wallet.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg(feature = "transparent-inputs")]
pub struct TransparentAddressMetadata {
    source: TransparentAddressSource,
    exposure: Exposure,
    next_check_time: Option<SystemTime>,
}

#[cfg(feature = "transparent-inputs")]
impl TransparentAddressMetadata {
    /// Constructs a new [`TransparentAddressMetadata`] value from its constituent parts.
    pub fn new(
        source: TransparentAddressSource,
        exposure: Exposure,
        next_check_time: Option<SystemTime>,
    ) -> Self {
        Self {
            source,
            exposure,
            next_check_time,
        }
    }

    /// Returns a [`TransparentAddressMetadata`] with [`TransparentAddressSource::Derived`] source
    /// information and the specified exposure height.
    pub fn derived(
        scope: TransparentKeyScope,
        address_index: NonHardenedChildIndex,
        exposure: Exposure,
        next_check_time: Option<SystemTime>,
    ) -> Self {
        Self {
            source: TransparentAddressSource::Derived {
                scope,
                address_index,
            },
            exposure,
            next_check_time,
        }
    }

    /// Returns a [`TransparentAddressMetadata`] with [`TransparentAddressSource::StandalonePubkey`]
    /// source information for a P2PKH address and the specified exposure height.
    #[cfg(feature = "transparent-key-import")]
    pub fn standalone_p2pkh(
        pubkey: secp256k1::PublicKey,
        exposure: Exposure,
        next_check_time: Option<SystemTime>,
    ) -> Self {
        Self {
            source: TransparentAddressSource::StandalonePubkey(pubkey),
            exposure,
            next_check_time,
        }
    }

    /// Returns a [`TransparentAddressMetadata`] with [`TransparentAddressSource::StandaloneScript`]
    /// source information for a P2SH address and the specified exposure height.
    #[cfg(feature = "transparent-key-import")]
    pub fn standalone_script(
        redeem_script: script::Redeem,
        exposure: Exposure,
        next_check_time: Option<SystemTime>,
    ) -> Self {
        Self {
            source: TransparentAddressSource::StandaloneScript(redeem_script),
            exposure,
            next_check_time,
        }
    }

    /// Returns the source metadata for the address.
    pub fn source(&self) -> &TransparentAddressSource {
        &self.source
    }

    /// Returns the exposure metadata for this transparent address.
    pub fn exposure(&self) -> Exposure {
        self.exposure
    }

    /// Returns a copy of this metadata, with its exposure metadata updated
    pub fn with_exposure_at(
        &self,
        exposure_height: BlockHeight,
        gap_metadata: GapMetadata,
    ) -> Self {
        Self {
            source: self.source.clone(),
            exposure: Exposure::Exposed {
                at_height: exposure_height,
                gap_metadata,
            },
            next_check_time: self.next_check_time,
        }
    }

    /// Returns the timestamp of the earliest time that the light wallet server may be queried for
    /// UTXOs associated with this address, or `None` if the wallet backend is not placing any
    /// restrictions on when this address can be queried. Unless the wallet application is
    /// requesting address information from a light wallet server that is trusted for privacy,
    /// only one such query should be performed at a time, to avoid linking multiple transparent
    /// addresses as belonging to the same wallet in the view of the light wallet server.
    pub fn next_check_time(&self) -> Option<SystemTime> {
        self.next_check_time
    }

    /// Returns the [`TransparentKeyScope`] of the private key from which the address was derived,
    /// if known. Returns `None` for standalone addresses in the wallet.
    pub fn scope(&self) -> Option<TransparentKeyScope> {
        self.source.scope()
    }

    /// Returns the BIP 44 [`NonHardenedChildIndex`] at which the address was derived, if known.
    /// Returns `None` for standalone addresses in the wallet.
    pub fn address_index(&self) -> Option<NonHardenedChildIndex> {
        self.source.address_index()
    }

    /// Returns the redeem script for the address, if this is a P2SH address.
    /// Returns `None` for non-P2SH addresses.
    #[cfg(feature = "transparent-key-import")]
    pub fn redeem_script(&self) -> Option<&script::Redeem> {
        self.source.redeem_script()
    }
}

/// Source information for a transparent address.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg(feature = "transparent-inputs")]
pub enum TransparentAddressSource {
    /// BIP 44 path derivation information for the address below account pubkey level, i.e. the
    /// `change` and `index` elements of the path.
    Derived {
        scope: TransparentKeyScope,
        address_index: NonHardenedChildIndex,
    },

    /// The address was derived from a secp256k1 public key for which derivation information is
    /// unknown or for which the associated spending key was produced from system randomness.
    /// This variant provides the public key directly.
    #[cfg(feature = "transparent-key-import")]
    StandalonePubkey(secp256k1::PublicKey),

    /// The address was derived from a P2SH redeem_script for which derivation information is
    /// unknown.
    /// This variant provides the redeem script directly.
    #[cfg(feature = "transparent-key-import")]
    StandaloneScript(script::Redeem),
}

#[cfg(feature = "transparent-inputs")]
impl TransparentAddressSource {
    /// Returns the [`TransparentKeyScope`] of the private key from which the address was derived,
    /// if known. Returns `None` for standalone addresses in the wallet.
    pub fn scope(&self) -> Option<TransparentKeyScope> {
        match self {
            TransparentAddressSource::Derived { scope, .. } => Some(*scope),
            #[cfg(feature = "transparent-key-import")]
            TransparentAddressSource::StandalonePubkey(_) => None,
            #[cfg(feature = "transparent-key-import")]
            TransparentAddressSource::StandaloneScript(_) => None,
        }
    }

    /// Returns the BIP 44 [`NonHardenedChildIndex`] at which the address was derived, if known.
    /// Returns `None` for standalone addresses in the wallet.
    pub fn address_index(&self) -> Option<NonHardenedChildIndex> {
        match self {
            TransparentAddressSource::Derived { address_index, .. } => Some(*address_index),
            #[cfg(feature = "transparent-key-import")]
            TransparentAddressSource::StandalonePubkey(_) => None,
            #[cfg(feature = "transparent-key-import")]
            TransparentAddressSource::StandaloneScript(_) => None,
        }
    }

    /// Returns the redeem script for the address, if this is a P2SH address.
    /// Returns `None` for non-P2SH addresses.
    #[cfg(feature = "transparent-key-import")]
    pub fn redeem_script(&self) -> Option<&script::Redeem> {
        match self {
            TransparentAddressSource::Derived { .. } => None,
            #[cfg(feature = "transparent-key-import")]
            TransparentAddressSource::StandalonePubkey(_) => None,
            #[cfg(feature = "transparent-key-import")]
            TransparentAddressSource::StandaloneScript(redeem_script) => Some(redeem_script),
        }
    }
}

/// Property tests for [`OutputRef`], whose identity (txid, pool, output index) is the key the
/// note-locking tables and the proposal double-spend check operate on.
#[cfg(test)]
mod output_ref_tests {
    use proptest::prelude::*;
    use zcash_protocol::{PoolType, ShieldedPool, TxId};

    use super::{NoteId, OutputRef};

    fn arb_shielded_pool() -> impl Strategy<Value = ShieldedPool> {
        prop_oneof![
            Just(ShieldedPool::Sapling),
            Just(ShieldedPool::Orchard),
            Just(ShieldedPool::Ironwood),
        ]
    }

    fn arb_pool_type() -> impl Strategy<Value = PoolType> {
        prop_oneof![
            Just(PoolType::Transparent),
            arb_shielded_pool().prop_map(PoolType::Shielded),
        ]
    }

    fn arb_output_ref() -> impl Strategy<Value = OutputRef> {
        (any::<[u8; 32]>(), arb_pool_type(), any::<u32>())
            .prop_map(|(txid, pool, idx)| OutputRef::new(TxId::from_bytes(txid), pool, idx))
    }

    proptest! {
        /// Converting a `NoteId` preserves every component: the note's pool maps into the
        /// shielded arm of `PoolType`, and the `u16` output index widens losslessly.
        #[test]
        fn from_note_id_preserves_fields(
            txid in any::<[u8; 32]>(),
            pool in arb_shielded_pool(),
            idx in any::<u16>(),
        ) {
            let txid = TxId::from_bytes(txid);
            let output_ref = OutputRef::from(NoteId::new(txid, pool, idx));
            prop_assert_eq!(output_ref.txid(), &txid);
            prop_assert_eq!(output_ref.pool(), PoolType::Shielded(pool));
            prop_assert_eq!(output_ref.output_index(), u32::from(idx));
        }

        /// Identity is exactly the (txid, pool, output index) triple: a reference equals
        /// itself, differs from any single-field mutation of itself, and `Ord` agrees with
        /// `Eq` (the `BTreeSet` double-spend check in proposal construction and the lock
        /// tables both rely on this).
        #[test]
        fn identity_is_the_full_triple(a in arb_output_ref()) {
            prop_assert_eq!(a, a);
            prop_assert_eq!(a.cmp(&a), std::cmp::Ordering::Equal);

            // A different output index is a different output.
            let other_index = OutputRef::new(
                *a.txid(),
                a.pool(),
                a.output_index().wrapping_add(1),
            );
            prop_assert_ne!(a, other_index);
            prop_assert_ne!(a.cmp(&other_index), std::cmp::Ordering::Equal);

            // A different pool is a different output, even at the same (txid, index): the
            // same transaction may have outputs at the same index in several pools.
            let other_pool = OutputRef::new(
                *a.txid(),
                match a.pool() {
                    PoolType::Transparent => PoolType::SAPLING,
                    PoolType::Shielded(_) => PoolType::Transparent,
                },
                a.output_index(),
            );
            prop_assert_ne!(a, other_pool);
            prop_assert_ne!(a.cmp(&other_pool), std::cmp::Ordering::Equal);

            // A different transaction is a different output.
            let mut txid = <[u8; 32]>::from(*a.txid());
            txid[0] = txid[0].wrapping_add(1);
            let other_txid = OutputRef::new(TxId::from_bytes(txid), a.pool(), a.output_index());
            prop_assert_ne!(a, other_txid);
            prop_assert_ne!(a.cmp(&other_txid), std::cmp::Ordering::Equal);
        }

        /// Two independently drawn references are equal exactly when all three components
        /// match.
        #[test]
        fn equality_is_component_wise(a in arb_output_ref(), b in arb_output_ref()) {
            let components_equal = a.txid() == b.txid()
                && a.pool() == b.pool()
                && a.output_index() == b.output_index();
            prop_assert_eq!(a == b, components_equal);
        }
    }
}