zcash_client_backend/wallet.rs
1//! Structs representing transaction data scanned from the block chain by a wallet or
2//! light client.
3use std::fmt::Debug;
4
5use incrementalmerkletree::Position;
6
7use ::transparent::{
8 address::TransparentAddress,
9 bundle::{OutPoint, TxOut},
10};
11use zcash_address::ZcashAddress;
12use zcash_keys::{
13 address::Receiver,
14 keys::{OutgoingViewingKey, transparent::TransparentKeyScope},
15};
16use zcash_note_encryption::EphemeralKeyBytes;
17use zcash_primitives::transaction::{TxId, fees::transparent as transparent_fees};
18use zcash_protocol::{
19 PoolType, ShieldedPool,
20 consensus::{BlockHeight, TxIndex},
21 value::{BalanceError, Zatoshis},
22};
23#[cfg(feature = "transparent-inputs")]
24use zcash_script::script;
25use zip32::Scope;
26
27use crate::{TransferType, fees::sapling as sapling_fees};
28
29#[cfg(feature = "orchard")]
30use crate::fees::orchard as orchard_fees;
31
32#[cfg(feature = "transparent-inputs")]
33use {std::time::SystemTime, zcash_keys::keys::transparent::NonHardenedChildIndex};
34
35/// A unique identifier for a shielded transaction output
36#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
37pub struct NoteId {
38 txid: TxId,
39 protocol: ShieldedPool,
40 output_index: u16,
41}
42
43impl NoteId {
44 /// Constructs a new `NoteId` from its parts.
45 pub fn new(txid: TxId, protocol: ShieldedPool, output_index: u16) -> Self {
46 Self {
47 txid,
48 protocol,
49 output_index,
50 }
51 }
52
53 /// Returns the ID of the transaction containing this note.
54 pub fn txid(&self) -> &TxId {
55 &self.txid
56 }
57
58 /// Returns the shielded protocol used by this note.
59 pub fn protocol(&self) -> ShieldedPool {
60 self.protocol
61 }
62
63 /// Returns the index of this note within its transaction's corresponding list of
64 /// shielded outputs.
65 pub fn output_index(&self) -> u16 {
66 self.output_index
67 }
68}
69
70/// A reference to a transaction output received by the wallet, across all pools.
71#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
72pub struct OutputRef {
73 txid: TxId,
74 pool: PoolType,
75 output_index: u32,
76}
77
78impl OutputRef {
79 /// Constructs a new `OutputRef` from its parts.
80 pub fn new(txid: TxId, pool: PoolType, output_index: u32) -> Self {
81 Self {
82 txid,
83 pool,
84 output_index,
85 }
86 }
87
88 /// Returns the ID of the transaction containing this output.
89 pub fn txid(&self) -> &TxId {
90 &self.txid
91 }
92
93 /// Returns the pool type of this output.
94 pub fn pool(&self) -> PoolType {
95 self.pool
96 }
97
98 /// Returns the index of this output within its transaction.
99 pub fn output_index(&self) -> u32 {
100 self.output_index
101 }
102}
103
104impl From<NoteId> for OutputRef {
105 fn from(note_id: NoteId) -> Self {
106 Self {
107 txid: note_id.txid,
108 pool: PoolType::Shielded(note_id.protocol),
109 output_index: note_id.output_index.into(),
110 }
111 }
112}
113
114pub use crate::data_api::locking::LockOwner;
115
116/// A type that represents the recipient of a transaction output.
117///
118/// Variants vary along two independent axes:
119///
120/// * **Relationship to the wallet**: whether the recipient address is [`Self::External`] to
121/// the wallet, an [`Self::EphemeralTransparent`] address of a wallet account (used
122/// transiently as a middle hop), or otherwise internal to a wallet account (recorded as
123/// [`Self::InternalShielded`] or [`Self::InternalTransparent`], depending on payload
124/// domain).
125/// * **Payload domain**: whether the output is shielded (in which case what is recorded is
126/// the decrypted [`Note`], since the recipient address is not itself externally
127/// meaningful) or transparent (in which case what is recorded is the on-chain-observable
128/// recipient address, since transparent outputs carry no analogous decryptable payload).
129#[derive(Debug, Clone, PartialEq, Eq)]
130pub enum Recipient<AccountId> {
131 /// An output sent to a recipient external to the wallet.
132 External {
133 recipient_address: ZcashAddress,
134 output_pool: PoolType,
135 },
136 /// A transparent output sent to an ephemeral address of a wallet account
137 /// (e.g. the middle hop of a ZIP 320 / TEX flow). The `outpoint` is
138 /// recorded so the wallet can later detect when this output is spent
139 /// without relying on a continuous address watch.
140 #[cfg(feature = "transparent-inputs")]
141 EphemeralTransparent {
142 receiving_account: AccountId,
143 ephemeral_address: TransparentAddress,
144 outpoint: OutPoint,
145 },
146 /// A transparent output sent to a non-ephemeral transparent address belonging to
147 /// a wallet account. Used to record the send side of a transparent output that
148 /// the wallet both funded and received.
149 ///
150 /// Distinct from [`Self::InternalShielded`] because for transparent outputs
151 /// the recipient address is observable on chain and must be recorded;
152 /// additionally, the receiving account may not be known at the point the
153 /// send is recorded. For shielded outputs the recipient address is not
154 /// externally meaningful, so wallet-internal sends are recorded against
155 /// the receiving account alone.
156 #[cfg(feature = "transparent-inputs")]
157 InternalTransparent {
158 receiving_account: AccountId,
159 recipient_address: TransparentAddress,
160 },
161 /// A shielded output recorded against a wallet account. Used for
162 /// same-account outputs such as change (`external_address` is `None`) and
163 /// for outputs received via an external IVK but funded by another wallet
164 /// account, in which case `external_address` is the address that was paid.
165 InternalShielded {
166 receiving_account: AccountId,
167 external_address: Option<ZcashAddress>,
168 note: Box<Note>,
169 },
170}
171
172/// The shielded subset of a [`Transaction`]'s data that is relevant to a particular wallet.
173///
174/// [`Transaction`]: zcash_primitives::transaction::Transaction
175#[derive(Clone)]
176pub struct WalletTx<AccountId> {
177 txid: TxId,
178 block_index: TxIndex,
179 transparent_spends: Vec<WalletTransparentSpend<AccountId>>,
180 transparent_outputs: Vec<WalletTransparentOutput<AccountId>>,
181 #[cfg(feature = "transparent-inputs")]
182 transparent_address_observations: Vec<TransparentAddressObservation>,
183 sapling_spends: Vec<WalletSaplingSpend<AccountId>>,
184 sapling_outputs: Vec<WalletSaplingOutput<AccountId>>,
185 #[cfg(feature = "orchard")]
186 orchard_spends: Vec<WalletOrchardSpend<AccountId>>,
187 #[cfg(feature = "orchard")]
188 orchard_outputs: Vec<WalletOrchardOutput<AccountId>>,
189 #[cfg(feature = "orchard")]
190 ironwood_spends: Vec<WalletIronwoodSpend<AccountId>>,
191 #[cfg(feature = "orchard")]
192 ironwood_outputs: Vec<WalletIronwoodOutput<AccountId>>,
193}
194
195impl<AccountId> WalletTx<AccountId> {
196 /// Constructs a new [`WalletTx`] from its constituent parts.
197 #[allow(clippy::too_many_arguments)]
198 pub fn new(
199 txid: TxId,
200 block_index: TxIndex,
201 transparent_spends: Vec<WalletTransparentSpend<AccountId>>,
202 transparent_outputs: Vec<WalletTransparentOutput<AccountId>>,
203 #[cfg(feature = "transparent-inputs")] transparent_address_observations: Vec<
204 TransparentAddressObservation,
205 >,
206 sapling_spends: Vec<WalletSaplingSpend<AccountId>>,
207 sapling_outputs: Vec<WalletSaplingOutput<AccountId>>,
208 #[cfg(feature = "orchard")] orchard_spends: Vec<
209 WalletSpend<orchard::note::Nullifier, AccountId>,
210 >,
211 #[cfg(feature = "orchard")] orchard_outputs: Vec<WalletOrchardOutput<AccountId>>,
212 #[cfg(feature = "orchard")] ironwood_spends: Vec<
213 WalletSpend<orchard::note::Nullifier, AccountId>,
214 >,
215 #[cfg(feature = "orchard")] ironwood_outputs: Vec<WalletIronwoodOutput<AccountId>>,
216 ) -> Self {
217 Self {
218 txid,
219 block_index,
220 transparent_spends,
221 transparent_outputs,
222 #[cfg(feature = "transparent-inputs")]
223 transparent_address_observations,
224 sapling_spends,
225 sapling_outputs,
226 #[cfg(feature = "orchard")]
227 orchard_spends,
228 #[cfg(feature = "orchard")]
229 orchard_outputs,
230 #[cfg(feature = "orchard")]
231 ironwood_spends,
232 #[cfg(feature = "orchard")]
233 ironwood_outputs,
234 }
235 }
236
237 /// Returns the [`TxId`] for the corresponding [`Transaction`].
238 ///
239 /// [`Transaction`]: zcash_primitives::transaction::Transaction
240 pub fn txid(&self) -> TxId {
241 self.txid
242 }
243
244 /// Returns the index of the transaction in the containing block.
245 pub fn block_index(&self) -> TxIndex {
246 self.block_index
247 }
248
249 /// Returns a record for each transparent output belonging to the wallet that was spent in
250 /// the transaction.
251 pub fn transparent_spends(&self) -> &[WalletTransparentSpend<AccountId>] {
252 &self.transparent_spends
253 }
254
255 /// Returns a record for each transparent coin received or produced by the wallet.
256 pub fn transparent_outputs(&self) -> &[WalletTransparentOutput<AccountId>] {
257 &self.transparent_outputs
258 }
259
260 /// Returns a record of every transparent address that this transaction's transparent data
261 /// names, whether or not the wallet controls it.
262 ///
263 /// The set covers only the involvement directions the data this record was built from can
264 /// express: scanning a compact block yields output observations, since a compact input
265 /// carries no `scriptSig` and so names no address, while scanning a full block yields both
266 /// directions.
267 #[cfg(feature = "transparent-inputs")]
268 pub fn transparent_address_observations(&self) -> &[TransparentAddressObservation] {
269 &self.transparent_address_observations
270 }
271
272 /// Returns a record for each Sapling note belonging to the wallet that was spent in the
273 /// transaction.
274 pub fn sapling_spends(&self) -> &[WalletSaplingSpend<AccountId>] {
275 self.sapling_spends.as_ref()
276 }
277
278 /// Returns a record for each Sapling note received or produced by the wallet in the
279 /// transaction.
280 pub fn sapling_outputs(&self) -> &[WalletSaplingOutput<AccountId>] {
281 self.sapling_outputs.as_ref()
282 }
283
284 /// Returns a record for each Orchard note belonging to the wallet that was spent in the
285 /// transaction.
286 #[cfg(feature = "orchard")]
287 pub fn orchard_spends(&self) -> &[WalletOrchardSpend<AccountId>] {
288 self.orchard_spends.as_ref()
289 }
290
291 /// Returns a record for each Orchard note received or produced by the wallet in the
292 /// transaction.
293 #[cfg(feature = "orchard")]
294 pub fn orchard_outputs(&self) -> &[WalletOrchardOutput<AccountId>] {
295 self.orchard_outputs.as_ref()
296 }
297
298 /// Returns a record for each Ironwood note belonging to the wallet that was spent in the
299 /// transaction.
300 #[cfg(feature = "orchard")]
301 pub fn ironwood_spends(&self) -> &[WalletIronwoodSpend<AccountId>] {
302 self.ironwood_spends.as_ref()
303 }
304
305 /// Returns a record for each Ironwood note received or produced by the wallet in the
306 /// transaction.
307 #[cfg(feature = "orchard")]
308 pub fn ironwood_outputs(&self) -> &[WalletIronwoodOutput<AccountId>] {
309 self.ironwood_outputs.as_ref()
310 }
311}
312
313/// A transparent output controlled by the wallet.
314#[derive(Debug, Clone, PartialEq, Eq)]
315pub struct WalletTransparentOutput<AccountId> {
316 outpoint: OutPoint,
317 txout: TxOut<Zatoshis>,
318 mined_height: Option<BlockHeight>,
319 recipient_account: Option<AccountId>,
320 recipient_key_scope: Option<TransparentKeyScope>,
321 recipient_address: TransparentAddress,
322 funding_account: Option<AccountId>,
323 /// The known serialized input size for this output, if available.
324 /// This is set for P2SH outputs where the redeem script is known.
325 known_input_size: Option<usize>,
326}
327
328impl<AccountId> WalletTransparentOutput<AccountId> {
329 /// Constructs a new [`WalletTransparentOutput`] from its constituent parts.
330 ///
331 /// Returns `None` if the recipient address for the provided [`TxOut`] cannot be
332 /// determined based on the set of output script patterns understood by this wallet.
333 pub fn from_parts(
334 outpoint: OutPoint,
335 txout: TxOut<Zatoshis>,
336 mined_height: Option<BlockHeight>,
337 recipient_account: Option<AccountId>,
338 recipient_key_scope: Option<TransparentKeyScope>,
339 funding_account: Option<AccountId>,
340 ) -> Option<Self> {
341 txout
342 .recipient_address()
343 .map(|recipient_address| WalletTransparentOutput {
344 outpoint,
345 txout,
346 mined_height,
347 recipient_account,
348 recipient_key_scope,
349 recipient_address,
350 funding_account,
351 known_input_size: None,
352 })
353 }
354
355 /// Returns a copy of this output with account-identifying data redacted,
356 /// for inclusion in a [`Proposal`].
357 ///
358 /// Specifically:
359 /// - The `AccountId` type parameter is replaced with `()`, erasing the value
360 /// of `recipient_account` while preserving whether the output is
361 /// wallet-owned (the `Some` / `None` distinction is retained).
362 /// - `funding_account` is cleared to `None`, since a proposal does not
363 /// carry information about which account funded prior outputs.
364 ///
365 /// Used when constructing or reconstructing a [`Proposal`], whose
366 /// transparent inputs are deliberately account-agnostic so that proposals
367 /// can be wire-encoded and shared without revealing wallet account
368 /// structure.
369 ///
370 /// [`Proposal`]: crate::proposal::Proposal
371 #[cfg(feature = "transparent-inputs")]
372 pub(crate) fn redact_account_data(self) -> WalletTransparentOutput<()> {
373 WalletTransparentOutput {
374 outpoint: self.outpoint,
375 txout: self.txout,
376 mined_height: self.mined_height,
377 recipient_account: self.recipient_account.map(|_| ()),
378 recipient_key_scope: self.recipient_key_scope,
379 recipient_address: self.recipient_address,
380 funding_account: None,
381 known_input_size: self.known_input_size,
382 }
383 }
384
385 /// Sets the known serialized input size for this output.
386 ///
387 /// This should be used for P2SH outputs where the wallet knows the redeem script
388 /// and can compute the expected input size for fee calculation.
389 pub fn with_known_input_size(mut self, size: usize) -> Self {
390 self.known_input_size = Some(size);
391 self
392 }
393
394 /// Returns the [`OutPoint`] corresponding to the output.
395 pub fn outpoint(&self) -> &OutPoint {
396 &self.outpoint
397 }
398
399 /// The index of the output in the transaction that created this output.
400 pub fn index(&self) -> usize {
401 self.outpoint.n() as usize
402 }
403
404 /// Returns the transaction output itself.
405 pub fn txout(&self) -> &TxOut<Zatoshis> {
406 &self.txout
407 }
408
409 /// Returns the height at which the UTXO was mined, if any.
410 pub fn mined_height(&self) -> Option<BlockHeight> {
411 self.mined_height
412 }
413
414 /// Returns the transparent key scope at which this address was derived, if known.
415 ///
416 /// This metadata MUST be returned for any transparent address derived by the wallet;
417 /// this metadata is used by `propose_shielding` to ensure that shielding transactions
418 /// do not inadvertently link ephemeral addresses to other wallet activity on-chain.
419 pub fn recipient_key_scope(&self) -> Option<TransparentKeyScope> {
420 self.recipient_key_scope
421 }
422
423 /// Returns the [`TransferType`] for this output, derived from the recipient,
424 /// recipient-key-scope, and funding-account information stored on the output:
425 ///
426 /// - [`TransferType::Outgoing`] when [`recipient_account`](Self::recipient_account)
427 /// is `None` (the recipient is external to the wallet).
428 /// - [`TransferType::AccountInternal`] when the recipient is a wallet account and
429 /// the output is a same-account self-transfer. This is detected either
430 /// structurally, when [`recipient_key_scope`](Self::recipient_key_scope) is
431 /// `INTERNAL` or `EPHEMERAL` (those key scopes exist only within a single
432 /// account), or by observation, when the recipient account is also the
433 /// [`funding_account`](Self::funding_account). The latter case also covers
434 /// standalone addresses, which have no key scope.
435 /// - [`TransferType::WalletInternal`] when the recipient is a wallet account and
436 /// the [`funding_account`](Self::funding_account) is a different wallet account
437 /// (a cross-account transfer within the wallet).
438 /// - [`TransferType::Incoming`] when the recipient is a wallet account and no
439 /// wallet funding account is known.
440 pub fn transfer_type(&self) -> TransferType
441 where
442 AccountId: PartialEq,
443 {
444 match (
445 self.recipient_account.as_ref(),
446 self.recipient_key_scope,
447 self.funding_account.as_ref(),
448 ) {
449 (None, _, _) => TransferType::Outgoing,
450 (Some(_), Some(TransparentKeyScope::INTERNAL | TransparentKeyScope::EPHEMERAL), _) => {
451 TransferType::AccountInternal
452 }
453 (Some(r), _, Some(r0)) if r == r0 => TransferType::AccountInternal,
454 (Some(_), _, Some(_)) => TransferType::WalletInternal,
455 (Some(_), _, _) => TransferType::Incoming,
456 }
457 }
458
459 /// The identifier for the account that received this output, if known to belong to the
460 /// wallet. Returns `None` for outputs sent to addresses outside the wallet.
461 pub fn recipient_account(&self) -> Option<&AccountId> {
462 self.recipient_account.as_ref()
463 }
464
465 /// Returns the wallet address that received the UTXO.
466 pub fn recipient_address(&self) -> &TransparentAddress {
467 &self.recipient_address
468 }
469
470 /// The identifier for the wallet account that provided funds in the transaction
471 /// that created the output, if known.
472 ///
473 /// Note: the Zcash protocol permits construction of transactions where multiple distinct
474 /// accounts provide funds; however, `zcash_client_backend` does not currently support the
475 /// construction of transactions of this form. In cases where multiple funding accounts are
476 /// detected, the account that provided the most significant source of funds should be selected
477 /// if possible; in the future, this should be either expanded to support a set of funding
478 /// accounts (which will require potentially invasive storage backend changes).
479 pub fn funding_account(&self) -> Option<&AccountId> {
480 self.funding_account.as_ref()
481 }
482
483 /// Returns the value of the UTXO
484 pub fn value(&self) -> Zatoshis {
485 self.txout.value()
486 }
487}
488
489/// The way in which a transaction's transparent data names an address, and the data that the
490/// involvement carries.
491#[cfg(feature = "transparent-inputs")]
492#[derive(Debug, Clone, PartialEq, Eq)]
493pub enum TransparentInvolvement {
494 /// The observed address is paid by the transaction output at the observed index, which has
495 /// the given value.
496 Output(Zatoshis),
497 /// The observed address is revealed by the `scriptSig` of the transaction input at the
498 /// observed index, which spends the given outpoint.
499 Input(OutPoint),
500}
501
502/// A record that a transaction's transparent data names a particular address.
503///
504/// An observation is recorded for every address a wallet-involved transaction names, whether or
505/// not the wallet controls that address, so that the involvement can be recognized if a key
506/// covering the address is added to the wallet afterwards.
507///
508/// An observation is identified by the transaction it belongs to, the direction of its
509/// [`Self::involvement`], and its [`Self::item_index`]; the address and the involvement data
510/// are functions of that identity, so observing the same transaction twice yields identical
511/// records.
512#[cfg(feature = "transparent-inputs")]
513#[derive(Debug, Clone, PartialEq, Eq)]
514pub struct TransparentAddressObservation {
515 address: TransparentAddress,
516 item_index: u32,
517 involvement: TransparentInvolvement,
518}
519
520#[cfg(feature = "transparent-inputs")]
521impl TransparentAddressObservation {
522 /// Constructs an observation of the address paid by the transaction output at `item_index`.
523 pub fn output(item_index: u32, address: TransparentAddress, value: Zatoshis) -> Self {
524 Self {
525 address,
526 item_index,
527 involvement: TransparentInvolvement::Output(value),
528 }
529 }
530
531 /// Constructs an observation of the address revealed by the `scriptSig` of the transaction
532 /// input at `item_index`, which spends `prevout`.
533 pub fn input(item_index: u32, address: TransparentAddress, prevout: OutPoint) -> Self {
534 Self {
535 address,
536 item_index,
537 involvement: TransparentInvolvement::Input(prevout),
538 }
539 }
540
541 /// Returns the observed address.
542 pub fn address(&self) -> &TransparentAddress {
543 &self.address
544 }
545
546 /// Returns the index of the output or input that names the address, within the
547 /// transaction's `vout` or `vin` respectively.
548 pub fn item_index(&self) -> u32 {
549 self.item_index
550 }
551
552 /// Returns the direction of the involvement, and the data that it carries.
553 pub fn involvement(&self) -> &TransparentInvolvement {
554 &self.involvement
555 }
556}
557
558/// The serialized length of a compressed secp256k1 public key.
559#[cfg(feature = "transparent-inputs")]
560const COMPRESSED_PUBKEY_LEN: usize = 33;
561
562/// The serialized length of an uncompressed secp256k1 public key.
563#[cfg(feature = "transparent-inputs")]
564const UNCOMPRESSED_PUBKEY_LEN: usize = 65;
565
566/// The number of pushes in a P2PKH `scriptSig`: the signature, then the public key.
567#[cfg(feature = "transparent-inputs")]
568const P2PKH_SIG_PUSH_COUNT: usize = 2;
569
570/// Returns the address that a `scriptSig` reveals as the recipient of the output it spends, if
571/// the script has a shape from which the address can be recovered.
572///
573/// Both recognized shapes end with the material that the spent `scriptPubKey` commits to: a
574/// P2PKH `scriptSig` is `<sig> <pubkey>`, whose address is the HASH160 of the public key; any
575/// other push-only `scriptSig` is read as a P2SH spend, whose address is the HASH160 of its
576/// final push (the redeem script). A `scriptSig` that is empty or not push-only yields `None`.
577///
578/// The two shapes are distinguished without reference to the output being spent, which the
579/// wallet need not hold: a two-push `scriptSig` whose final push is a valid public key encoding
580/// is read as P2PKH. A P2SH redeem script that is itself a valid public key encoding, spent by a
581/// single-signature `scriptSig`, is therefore misread as P2PKH; no standard redeem script has
582/// that shape. A misread names an address of the wrong kind, which matches nothing the wallet
583/// holds, so the input direction misses that spend permanently — unless the transaction that
584/// created the spent output is itself stored, since its output observation names the address
585/// correctly.
586#[cfg(feature = "transparent-inputs")]
587fn address_from_script_sig(
588 script_sig: &::transparent::address::Script,
589) -> Option<TransparentAddress> {
590 let pushes = script::Sig::parse(&script_sig.0).ok()?.0;
591 let last = pushes.last()?.value();
592
593 // Equivalent to `CPubKey::GetLen` composed with `CPubKey::ValidSize`: the leading byte of a
594 // serialized public key determines the length the encoding must have.
595 let is_pubkey = match last.first() {
596 Some(2 | 3) => last.len() == COMPRESSED_PUBKEY_LEN,
597 Some(4 | 6 | 7) => last.len() == UNCOMPRESSED_PUBKEY_LEN,
598 _ => false,
599 };
600
601 Some(if pushes.len() == P2PKH_SIG_PUSH_COUNT && is_pubkey {
602 TransparentAddress::PublicKeyHash(::transparent::util::hash160::hash(&last))
603 } else {
604 TransparentAddress::ScriptHash(::transparent::util::hash160::hash(&last))
605 })
606}
607
608/// Returns an observation for every address named by the given transaction's transparent data:
609/// one for each output whose `scriptPubKey` describes an address, and one for each non-coinbase
610/// input whose `scriptSig` reveals the address of the output it spends.
611///
612/// Outputs and inputs whose scripts name no address are omitted. Script data that does not
613/// parse names no address; it is chain data the wallet does not control, so it is skipped
614/// rather than reported as an error.
615#[cfg(feature = "transparent-inputs")]
616pub fn transparent_address_observations(
617 tx: &zcash_primitives::transaction::Transaction,
618) -> Vec<TransparentAddressObservation> {
619 let mut observations = vec![];
620
621 let Some(bundle) = tx.transparent_bundle() else {
622 return observations;
623 };
624
625 for (output_index, txout) in bundle.vout.iter().enumerate() {
626 if let Some(address) = txout.recipient_address() {
627 observations.push(TransparentAddressObservation::output(
628 u32::try_from(output_index).expect("a transaction has fewer than 2^32 outputs"),
629 address,
630 txout.value(),
631 ));
632 }
633 }
634
635 // A coinbase transaction's single input carries arbitrary data in its `scriptSig` and
636 // spends the null outpoint, so it reveals no address and references no prior output.
637 if !zcash_primitives::transaction::coinbase::is_coinbase(tx) {
638 for (input_index, txin) in bundle.vin.iter().enumerate() {
639 if let Some(address) = address_from_script_sig(txin.script_sig()) {
640 observations.push(TransparentAddressObservation::input(
641 u32::try_from(input_index).expect("a transaction has fewer than 2^32 inputs"),
642 address,
643 txin.prevout().clone(),
644 ));
645 }
646 }
647 }
648
649 observations
650}
651
652impl<AccountId: Debug> transparent_fees::InputView for WalletTransparentOutput<AccountId> {
653 fn outpoint(&self) -> &OutPoint {
654 &self.outpoint
655 }
656 fn coin(&self) -> &TxOut<Zatoshis> {
657 &self.txout
658 }
659 fn serialized_size(&self) -> transparent_fees::InputSize {
660 match self.known_input_size {
661 Some(size) => transparent_fees::InputSize::Known(size),
662 None => {
663 match zcash_script::script::PubKey::parse(&self.txout.script_pubkey().0)
664 .ok()
665 .as_ref()
666 .and_then(zcash_script::solver::standard)
667 {
668 Some(zcash_script::solver::ScriptKind::PubKeyHash { .. }) => {
669 transparent_fees::InputSize::STANDARD_P2PKH
670 }
671 Some(zcash_script::solver::ScriptKind::ScriptHash { .. }) => {
672 // P2SH input size depends on the redeem script, which the
673 // wallet must set via `with_known_input_size` (the SQLite
674 // backend does this by reading the redeem script from the DB
675 // and computing the exact size via
676 // `p2sh_input_serialized_len`). Without it we cannot
677 // determine the exact input size; return `Unknown` so the
678 // estimator falls back to the consensus-maximum input size
679 // rather than guessing.
680 transparent_fees::InputSize::Unknown(self.outpoint.clone())
681 }
682 _ => transparent_fees::InputSize::Unknown(self.outpoint.clone()),
683 }
684 }
685 }
686 }
687}
688
689/// A reference to a spent note belonging to the wallet within a transaction.
690#[derive(Clone)]
691pub struct WalletSpend<Nf, AccountId> {
692 index: usize,
693 nf: Nf,
694 account_id: AccountId,
695}
696
697impl<Nf, AccountId> WalletSpend<Nf, AccountId> {
698 /// Constructs a `WalletSpend` from its constituent parts.
699 pub fn from_parts(index: usize, nf: Nf, account_id: AccountId) -> Self {
700 Self {
701 index,
702 nf,
703 account_id,
704 }
705 }
706
707 /// Returns the index of the Sapling spend or Orchard action within the transaction that
708 /// created this spend.
709 pub fn index(&self) -> usize {
710 self.index
711 }
712 /// Returns the nullifier of the spent note.
713 pub fn nf(&self) -> &Nf {
714 &self.nf
715 }
716 /// Returns the identifier to the account_id to which the note belonged.
717 pub fn account_id(&self) -> &AccountId {
718 &self.account_id
719 }
720}
721
722/// A type alias for Sapling [`WalletSpend`]s.
723pub type WalletSaplingSpend<AccountId> = WalletSpend<sapling::Nullifier, AccountId>;
724
725/// A type alias for Orchard [`WalletSpend`]s.
726#[cfg(feature = "orchard")]
727pub type WalletOrchardSpend<AccountId> = WalletSpend<orchard::note::Nullifier, AccountId>;
728
729/// A type alias for Ironwood [`WalletSpend`]s.
730///
731/// Ironwood notes are Orchard-shaped and therefore share the Orchard nullifier type, but Ironwood
732/// is a distinct pool from Orchard.
733#[cfg(feature = "orchard")]
734pub type WalletIronwoodSpend<AccountId> = WalletSpend<orchard::note::Nullifier, AccountId>;
735
736/// A reference to a transparent output belonging to the wallet that is spent within a
737/// transaction.
738///
739/// This is the transparent counterpart of [`WalletSpend`]. A transparent output is identified by
740/// the [`OutPoint`] that names it rather than by a nullifier, so unlike a shielded spend it can be
741/// recognized only by a wallet that already knows of the output being spent.
742#[derive(Clone, Debug)]
743pub struct WalletTransparentSpend<AccountId> {
744 index: usize,
745 outpoint: OutPoint,
746 account_id: AccountId,
747}
748
749impl<AccountId> WalletTransparentSpend<AccountId> {
750 /// Constructs a `WalletTransparentSpend` from its constituent parts.
751 pub fn from_parts(index: usize, outpoint: OutPoint, account_id: AccountId) -> Self {
752 Self {
753 index,
754 outpoint,
755 account_id,
756 }
757 }
758
759 /// Returns the index of the transparent input within the spending transaction.
760 pub fn index(&self) -> usize {
761 self.index
762 }
763
764 /// Returns the outpoint of the output being spent.
765 pub fn outpoint(&self) -> &OutPoint {
766 &self.outpoint
767 }
768
769 /// Returns the identifier for the account to which the spent output belonged.
770 pub fn account_id(&self) -> &AccountId {
771 &self.account_id
772 }
773}
774
775/// An output that was successfully decrypted in the process of wallet scanning.
776#[derive(Clone)]
777pub struct WalletOutput<Note, Nullifier, AccountId> {
778 index: usize,
779 ephemeral_key: EphemeralKeyBytes,
780 note: Note,
781 is_change: bool,
782 note_commitment_tree_position: Position,
783 nf: Option<Nullifier>,
784 account_id: AccountId,
785 recipient_key_scope: Option<zip32::Scope>,
786}
787
788impl<Note, Nullifier, AccountId> WalletOutput<Note, Nullifier, AccountId> {
789 /// Constructs a new `WalletOutput` value from its constituent parts.
790 #[allow(clippy::too_many_arguments)]
791 pub fn from_parts(
792 index: usize,
793 ephemeral_key: EphemeralKeyBytes,
794 note: Note,
795 is_change: bool,
796 note_commitment_tree_position: Position,
797 nf: Option<Nullifier>,
798 account_id: AccountId,
799 recipient_key_scope: Option<zip32::Scope>,
800 ) -> Self {
801 Self {
802 index,
803 ephemeral_key,
804 note,
805 is_change,
806 note_commitment_tree_position,
807 nf,
808 account_id,
809 recipient_key_scope,
810 }
811 }
812
813 /// The index of the output or action in the transaction that created this output.
814 pub fn index(&self) -> usize {
815 self.index
816 }
817 /// The [`EphemeralKeyBytes`] used in the decryption of the note.
818 pub fn ephemeral_key(&self) -> &EphemeralKeyBytes {
819 &self.ephemeral_key
820 }
821 /// The note.
822 pub fn note(&self) -> &Note {
823 &self.note
824 }
825 /// A flag indicating whether the process of note decryption determined that this
826 /// output should be classified as change.
827 pub fn is_change(&self) -> bool {
828 self.is_change
829 }
830 /// The position of the note in the global note commitment tree.
831 pub fn note_commitment_tree_position(&self) -> Position {
832 self.note_commitment_tree_position
833 }
834 /// The nullifier for the note, if the key used to decrypt the note was able to compute it.
835 pub fn nf(&self) -> Option<&Nullifier> {
836 self.nf.as_ref()
837 }
838 /// The identifier for the account to which the output belongs.
839 pub fn account_id(&self) -> &AccountId {
840 &self.account_id
841 }
842 /// The ZIP 32 scope for which the viewing key that decrypted this output was derived, if
843 /// known.
844 pub fn recipient_key_scope(&self) -> Option<zip32::Scope> {
845 self.recipient_key_scope
846 }
847}
848
849/// A subset of an [`OutputDescription`] relevant to wallets and light clients.
850///
851/// [`OutputDescription`]: sapling::bundle::OutputDescription
852pub type WalletSaplingOutput<AccountId> =
853 WalletOutput<sapling::Note, sapling::Nullifier, AccountId>;
854
855/// The output part of an Orchard [`Action`] that was decrypted in the process of scanning.
856///
857/// [`Action`]: orchard::Action
858#[cfg(feature = "orchard")]
859pub type WalletOrchardOutput<AccountId> =
860 WalletOutput<(orchard::note::Note, orchard::ValuePool), orchard::note::Nullifier, AccountId>;
861
862/// The output part of an Ironwood [`Action`] that was decrypted in the process of scanning.
863///
864/// [`Action`]: orchard::Action
865#[cfg(feature = "orchard")]
866pub type WalletIronwoodOutput<AccountId> =
867 WalletOutput<(orchard::note::Note, orchard::ValuePool), orchard::note::Nullifier, AccountId>;
868
869/// An enumeration of supported shielded note types for use in [`ReceivedNote`]
870#[derive(Debug, Clone, PartialEq, Eq)]
871pub enum Note {
872 Sapling(sapling::Note),
873 #[cfg(feature = "orchard")]
874 Orchard {
875 note: orchard::Note,
876 pool: orchard::ValuePool,
877 },
878}
879
880impl Note {
881 /// Returns the receiver of this note.
882 pub fn receiver(&self) -> Receiver {
883 match self {
884 Note::Sapling(n) => Receiver::Sapling(n.recipient()),
885 #[cfg(feature = "orchard")]
886 Note::Orchard { note, .. } => Receiver::Orchard(note.recipient()),
887 }
888 }
889
890 pub fn value(&self) -> Zatoshis {
891 match self {
892 Note::Sapling(n) => n.value().inner().try_into().expect(
893 "Sapling notes must have values in the range of valid non-negative ZEC values.",
894 ),
895 #[cfg(feature = "orchard")]
896 Note::Orchard { note, .. } => Zatoshis::from_u64(note.value().inner()).expect(
897 "Orchard notes must have values in the range of valid non-negative ZEC values.",
898 ),
899 }
900 }
901
902 /// Returns the shielded value pool to which this note belongs.
903 pub fn pool(&self) -> ShieldedPool {
904 match self {
905 Note::Sapling(_) => ShieldedPool::Sapling,
906 #[cfg(feature = "orchard")]
907 Note::Orchard { pool, .. } => shielded_pool_for_value_pool(*pool),
908 }
909 }
910}
911
912/// Returns the shielded pool corresponding to an Orchard-protocol value pool. The Orchard protocol
913/// serves both the Orchard pool (version-2 notes) and the Ironwood pool (version-3 notes); this is
914/// the single point at which that classification is made.
915#[cfg(feature = "orchard")]
916pub(crate) fn shielded_pool_for_value_pool(pool: orchard::ValuePool) -> ShieldedPool {
917 match pool {
918 orchard::ValuePool::Orchard => ShieldedPool::Orchard,
919 orchard::ValuePool::Ironwood => ShieldedPool::Ironwood,
920 }
921}
922
923/// A note that was received by the wallet, along with contextual information about the output that
924/// generated the note and the key that is required to spend it.
925#[derive(Clone, PartialEq, Eq)]
926pub struct ReceivedNote<NoteRef, NoteT> {
927 note_id: NoteRef,
928 txid: TxId,
929 output_index: u16,
930 note: NoteT,
931 spending_key_scope: Scope,
932 note_commitment_tree_position: Position,
933 mined_height: Option<BlockHeight>,
934 max_shielding_input_height: Option<BlockHeight>,
935}
936
937impl<NoteRef, NoteT> ReceivedNote<NoteRef, NoteT> {
938 /// Constructs a new [`ReceivedNote`] from its constituent parts.
939 #[allow(clippy::too_many_arguments)]
940 pub fn from_parts(
941 note_id: NoteRef,
942 txid: TxId,
943 output_index: u16,
944 note: NoteT,
945 spending_key_scope: Scope,
946 note_commitment_tree_position: Position,
947 mined_height: Option<BlockHeight>,
948 max_shielding_input_height: Option<BlockHeight>,
949 ) -> Self {
950 ReceivedNote {
951 note_id,
952 txid,
953 output_index,
954 note,
955 spending_key_scope,
956 note_commitment_tree_position,
957 mined_height,
958 max_shielding_input_height,
959 }
960 }
961
962 /// Returns the storage backend's internal identifier for the note.
963 pub fn internal_note_id(&self) -> &NoteRef {
964 &self.note_id
965 }
966 /// Returns the txid of the transaction that constructed the note.
967 pub fn txid(&self) -> &TxId {
968 &self.txid
969 }
970 /// Returns the output index of the note within the transaction, according to the note's
971 /// shielded protocol.
972 pub fn output_index(&self) -> u16 {
973 self.output_index
974 }
975 /// Returns the note data.
976 pub fn note(&self) -> &NoteT {
977 &self.note
978 }
979 /// Returns the [`Scope`] of the spending key required to make spend authorizing signatures for
980 /// the note.
981 pub fn spending_key_scope(&self) -> Scope {
982 self.spending_key_scope
983 }
984 /// Returns the position of the note in the note commitment tree.
985 pub fn note_commitment_tree_position(&self) -> Position {
986 self.note_commitment_tree_position
987 }
988 /// Returns the block height at which the transaction that produced the note was mined.
989 pub fn mined_height(&self) -> Option<BlockHeight> {
990 self.mined_height
991 }
992 /// Returns the maximum block height among those at which transparent inputs to the transaction
993 /// that produced the note were created, considering only transparent inputs that belong to the
994 /// same wallet account as the note. This height is used in determining the effective number of
995 /// confirmations for externally-received value. See [`ZIP 315`] for additional information.
996 ///
997 /// [`ZIP 315`]: https://zips.z.cash/zip-0315
998 pub fn max_shielding_input_height(&self) -> Option<BlockHeight> {
999 self.max_shielding_input_height
1000 }
1001
1002 /// Map over the `note` field of this data structure.
1003 ///
1004 /// Consume this value, applying the provided function to the value of its `note` field and
1005 /// returning a new `ReceivedNote` with the result as its `note` field value.
1006 pub fn map_note<N, F: Fn(NoteT) -> N>(self, f: F) -> ReceivedNote<NoteRef, N> {
1007 ReceivedNote {
1008 note_id: self.note_id,
1009 txid: self.txid,
1010 output_index: self.output_index,
1011 note: f(self.note),
1012 spending_key_scope: self.spending_key_scope,
1013 note_commitment_tree_position: self.note_commitment_tree_position,
1014 mined_height: self.mined_height,
1015 max_shielding_input_height: self.max_shielding_input_height,
1016 }
1017 }
1018}
1019
1020impl<NoteRef: Debug> Debug for ReceivedNote<NoteRef, sapling::Note> {
1021 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1022 f.debug_struct("ReceivedNote")
1023 .field("note_id", &self.note_id)
1024 .field("txid", &self.txid)
1025 .field("output_index", &self.output_index)
1026 .field("note_value", &self.note_value())
1027 .field("spending_key_scope", &self.spending_key_scope)
1028 .field(
1029 "note_commitment_tree_position",
1030 &self.note_commitment_tree_position,
1031 )
1032 .field("mined_height", &self.mined_height)
1033 .finish()
1034 }
1035}
1036
1037#[cfg(feature = "orchard")]
1038impl<NoteRef: Debug> Debug for ReceivedNote<NoteRef, orchard::note::Note> {
1039 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1040 f.debug_struct("ReceivedNote")
1041 .field("note_id", &self.note_id)
1042 .field("txid", &self.txid)
1043 .field("output_index", &self.output_index)
1044 .field("note_value", &self.note_value())
1045 .field("spending_key_scope", &self.spending_key_scope)
1046 .field(
1047 "note_commitment_tree_position",
1048 &self.note_commitment_tree_position,
1049 )
1050 .field("mined_height", &self.mined_height)
1051 .finish()
1052 }
1053}
1054
1055impl<NoteRef> ReceivedNote<NoteRef, sapling::Note> {
1056 pub fn note_value(&self) -> Result<Zatoshis, BalanceError> {
1057 self.note.value().inner().try_into()
1058 }
1059}
1060
1061#[cfg(feature = "orchard")]
1062impl<NoteRef> ReceivedNote<NoteRef, orchard::note::Note> {
1063 pub fn note_value(&self) -> Result<Zatoshis, BalanceError> {
1064 self.note.value().inner().try_into()
1065 }
1066}
1067
1068impl<NoteRef> sapling_fees::InputView<NoteRef> for (NoteRef, sapling::value::NoteValue) {
1069 fn note_id(&self) -> &NoteRef {
1070 &self.0
1071 }
1072
1073 fn value(&self) -> Zatoshis {
1074 self.1
1075 .inner()
1076 .try_into()
1077 .expect("Sapling note values are indirectly checked by consensus.")
1078 }
1079}
1080
1081impl<NoteRef> sapling_fees::InputView<NoteRef> for ReceivedNote<NoteRef, sapling::Note> {
1082 fn note_id(&self) -> &NoteRef {
1083 &self.note_id
1084 }
1085
1086 fn value(&self) -> Zatoshis {
1087 self.note
1088 .value()
1089 .inner()
1090 .try_into()
1091 .expect("Sapling note values are indirectly checked by consensus.")
1092 }
1093}
1094
1095#[cfg(feature = "orchard")]
1096impl<NoteRef> orchard_fees::InputView<NoteRef> for (NoteRef, orchard::value::NoteValue) {
1097 fn note_id(&self) -> &NoteRef {
1098 &self.0
1099 }
1100
1101 fn value(&self) -> Zatoshis {
1102 self.1
1103 .inner()
1104 .try_into()
1105 .expect("Orchard note values are indirectly checked by consensus.")
1106 }
1107}
1108
1109#[cfg(feature = "orchard")]
1110impl<NoteRef> orchard_fees::InputView<NoteRef> for ReceivedNote<NoteRef, orchard::Note> {
1111 fn note_id(&self) -> &NoteRef {
1112 &self.note_id
1113 }
1114
1115 fn value(&self) -> Zatoshis {
1116 self.note
1117 .value()
1118 .inner()
1119 .try_into()
1120 .expect("Orchard note values are indirectly checked by consensus.")
1121 }
1122}
1123
1124/// Describes a policy for which outgoing viewing key should be able to decrypt
1125/// transaction outputs.
1126///
1127/// For details on what transaction information is visible to the holder of an outgoing
1128/// viewing key, refer to [ZIP 310].
1129///
1130/// [ZIP 310]: https://zips.z.cash/zip-0310
1131#[derive(Debug, Clone)]
1132pub enum OvkPolicy {
1133 /// Use an outgoing viewing key produced from the sender's [`UnifiedFullViewingKey`],
1134 /// selected via the policy documented in [`UnifiedFullViewingKey::select_ovk`].
1135 ///
1136 /// External transaction outputs will be decryptable by the sender, in addition to the
1137 /// recipients. Wallet-internal transaction outputs will be decryptable only with the wallet's
1138 /// internal-scoped incoming viewing key.
1139 ///
1140 /// [`UnifiedFullViewingKey`]: zcash_keys::keys::UnifiedFullViewingKey
1141 /// [`UnifiedFullViewingKey::select_ovk`]: zcash_keys::keys::UnifiedFullViewingKey::select_ovk
1142 Sender,
1143
1144 /// Use custom outgoing viewing keys. These might for instance be derived from a
1145 /// different seed than the wallet's spending keys.
1146 ///
1147 /// Transaction outputs will be decryptable by the recipients, and whoever controls
1148 /// the provided outgoing viewing keys.
1149 Custom {
1150 external_ovk: OutgoingViewingKey,
1151 internal_ovk: Option<OutgoingViewingKey>,
1152 },
1153 /// Use no outgoing viewing keys. Transaction outputs will be decryptable by their
1154 /// recipients, but not by the sender.
1155 Discard,
1156}
1157
1158impl OvkPolicy {
1159 /// Constructs an [`OvkPolicy::Custom`] value from a single arbitrary 32-byte key with both the
1160 /// external_ovk and internal_ovk components set to the same key.
1161 ///
1162 /// Outputs of transactions created with this OVK policy will be recoverable using this key
1163 /// irrespective of whether they are external outputs or wallet-internal change outputs.
1164 pub fn custom_from_common_bytes(key: &[u8; 32]) -> Self {
1165 let k = OutgoingViewingKey::from(*key);
1166 OvkPolicy::Custom {
1167 external_ovk: k,
1168 internal_ovk: Some(k),
1169 }
1170 }
1171}
1172
1173/// Metadata describing the gap limit position of a transparent address.
1174#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1175#[cfg(feature = "transparent-inputs")]
1176pub enum GapMetadata {
1177 /// The address, or an address at a greater child index, has received transparent funds and
1178 /// will be discovered by wallet recovery by exploration over the space of
1179 /// [`NonHardenedChildIndex`]es using the provided gap limit.
1180 GapRecoverable { gap_limit: u32 },
1181 /// The address exists within an address gap of the given limit size, and will be discovered by
1182 /// wallet recovery by exploration using the provided gap limit. In the view of the wallet, no
1183 /// addresses at the given position or greater (up to the gap limit) have received funds. The
1184 /// number of addresses remaining within the gap limit before no additional addresses can be
1185 /// allocated is given by `gap_limit - (gap_position + 1)`.
1186 InGap {
1187 /// A zero-based index over the child indices in the gap.
1188 gap_position: u32,
1189 /// The maximum number of sequential child indices that can be allocated to addresses
1190 /// without any of those addresses having received funds.
1191 gap_limit: u32,
1192 },
1193 /// The wallet does not contain derivation information for the associated address, and so its
1194 /// relationship to other addresses in the wallet cannot be determined.
1195 DerivationUnknown,
1196}
1197
1198/// Metadata describing whether and when a transparent address was exposed by the wallet.
1199#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1200#[cfg(feature = "transparent-inputs")]
1201pub enum Exposure {
1202 /// The address has been exposed by the wallet.
1203 Exposed {
1204 /// The address was first exposed to the wider ecosystem at this height, to the best
1205 /// of our knowledge.
1206 ///
1207 /// - For user-generated addresses, this is the chain tip height at the time that the
1208 /// address was generated by an explicit request by the user or reserved for use in
1209 /// a ZIP 320 transaction. These heights are not recoverable from chain.
1210 /// - In the case of an address with its first use discovered in a transaction
1211 /// obtained by scanning the chain, this will be set to the mined height of that
1212 /// transaction. In recover from seed cases, this is what user-generated addresses
1213 /// will be assigned.
1214 at_height: BlockHeight,
1215 /// Transparent address gap metadata, as of the time the query that produced this exposure
1216 /// metadata was executed.
1217 gap_metadata: GapMetadata,
1218 },
1219 /// The address is not known to have been exposed to an external caller by the wallet.
1220 ///
1221 /// The wallet makes its determination based on observed chain data and inference from
1222 /// standard wallet address generation patterns. In particular, this is the state that
1223 /// an address is in when it has been generated by the advancement of the transparent
1224 /// address gap. This judgement may be incorrect for restored wallets.
1225 Unknown,
1226 /// It is not possible for the wallet to determine whether the address has been exposed,
1227 /// given the information the wallet has access to.
1228 CannotKnow,
1229}
1230
1231/// Information about a transparent address controlled by the wallet.
1232#[derive(Debug, Clone, PartialEq, Eq)]
1233#[cfg(feature = "transparent-inputs")]
1234pub struct TransparentAddressMetadata {
1235 source: TransparentAddressSource,
1236 exposure: Exposure,
1237 next_check_time: Option<SystemTime>,
1238}
1239
1240#[cfg(feature = "transparent-inputs")]
1241impl TransparentAddressMetadata {
1242 /// Constructs a new [`TransparentAddressMetadata`] value from its constituent parts.
1243 pub fn new(
1244 source: TransparentAddressSource,
1245 exposure: Exposure,
1246 next_check_time: Option<SystemTime>,
1247 ) -> Self {
1248 Self {
1249 source,
1250 exposure,
1251 next_check_time,
1252 }
1253 }
1254
1255 /// Returns a [`TransparentAddressMetadata`] with [`TransparentAddressSource::Derived`] source
1256 /// information and the specified exposure height.
1257 pub fn derived(
1258 scope: TransparentKeyScope,
1259 address_index: NonHardenedChildIndex,
1260 exposure: Exposure,
1261 next_check_time: Option<SystemTime>,
1262 ) -> Self {
1263 Self {
1264 source: TransparentAddressSource::Derived {
1265 scope,
1266 address_index,
1267 },
1268 exposure,
1269 next_check_time,
1270 }
1271 }
1272
1273 /// Returns a [`TransparentAddressMetadata`] with [`TransparentAddressSource::StandalonePubkey`]
1274 /// source information for a P2PKH address and the specified exposure height.
1275 #[cfg(feature = "transparent-key-import")]
1276 pub fn standalone_p2pkh(
1277 pubkey: secp256k1::PublicKey,
1278 exposure: Exposure,
1279 next_check_time: Option<SystemTime>,
1280 ) -> Self {
1281 Self {
1282 source: TransparentAddressSource::StandalonePubkey(pubkey),
1283 exposure,
1284 next_check_time,
1285 }
1286 }
1287
1288 /// Returns a [`TransparentAddressMetadata`] with [`TransparentAddressSource::StandaloneScript`]
1289 /// source information for a P2SH address and the specified exposure height.
1290 #[cfg(feature = "transparent-key-import")]
1291 pub fn standalone_script(
1292 redeem_script: script::Redeem,
1293 exposure: Exposure,
1294 next_check_time: Option<SystemTime>,
1295 ) -> Self {
1296 Self {
1297 source: TransparentAddressSource::StandaloneScript(redeem_script),
1298 exposure,
1299 next_check_time,
1300 }
1301 }
1302
1303 /// Returns a [`TransparentAddressMetadata`] with [`TransparentAddressSource::StandaloneAddress`]
1304 /// source information for an imported bare transparent address and the specified exposure
1305 /// height.
1306 #[cfg(feature = "transparent-key-import")]
1307 pub fn standalone_address(exposure: Exposure, next_check_time: Option<SystemTime>) -> Self {
1308 Self {
1309 source: TransparentAddressSource::StandaloneAddress,
1310 exposure,
1311 next_check_time,
1312 }
1313 }
1314
1315 /// Returns the source metadata for the address.
1316 pub fn source(&self) -> &TransparentAddressSource {
1317 &self.source
1318 }
1319
1320 /// Returns the exposure metadata for this transparent address.
1321 pub fn exposure(&self) -> Exposure {
1322 self.exposure
1323 }
1324
1325 /// Returns a copy of this metadata, with its exposure metadata updated
1326 pub fn with_exposure_at(
1327 &self,
1328 exposure_height: BlockHeight,
1329 gap_metadata: GapMetadata,
1330 ) -> Self {
1331 Self {
1332 source: self.source.clone(),
1333 exposure: Exposure::Exposed {
1334 at_height: exposure_height,
1335 gap_metadata,
1336 },
1337 next_check_time: self.next_check_time,
1338 }
1339 }
1340
1341 /// Returns the timestamp of the earliest time that the light wallet server may be queried for
1342 /// UTXOs associated with this address, or `None` if the wallet backend is not placing any
1343 /// restrictions on when this address can be queried. Unless the wallet application is
1344 /// requesting address information from a light wallet server that is trusted for privacy,
1345 /// only one such query should be performed at a time, to avoid linking multiple transparent
1346 /// addresses as belonging to the same wallet in the view of the light wallet server.
1347 pub fn next_check_time(&self) -> Option<SystemTime> {
1348 self.next_check_time
1349 }
1350
1351 /// Returns the [`TransparentKeyScope`] of the private key from which the address was derived,
1352 /// if known. Returns `None` for standalone addresses in the wallet.
1353 pub fn scope(&self) -> Option<TransparentKeyScope> {
1354 self.source.scope()
1355 }
1356
1357 /// Returns the BIP 44 [`NonHardenedChildIndex`] at which the address was derived, if known.
1358 /// Returns `None` for standalone addresses in the wallet.
1359 pub fn address_index(&self) -> Option<NonHardenedChildIndex> {
1360 self.source.address_index()
1361 }
1362
1363 /// Returns the redeem script for the address, if this is a P2SH address.
1364 /// Returns `None` for non-P2SH addresses.
1365 #[cfg(feature = "transparent-key-import")]
1366 pub fn redeem_script(&self) -> Option<&script::Redeem> {
1367 self.source.redeem_script()
1368 }
1369}
1370
1371/// Source information for a transparent address.
1372#[derive(Debug, Clone, PartialEq, Eq)]
1373#[cfg(feature = "transparent-inputs")]
1374pub enum TransparentAddressSource {
1375 /// BIP 44 path derivation information for the address below account pubkey level, i.e. the
1376 /// `change` and `index` elements of the path.
1377 Derived {
1378 scope: TransparentKeyScope,
1379 address_index: NonHardenedChildIndex,
1380 },
1381
1382 /// The address was derived from a secp256k1 public key for which derivation information is
1383 /// unknown or for which the associated spending key was produced from system randomness.
1384 /// This variant provides the public key directly.
1385 #[cfg(feature = "transparent-key-import")]
1386 StandalonePubkey(secp256k1::PublicKey),
1387
1388 /// The address was derived from a P2SH redeem_script for which derivation information is
1389 /// unknown.
1390 /// This variant provides the redeem script directly.
1391 #[cfg(feature = "transparent-key-import")]
1392 StandaloneScript(script::Redeem),
1393
1394 /// The address was imported as a bare transparent address, without any associated key
1395 /// material. The wallet watches for outputs received by the address, but holds neither
1396 /// the public key (P2PKH) nor the redeem script (P2SH) from which it was derived, so
1397 /// funds received by it cannot be spent unless that material is subsequently imported.
1398 #[cfg(feature = "transparent-key-import")]
1399 StandaloneAddress,
1400}
1401
1402#[cfg(feature = "transparent-inputs")]
1403impl TransparentAddressSource {
1404 /// Returns the [`TransparentKeyScope`] of the private key from which the address was derived,
1405 /// if known. Returns `None` for standalone addresses in the wallet.
1406 pub fn scope(&self) -> Option<TransparentKeyScope> {
1407 match self {
1408 TransparentAddressSource::Derived { scope, .. } => Some(*scope),
1409 #[cfg(feature = "transparent-key-import")]
1410 TransparentAddressSource::StandalonePubkey(_) => None,
1411 #[cfg(feature = "transparent-key-import")]
1412 TransparentAddressSource::StandaloneScript(_) => None,
1413 #[cfg(feature = "transparent-key-import")]
1414 TransparentAddressSource::StandaloneAddress => None,
1415 }
1416 }
1417
1418 /// Returns the BIP 44 [`NonHardenedChildIndex`] at which the address was derived, if known.
1419 /// Returns `None` for standalone addresses in the wallet.
1420 pub fn address_index(&self) -> Option<NonHardenedChildIndex> {
1421 match self {
1422 TransparentAddressSource::Derived { address_index, .. } => Some(*address_index),
1423 #[cfg(feature = "transparent-key-import")]
1424 TransparentAddressSource::StandalonePubkey(_) => None,
1425 #[cfg(feature = "transparent-key-import")]
1426 TransparentAddressSource::StandaloneScript(_) => None,
1427 #[cfg(feature = "transparent-key-import")]
1428 TransparentAddressSource::StandaloneAddress => None,
1429 }
1430 }
1431
1432 /// Returns the redeem script for the address, if this is a P2SH address.
1433 /// Returns `None` for non-P2SH addresses.
1434 #[cfg(feature = "transparent-key-import")]
1435 pub fn redeem_script(&self) -> Option<&script::Redeem> {
1436 match self {
1437 TransparentAddressSource::Derived { .. } => None,
1438 #[cfg(feature = "transparent-key-import")]
1439 TransparentAddressSource::StandalonePubkey(_) => None,
1440 #[cfg(feature = "transparent-key-import")]
1441 TransparentAddressSource::StandaloneScript(redeem_script) => Some(redeem_script),
1442 #[cfg(feature = "transparent-key-import")]
1443 TransparentAddressSource::StandaloneAddress => None,
1444 }
1445 }
1446}
1447
1448/// Property tests for [`OutputRef`], whose identity (txid, pool, output index) is the key the
1449/// note-locking tables and the proposal double-spend check operate on.
1450#[cfg(test)]
1451mod output_ref_tests {
1452 use proptest::prelude::*;
1453 use zcash_protocol::{PoolType, ShieldedPool, TxId};
1454
1455 use super::{NoteId, OutputRef};
1456
1457 fn arb_shielded_pool() -> impl Strategy<Value = ShieldedPool> {
1458 prop_oneof![
1459 Just(ShieldedPool::Sapling),
1460 Just(ShieldedPool::Orchard),
1461 Just(ShieldedPool::Ironwood),
1462 ]
1463 }
1464
1465 fn arb_pool_type() -> impl Strategy<Value = PoolType> {
1466 prop_oneof![
1467 Just(PoolType::Transparent),
1468 arb_shielded_pool().prop_map(PoolType::Shielded),
1469 ]
1470 }
1471
1472 fn arb_output_ref() -> impl Strategy<Value = OutputRef> {
1473 (any::<[u8; 32]>(), arb_pool_type(), any::<u32>())
1474 .prop_map(|(txid, pool, idx)| OutputRef::new(TxId::from_bytes(txid), pool, idx))
1475 }
1476
1477 proptest! {
1478 /// Converting a `NoteId` preserves every component: the note's pool maps into the
1479 /// shielded arm of `PoolType`, and the `u16` output index widens losslessly.
1480 #[test]
1481 fn from_note_id_preserves_fields(
1482 txid in any::<[u8; 32]>(),
1483 pool in arb_shielded_pool(),
1484 idx in any::<u16>(),
1485 ) {
1486 let txid = TxId::from_bytes(txid);
1487 let output_ref = OutputRef::from(NoteId::new(txid, pool, idx));
1488 prop_assert_eq!(output_ref.txid(), &txid);
1489 prop_assert_eq!(output_ref.pool(), PoolType::Shielded(pool));
1490 prop_assert_eq!(output_ref.output_index(), u32::from(idx));
1491 }
1492
1493 /// Identity is exactly the (txid, pool, output index) triple: a reference equals
1494 /// itself, differs from any single-field mutation of itself, and `Ord` agrees with
1495 /// `Eq` (the `BTreeSet` double-spend check in proposal construction and the lock
1496 /// tables both rely on this).
1497 #[test]
1498 fn identity_is_the_full_triple(a in arb_output_ref()) {
1499 prop_assert_eq!(a, a);
1500 prop_assert_eq!(a.cmp(&a), std::cmp::Ordering::Equal);
1501
1502 // A different output index is a different output.
1503 let other_index = OutputRef::new(
1504 *a.txid(),
1505 a.pool(),
1506 a.output_index().wrapping_add(1),
1507 );
1508 prop_assert_ne!(a, other_index);
1509 prop_assert_ne!(a.cmp(&other_index), std::cmp::Ordering::Equal);
1510
1511 // A different pool is a different output, even at the same (txid, index): the
1512 // same transaction may have outputs at the same index in several pools.
1513 let other_pool = OutputRef::new(
1514 *a.txid(),
1515 match a.pool() {
1516 PoolType::Transparent => PoolType::SAPLING,
1517 PoolType::Shielded(_) => PoolType::Transparent,
1518 },
1519 a.output_index(),
1520 );
1521 prop_assert_ne!(a, other_pool);
1522 prop_assert_ne!(a.cmp(&other_pool), std::cmp::Ordering::Equal);
1523
1524 // A different transaction is a different output.
1525 let mut txid = <[u8; 32]>::from(*a.txid());
1526 txid[0] = txid[0].wrapping_add(1);
1527 let other_txid = OutputRef::new(TxId::from_bytes(txid), a.pool(), a.output_index());
1528 prop_assert_ne!(a, other_txid);
1529 prop_assert_ne!(a.cmp(&other_txid), std::cmp::Ordering::Equal);
1530 }
1531
1532 /// Two independently drawn references are equal exactly when all three components
1533 /// match.
1534 #[test]
1535 fn equality_is_component_wise(a in arb_output_ref(), b in arb_output_ref()) {
1536 let components_equal = a.txid() == b.txid()
1537 && a.pool() == b.pool()
1538 && a.output_index() == b.output_index();
1539 prop_assert_eq!(a == b, components_equal);
1540 }
1541 }
1542}
1543
1544#[cfg(all(test, feature = "transparent-inputs"))]
1545mod transparent_observation_tests {
1546 use ::transparent::{
1547 address::{Script, TransparentAddress},
1548 bundle::{Authorized as TransparentAuthorized, Bundle, OutPoint, TxIn, TxOut},
1549 util::hash160,
1550 };
1551 use zcash_primitives::transaction::{Authorized, Transaction, TransactionData, TxVersion};
1552 use zcash_protocol::{
1553 consensus::{BlockHeight, BranchId},
1554 value::Zatoshis,
1555 };
1556 use zcash_script::script;
1557
1558 use proptest::prelude::*;
1559
1560 use super::{
1561 TransparentAddressObservation, TransparentInvolvement, address_from_script_sig,
1562 transparent_address_observations,
1563 };
1564
1565 /// The `OP_CHECKSIG` opcode, which is not a push and so makes a `scriptSig` unreadable.
1566 const OP_CHECKSIG: u8 = 0xAC;
1567
1568 /// A validly-encoded compressed public key: the `0x02` prefix followed by 32 bytes.
1569 fn pubkey_bytes() -> Vec<u8> {
1570 let mut bytes = vec![0x02];
1571 bytes.extend_from_slice(&[0x11; 32]);
1572 bytes
1573 }
1574
1575 /// Builds a push-only script from the given data pushes. Each push is at most 75 bytes, so
1576 /// each is encoded as its own length byte followed by its data.
1577 fn push_script(pushes: &[&[u8]]) -> Script {
1578 let mut code = vec![];
1579 for data in pushes {
1580 assert!(
1581 data.len() < 76,
1582 "test pushes use the single-byte length form"
1583 );
1584 code.push(u8::try_from(data.len()).expect("checked above"));
1585 code.extend_from_slice(data);
1586 }
1587 Script(script::Code(code))
1588 }
1589
1590 fn tx_from_bundle(bundle: Bundle<TransparentAuthorized, Zatoshis>) -> Transaction {
1591 TransactionData::<Authorized>::from_parts(
1592 TxVersion::V5,
1593 BranchId::Nu5,
1594 0,
1595 BlockHeight::from(0),
1596 Some(bundle),
1597 None,
1598 None,
1599 None,
1600 )
1601 .freeze()
1602 .expect("transaction data is complete")
1603 }
1604
1605 /// A two-push `scriptSig` whose final push is a valid public key encoding is read as a
1606 /// P2PKH spend, so the revealed address is the HASH160 of that public key.
1607 #[test]
1608 fn script_sig_address_reads_p2pkh_shape() {
1609 let pubkey = pubkey_bytes();
1610 let script_sig = push_script(&[&[0x30; 71], &pubkey]);
1611
1612 assert_eq!(
1613 address_from_script_sig(&script_sig),
1614 Some(TransparentAddress::PublicKeyHash(hash160::hash(&pubkey)))
1615 );
1616 }
1617
1618 /// Any other push-only `scriptSig` is read as a P2SH spend, so the revealed address is the
1619 /// HASH160 of its final push, which is the redeem script.
1620 #[test]
1621 fn script_sig_address_reads_p2sh_shape() {
1622 let redeem_script = vec![0xAB; 40];
1623 let script_sig = push_script(&[&[0x30; 71], &[0x30; 71], &redeem_script]);
1624
1625 assert_eq!(
1626 address_from_script_sig(&script_sig),
1627 Some(TransparentAddress::ScriptHash(hash160::hash(
1628 &redeem_script
1629 )))
1630 );
1631 }
1632
1633 /// A `scriptSig` that is empty, or that contains an opcode that is not a push, reveals no
1634 /// address. Both are chain data the wallet does not control, so neither is an error.
1635 #[test]
1636 fn script_sig_address_rejects_unusable_scripts() {
1637 assert_eq!(address_from_script_sig(&Script(script::Code(vec![]))), None);
1638 assert_eq!(
1639 address_from_script_sig(&Script(script::Code(vec![OP_CHECKSIG]))),
1640 None
1641 );
1642 }
1643
1644 /// Both involvement directions are extracted from a complete transaction, indexed by
1645 /// position within `vout` and `vin` respectively.
1646 #[test]
1647 fn observations_cover_both_directions() {
1648 let recipient = TransparentAddress::PublicKeyHash([0x22; 20]);
1649 let pubkey = pubkey_bytes();
1650 let prevout = OutPoint::new([0x33; 32], 7);
1651 let value = Zatoshis::const_from_u64(1000);
1652
1653 let bundle = Bundle::<TransparentAuthorized, Zatoshis> {
1654 vin: vec![TxIn::from_parts(
1655 prevout.clone(),
1656 push_script(&[&[0x30; 71], &pubkey]),
1657 0,
1658 )],
1659 vout: vec![TxOut::new(value, Script::from(&recipient.script()))],
1660 authorization: TransparentAuthorized,
1661 };
1662
1663 assert_eq!(
1664 transparent_address_observations(&tx_from_bundle(bundle)),
1665 vec![
1666 TransparentAddressObservation::output(0, recipient, value),
1667 TransparentAddressObservation::input(
1668 0,
1669 TransparentAddress::PublicKeyHash(hash160::hash(&pubkey)),
1670 prevout,
1671 ),
1672 ]
1673 );
1674 }
1675
1676 proptest! {
1677 /// Script data comes from the chain, so `address_from_script_sig` must be total over
1678 /// arbitrary bytes: it may recognize no address, but it may not panic, and whatever it
1679 /// recognizes must be the HASH160 of the script's final push.
1680 #[test]
1681 fn script_sig_address_is_total(code in prop::collection::vec(any::<u8>(), 0..300)) {
1682 let script = Script(script::Code(code.clone()));
1683 let recognized = address_from_script_sig(&script);
1684
1685 match script::Sig::parse(&script.0).ok().map(|sig| sig.0) {
1686 // A push-only script with at least one push always names an address, and that
1687 // address is the HASH160 of its final push.
1688 Some(pushes) if !pushes.is_empty() => {
1689 let expected = hash160::hash(&pushes.last().unwrap().value());
1690 prop_assert_eq!(
1691 recognized.map(|address| match address {
1692 TransparentAddress::PublicKeyHash(h) => h,
1693 TransparentAddress::ScriptHash(h) => h,
1694 }),
1695 Some(expected)
1696 );
1697 }
1698 // Anything else names none.
1699 _ => prop_assert_eq!(recognized, None),
1700 }
1701 }
1702
1703 /// Observation extraction is likewise total: arbitrary `scriptSig` bytes on a
1704 /// transaction's inputs yield observations or none, never a panic, and every observation
1705 /// index addresses a real item of the transaction.
1706 #[test]
1707 fn observations_are_total(
1708 script_sigs in prop::collection::vec(
1709 prop::collection::vec(any::<u8>(), 0..80),
1710 0..4,
1711 ),
1712 output_count in 0usize..4,
1713 ) {
1714 let bundle = Bundle::<TransparentAuthorized, Zatoshis> {
1715 vin: script_sigs
1716 .iter()
1717 .enumerate()
1718 .map(|(i, code)| {
1719 TxIn::from_parts(
1720 OutPoint::new([u8::try_from(i).unwrap(); 32], 0),
1721 Script(script::Code(code.clone())),
1722 0,
1723 )
1724 })
1725 .collect(),
1726 vout: (0..output_count)
1727 .map(|i| {
1728 TxOut::new(
1729 Zatoshis::const_from_u64(1),
1730 Script::from(
1731 &TransparentAddress::PublicKeyHash([u8::try_from(i).unwrap(); 20])
1732 .script(),
1733 ),
1734 )
1735 })
1736 .collect(),
1737 authorization: TransparentAuthorized,
1738 };
1739 let tx = tx_from_bundle(bundle);
1740 let is_coinbase = zcash_primitives::transaction::coinbase::is_coinbase(&tx);
1741
1742 for observation in transparent_address_observations(&tx) {
1743 let index = usize::try_from(observation.item_index()).unwrap();
1744 match observation.involvement() {
1745 TransparentInvolvement::Output(_) => prop_assert!(index < output_count),
1746 TransparentInvolvement::Input(_) => {
1747 prop_assert!(!is_coinbase);
1748 prop_assert!(index < script_sigs.len());
1749 }
1750 }
1751 }
1752 }
1753 }
1754
1755 /// A coinbase transaction's single input carries arbitrary data and spends the null
1756 /// outpoint, so it contributes no input observation.
1757 #[test]
1758 fn observations_skip_coinbase_inputs() {
1759 let recipient = TransparentAddress::PublicKeyHash([0x44; 20]);
1760 let value = Zatoshis::const_from_u64(500);
1761
1762 let bundle = Bundle::<TransparentAuthorized, Zatoshis> {
1763 vin: vec![TxIn::from_parts(
1764 OutPoint::NULL,
1765 push_script(&[&[0x01, 0x02, 0x03]]),
1766 0,
1767 )],
1768 vout: vec![TxOut::new(value, Script::from(&recipient.script()))],
1769 authorization: TransparentAuthorized,
1770 };
1771
1772 assert_eq!(
1773 transparent_address_observations(&tx_from_bundle(bundle)),
1774 vec![TransparentAddressObservation::output(0, recipient, value)]
1775 );
1776 }
1777}