Skip to main content

zcash_client_backend/
proto.rs

1//! This module contains generated code for handling light client protobuf structs.
2
3use incrementalmerkletree::frontier::CommitmentTree;
4use nonempty::NonEmpty;
5use std::{
6    array::TryFromSliceError,
7    collections::BTreeMap,
8    fmt::{self, Display},
9    io,
10    num::NonZeroU32,
11};
12use zcash_address::unified::{self, Encoding};
13
14use self::proposal::proposed_input;
15// `parse_standard_proposal` matches the input value's variants bare.
16use self::proposal::proposed_input::Value::*;
17use self::proposal::{PriorStepChange, PriorStepOutput, ReceivedOutput};
18
19use sapling::{self, Node, note::ExtractedNoteCommitment};
20use zcash_note_encryption::EphemeralKeyBytes;
21use zcash_primitives::{
22    block::{BlockHash, BlockHeader},
23    merkle_tree::read_commitment_tree,
24    transaction::{TxId, TxVersion},
25};
26use zcash_protocol::{
27    PoolType, ShieldedPool,
28    consensus::{self, BlockHeight, NetworkType},
29    memo::{self, MemoBytes},
30    value::Zatoshis,
31};
32use zip321::{TransactionRequest, Zip321Error};
33
34use crate::{
35    data_api::{
36        InputSource,
37        chain::ChainState,
38        wallet::{ConfirmationsPolicy, TargetHeight, input_selection::LockFilter},
39    },
40    fees::{ChangeValue, DummyOutputCounts, StandardFeeRule, TransactionBalance},
41    proposal::{
42        Proposal, ProposalError, ShieldedInputs, Step, StepOutput, StepOutputIndex,
43        produces_shielded_bundle,
44    },
45};
46
47#[cfg(feature = "transparent-inputs")]
48use transparent::bundle::OutPoint;
49
50#[cfg(feature = "orchard")]
51use orchard::tree::MerkleHashOrchard;
52
53#[rustfmt::skip]
54#[allow(unknown_lints)]
55#[allow(clippy::derive_partial_eq_without_eq)]
56#[allow(clippy::doc_overindented_list_items)]
57pub mod compact_formats;
58
59#[rustfmt::skip]
60#[allow(unknown_lints)]
61#[allow(clippy::derive_partial_eq_without_eq)]
62#[allow(clippy::doc_overindented_list_items)]
63pub mod proposal;
64
65#[rustfmt::skip]
66#[allow(unknown_lints)]
67#[allow(clippy::derive_partial_eq_without_eq)]
68#[allow(clippy::doc_overindented_list_items)]
69pub mod service;
70
71impl compact_formats::CompactBlock {
72    /// Returns the [`BlockHash`] for this block.
73    ///
74    /// # Panics
75    ///
76    /// This function will panic if [`field@Self::header`] is not set and
77    /// [`field@Self::hash`] is not exactly 32 bytes.
78    pub fn hash(&self) -> BlockHash {
79        if let Some(header) = self.header() {
80            header.hash()
81        } else {
82            BlockHash::from_slice(&self.hash)
83        }
84    }
85
86    /// Returns the [`BlockHash`] for this block's parent.
87    ///
88    /// # Panics
89    ///
90    /// This function will panic if [`field@Self::header`] is not set and
91    /// [`field@Self::prev_hash`] is not exactly 32 bytes.
92    pub fn prev_hash(&self) -> BlockHash {
93        if let Some(header) = self.header() {
94            header.prev_block
95        } else {
96            BlockHash::from_slice(&self.prev_hash)
97        }
98    }
99
100    /// Returns the [`BlockHeight`] value for this block
101    ///
102    /// # Panics
103    ///
104    /// This function will panic if [`field@Self::height`] is not representable within a
105    /// `u32`.
106    pub fn height(&self) -> BlockHeight {
107        self.height.try_into().unwrap()
108    }
109
110    /// Returns the [`BlockHeader`] for this block if present.
111    ///
112    /// A convenience method that parses [`field@Self::header`] if present.
113    pub fn header(&self) -> Option<BlockHeader> {
114        if self.header.is_empty() {
115            None
116        } else {
117            BlockHeader::read(&self.header[..]).ok()
118        }
119    }
120}
121
122impl compact_formats::CompactTx {
123    /// Returns the transaction Id
124    pub fn txid(&self) -> TxId {
125        let mut txid_bytes = [0u8; 32];
126        txid_bytes.copy_from_slice(&self.txid);
127        TxId::from_bytes(txid_bytes)
128    }
129}
130
131/// An error indicating that a field of a compact format structure could not be parsed.
132#[derive(Clone, Debug)]
133#[non_exhaustive]
134pub enum CompactFormatError {
135    /// A byte slice had an invalid length for the expected field.
136    InvalidLength(TryFromSliceError),
137    /// A field value did not represent a valid protocol element.
138    InvalidValue,
139}
140
141impl Display for CompactFormatError {
142    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
143        match self {
144            CompactFormatError::InvalidLength(e) => write!(f, "Invalid compact format field: {e}"),
145            CompactFormatError::InvalidValue => {
146                write!(f, "Compact format field is not a valid protocol element")
147            }
148        }
149    }
150}
151
152impl compact_formats::CompactSaplingOutput {
153    /// Returns the note commitment for this output.
154    ///
155    /// A convenience method that parses [`field@Self::cmu`].
156    pub fn cmu(&self) -> Result<ExtractedNoteCommitment, CompactFormatError> {
157        let mut repr = [0; 32];
158        repr.copy_from_slice(&self.cmu[..]);
159        Option::from(ExtractedNoteCommitment::from_bytes(&repr))
160            .ok_or(CompactFormatError::InvalidValue)
161    }
162
163    /// Returns the ephemeral public key for this output.
164    ///
165    /// A convenience method that parses [`field@Self::ephemeral_key`].
166    pub fn ephemeral_key(&self) -> Result<EphemeralKeyBytes, CompactFormatError> {
167        self.ephemeral_key[..]
168            .try_into()
169            .map(EphemeralKeyBytes)
170            .map_err(CompactFormatError::InvalidLength)
171    }
172}
173
174impl<Proof> From<&sapling::bundle::OutputDescription<Proof>>
175    for compact_formats::CompactSaplingOutput
176{
177    fn from(
178        out: &sapling::bundle::OutputDescription<Proof>,
179    ) -> compact_formats::CompactSaplingOutput {
180        compact_formats::CompactSaplingOutput {
181            cmu: out.cmu().to_bytes().to_vec(),
182            ephemeral_key: out.ephemeral_key().as_ref().to_vec(),
183            ciphertext: out.enc_ciphertext()[..sapling::note_encryption::COMPACT_NOTE_SIZE]
184                .to_vec(),
185        }
186    }
187}
188
189impl TryFrom<compact_formats::CompactSaplingOutput>
190    for sapling::note_encryption::CompactOutputDescription
191{
192    type Error = CompactFormatError;
193
194    fn try_from(value: compact_formats::CompactSaplingOutput) -> Result<Self, Self::Error> {
195        (&value).try_into()
196    }
197}
198
199impl TryFrom<&compact_formats::CompactSaplingOutput>
200    for sapling::note_encryption::CompactOutputDescription
201{
202    type Error = CompactFormatError;
203
204    fn try_from(value: &compact_formats::CompactSaplingOutput) -> Result<Self, Self::Error> {
205        Ok(sapling::note_encryption::CompactOutputDescription {
206            cmu: value.cmu()?,
207            ephemeral_key: value.ephemeral_key()?,
208            enc_ciphertext: value.ciphertext[..]
209                .try_into()
210                .map_err(CompactFormatError::InvalidLength)?,
211        })
212    }
213}
214
215impl compact_formats::CompactSaplingSpend {
216    /// Returns the nullifier for this spend.
217    ///
218    /// A convenience method that parses [`field@Self::nf`].
219    pub fn nf(&self) -> Result<sapling::Nullifier, CompactFormatError> {
220        sapling::Nullifier::from_slice(&self.nf).map_err(CompactFormatError::InvalidLength)
221    }
222}
223
224#[cfg(feature = "transparent-inputs")]
225impl compact_formats::CompactTxIn {
226    /// Returns the outpoint of the transparent output that this input spends.
227    ///
228    /// A convenience method that parses [`field@Self::prevout_txid`] and
229    /// [`field@Self::prevout_index`].
230    pub fn prevout(&self) -> Result<transparent::bundle::OutPoint, CompactFormatError> {
231        Ok(transparent::bundle::OutPoint::new(
232            self.prevout_txid[..]
233                .try_into()
234                .map_err(CompactFormatError::InvalidLength)?,
235            self.prevout_index,
236        ))
237    }
238}
239
240#[cfg(feature = "transparent-inputs")]
241impl compact_formats::TxOut {
242    /// Returns the transparent output that this message describes.
243    ///
244    /// A convenience method that parses [`field@Self::value`] and [`field@Self::script_pub_key`].
245    ///
246    /// # Errors
247    /// Returns [`CompactFormatError::InvalidValue`] if the value is not a valid amount of
248    /// zatoshis.
249    pub fn to_txout(&self) -> Result<transparent::bundle::TxOut<Zatoshis>, CompactFormatError> {
250        Ok(transparent::bundle::TxOut::new(
251            Zatoshis::from_u64(self.value).map_err(|_| CompactFormatError::InvalidValue)?,
252            transparent::address::Script(zcash_script::script::Code(self.script_pub_key.clone())),
253        ))
254    }
255}
256
257#[cfg(feature = "orchard")]
258impl TryFrom<&compact_formats::CompactOrchardAction> for orchard::note_encryption::CompactAction {
259    type Error = CompactFormatError;
260
261    fn try_from(value: &compact_formats::CompactOrchardAction) -> Result<Self, Self::Error> {
262        Ok(orchard::note_encryption::CompactAction::from_parts(
263            value.nf()?,
264            value.cmx()?,
265            value.ephemeral_key()?,
266            value.ciphertext[..]
267                .try_into()
268                .map_err(CompactFormatError::InvalidLength)?,
269        ))
270    }
271}
272
273#[cfg(feature = "orchard")]
274impl compact_formats::CompactOrchardAction {
275    /// Returns the note commitment for the output of this action.
276    ///
277    /// A convenience method that parses [`field@Self::cmx`].
278    pub fn cmx(&self) -> Result<orchard::note::ExtractedNoteCommitment, CompactFormatError> {
279        Option::from(orchard::note::ExtractedNoteCommitment::from_bytes(
280            &self.cmx[..]
281                .try_into()
282                .map_err(CompactFormatError::InvalidLength)?,
283        ))
284        .ok_or(CompactFormatError::InvalidValue)
285    }
286
287    /// Returns the nullifier for the spend of this action.
288    ///
289    /// A convenience method that parses [`field@Self::nullifier`].
290    pub fn nf(&self) -> Result<orchard::note::Nullifier, CompactFormatError> {
291        let nf_bytes: [u8; 32] = self.nullifier[..]
292            .try_into()
293            .map_err(CompactFormatError::InvalidLength)?;
294        Option::from(orchard::note::Nullifier::from_bytes(&nf_bytes))
295            .ok_or(CompactFormatError::InvalidValue)
296    }
297
298    /// Returns the ephemeral public key for the output of this action.
299    ///
300    /// A convenience method that parses [`field@Self::ephemeral_key`].
301    pub fn ephemeral_key(&self) -> Result<EphemeralKeyBytes, CompactFormatError> {
302        self.ephemeral_key[..]
303            .try_into()
304            .map(EphemeralKeyBytes)
305            .map_err(CompactFormatError::InvalidLength)
306    }
307}
308
309impl<A: sapling::bundle::Authorization> From<&sapling::bundle::SpendDescription<A>>
310    for compact_formats::CompactSaplingSpend
311{
312    fn from(spend: &sapling::bundle::SpendDescription<A>) -> compact_formats::CompactSaplingSpend {
313        compact_formats::CompactSaplingSpend {
314            nf: spend.nullifier().to_vec(),
315        }
316    }
317}
318
319#[cfg(feature = "orchard")]
320impl<SpendAuth> From<&orchard::Action<SpendAuth>> for compact_formats::CompactOrchardAction {
321    fn from(action: &orchard::Action<SpendAuth>) -> compact_formats::CompactOrchardAction {
322        compact_formats::CompactOrchardAction {
323            nullifier: action.nullifier().to_bytes().to_vec(),
324            cmx: action.cmx().to_bytes().to_vec(),
325            ephemeral_key: action.encrypted_note().epk_bytes.to_vec(),
326            ciphertext: action.encrypted_note().enc_ciphertext.0
327                [..orchard::note_encryption::COMPACT_NOTE_SIZE]
328                .to_vec(),
329        }
330    }
331}
332
333impl service::LightdInfo {
334    /// Returns the network type for the chain this server is following, or `None` if it
335    /// is not recognised.
336    pub fn chain_name(&self) -> Option<NetworkType> {
337        match self.chain_name.as_str() {
338            "main" => Some(NetworkType::Main),
339            "test" => Some(NetworkType::Test),
340            "regtest" => Some(NetworkType::Regtest),
341            _ => None,
342        }
343    }
344
345    /// Returns the Sapling activation height for the chain this server is following.
346    ///
347    /// # Panics
348    ///
349    /// This function will panic if [`field@Self::sapling_activation_height`] is not
350    /// representable within a `u32`.
351    pub fn sapling_activation_height(&self) -> BlockHeight {
352        self.sapling_activation_height
353            .try_into()
354            .expect("lightwalletd should provide in-range heights")
355    }
356
357    /// Returns the current consensus branch ID for the chain tip of the chain this server
358    /// is following, or `None` if it is not recognised.
359    pub fn consensus_branch_id(&self) -> Option<consensus::BranchId> {
360        u32::from_str_radix(&self.consensus_branch_id, 16)
361            .ok()?
362            .try_into()
363            .ok()
364    }
365
366    /// Returns the chain tip height reported by the full node backing this server.
367    ///
368    /// If the full node is still syncing, this may not be the network's chain tip; in
369    /// this case, [`Self::estimated_height`] will report a larger height.
370    ///
371    /// # Panics
372    ///
373    /// This function will panic if [`field@Self::block_height`] is not representable
374    /// within a `u32`.
375    pub fn block_height(&self) -> BlockHeight {
376        self.block_height
377            .try_into()
378            .expect("lightwalletd should provide in-range heights")
379    }
380
381    /// Returns the estimated chain tip height for the chain this server is following.
382    ///
383    /// If the full node backing this server is fully synced, this is always equal to
384    /// [`Self::block_height`].
385    ///
386    /// # Panics
387    ///
388    /// This function will panic if [`field@Self::estimated_height`] is not representable
389    /// within a `u32`.
390    pub fn estimated_height(&self) -> BlockHeight {
391        self.estimated_height
392            .try_into()
393            .expect("lightwalletd should provide in-range heights")
394    }
395
396    /// Returns the donation address for this server.
397    ///
398    /// Returns `None` if:
399    /// - no donation address was provided.
400    /// - the provided donation address is not a valid [`unified::Address`].
401    /// - the provided donation address is for a different chain.
402    pub fn donation_address(&self) -> Option<unified::Address> {
403        if self.donation_address.is_empty() {
404            None
405        } else {
406            let (network_type, _revision, address) =
407                unified::Address::decode(&self.donation_address).ok()?;
408            (Some(network_type) == self.chain_name()).then_some(address)
409        }
410    }
411}
412
413impl service::TreeState {
414    /// Deserializes and returns the Sapling note commitment tree field of the tree state.
415    pub fn sapling_tree(
416        &self,
417    ) -> io::Result<CommitmentTree<Node, { sapling::NOTE_COMMITMENT_TREE_DEPTH }>> {
418        if self.sapling_tree.is_empty() {
419            Ok(CommitmentTree::empty())
420        } else {
421            let sapling_tree_bytes = hex::decode(&self.sapling_tree).map_err(|e| {
422                io::Error::new(
423                    io::ErrorKind::InvalidData,
424                    format!("Hex decoding of Sapling tree bytes failed: {e:?}"),
425                )
426            })?;
427            read_commitment_tree::<Node, _, { sapling::NOTE_COMMITMENT_TREE_DEPTH }>(
428                &sapling_tree_bytes[..],
429            )
430        }
431    }
432
433    /// Deserializes and returns the Sapling note commitment tree field of the tree state.
434    #[cfg(feature = "orchard")]
435    pub fn orchard_tree(
436        &self,
437    ) -> io::Result<CommitmentTree<MerkleHashOrchard, { orchard::NOTE_COMMITMENT_TREE_DEPTH as u8 }>>
438    {
439        if self.orchard_tree.is_empty() {
440            Ok(CommitmentTree::empty())
441        } else {
442            let orchard_tree_bytes = hex::decode(&self.orchard_tree).map_err(|e| {
443                io::Error::new(
444                    io::ErrorKind::InvalidData,
445                    format!("Hex decoding of Orchard tree bytes failed: {e:?}"),
446                )
447            })?;
448            read_commitment_tree::<
449                MerkleHashOrchard,
450                _,
451                { orchard::NOTE_COMMITMENT_TREE_DEPTH as u8 },
452            >(&orchard_tree_bytes[..])
453        }
454    }
455
456    /// Deserializes and returns the Ironwood note commitment tree field of the tree state.
457    ///
458    /// The Ironwood tree is Orchard-shaped, but Ironwood is a distinct pool tracked separately
459    /// from Orchard. An empty field yields an empty tree, which is the correct treestate at the
460    /// Ironwood pool's activation.
461    #[cfg(feature = "orchard")]
462    pub fn ironwood_tree(
463        &self,
464    ) -> io::Result<CommitmentTree<MerkleHashOrchard, { orchard::NOTE_COMMITMENT_TREE_DEPTH as u8 }>>
465    {
466        if self.ironwood_tree.is_empty() {
467            Ok(CommitmentTree::empty())
468        } else {
469            let ironwood_tree_bytes = hex::decode(&self.ironwood_tree).map_err(|e| {
470                io::Error::new(
471                    io::ErrorKind::InvalidData,
472                    format!("Hex decoding of Ironwood tree bytes failed: {e:?}"),
473                )
474            })?;
475            read_commitment_tree::<
476                MerkleHashOrchard,
477                _,
478                { orchard::NOTE_COMMITMENT_TREE_DEPTH as u8 },
479            >(&ironwood_tree_bytes[..])
480        }
481    }
482
483    /// Parses this tree state into a [`ChainState`] for use with [`scan_cached_blocks`].
484    ///
485    /// [`scan_cached_blocks`]: crate::data_api::chain::scan_cached_blocks
486    pub fn to_chain_state(&self) -> io::Result<ChainState> {
487        let hash = BlockHash::from_hex(&self.hash).map_err(|e| {
488            io::Error::new(
489                io::ErrorKind::InvalidData,
490                format!("Invalid block hash: {e}"),
491            )
492        })?;
493
494        Ok(ChainState::new(
495            self.height
496                .try_into()
497                .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid block height"))?,
498            hash,
499            self.sapling_tree()?.to_frontier(),
500            #[cfg(feature = "orchard")]
501            self.orchard_tree()?.to_frontier(),
502            #[cfg(feature = "orchard")]
503            self.ironwood_tree()?.to_frontier(),
504        ))
505    }
506}
507
508/// Constant for the V1 proposal serialization version.
509pub const PROPOSAL_SER_V1: u32 = 1;
510
511/// Errors that can occur in the process of decoding a [`Proposal`] from its protobuf
512/// representation.
513#[derive(Debug, Clone)]
514#[non_exhaustive]
515pub enum ProposalDecodingError<DbError> {
516    /// The encoded proposal contained no steps.
517    NoSteps,
518    /// The ZIP 321 transaction request URI was invalid.
519    Zip321(Zip321Error),
520    /// A proposed input was null.
521    NullInput(usize),
522    /// A transaction identifier string did not decode to a valid transaction ID.
523    TxIdInvalid(TryFromSliceError),
524    /// An invalid value pool identifier was encountered.
525    ValuePoolNotSupported(i32),
526    /// A failure occurred trying to retrieve an unspent note or UTXO from the wallet database.
527    InputRetrieval(DbError),
528    /// The unspent note or UTXO corresponding to a proposal input was not found in the wallet
529    /// database.
530    InputNotFound(TxId, PoolType, u32),
531    /// The transaction balance, or a component thereof, failed to decode correctly.
532    BalanceInvalid,
533    /// Failed to decode a ZIP-302-compliant memo from the provided memo bytes.
534    MemoInvalid(memo::Error),
535    /// The serialization version returned by the protobuf was not recognized.
536    VersionInvalid(u32),
537    /// The fee rule specified by the proposal is not supported by the wallet.
538    FeeRuleNotSupported(proposal::FeeRule),
539    /// The proposal violated balance or structural constraints.
540    ProposalInvalid(ProposalError),
541    /// An inputs field for the given protocol was present, but contained no input note references.
542    EmptyShieldedInputs(ShieldedPool),
543    /// A memo field was provided for a transparent output.
544    TransparentMemo,
545    /// Change outputs to the specified pool are not supported.
546    InvalidChangeRecipient(PoolType),
547    /// Ephemeral outputs to the specified pool are not supported.
548    InvalidEphemeralRecipient(PoolType),
549    /// The encoded confirmations policy was not valid (for example, a zero confirmation count or
550    /// trusted confirmations exceeding untrusted).
551    ConfirmationsPolicyInvalid,
552    /// A payment was directed to the Orchard pool while Ironwood is active at the proposal's target
553    /// height. Once Ironwood is active, Orchard-receiver payments target the Ironwood pool and only
554    /// change may return to Orchard, so such a payment cannot appear in a well-formed proposal.
555    OrchardPaymentProhibited,
556    /// A proposal step produces a shielded bundle (it spends shielded notes, pays to a shielded
557    /// pool, or returns shielded change) but its encoded anchor height is the zero sentinel. Every
558    /// shielded-tree lookup the step performs — including the dummy spends that pad an output-only
559    /// bundle — must be bound to a real anchor, so this combination cannot appear in a well-formed
560    /// proposal.
561    MissingShieldedAnchor,
562    /// The proposal specified an explicit transaction version header that the wallet does not
563    /// recognize.
564    ProposedVersionInvalid(u32),
565}
566
567impl<E> From<Zip321Error> for ProposalDecodingError<E> {
568    fn from(value: Zip321Error) -> Self {
569        Self::Zip321(value)
570    }
571}
572
573impl<E: Display> Display for ProposalDecodingError<E> {
574    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
575        match self {
576            ProposalDecodingError::NoSteps => write!(f, "The proposal had no steps."),
577            ProposalDecodingError::Zip321(err) => write!(f, "Transaction request invalid: {err}"),
578            ProposalDecodingError::NullInput(i) => {
579                write!(f, "Proposed input was null at index {i}")
580            }
581            ProposalDecodingError::TxIdInvalid(err) => {
582                write!(f, "Invalid transaction id: {err:?}")
583            }
584            ProposalDecodingError::ValuePoolNotSupported(id) => {
585                write!(f, "Invalid value pool identifier: {id:?}")
586            }
587            ProposalDecodingError::InputRetrieval(err) => {
588                write!(f, "An error occurred retrieving a transaction input: {err}")
589            }
590            ProposalDecodingError::InputNotFound(txid, pool, idx) => {
591                write!(f, "No {pool} input found for txid {txid}, index {idx}")
592            }
593            ProposalDecodingError::BalanceInvalid => {
594                write!(f, "An error occurred decoding the proposal balance.")
595            }
596            ProposalDecodingError::MemoInvalid(err) => {
597                write!(f, "An error occurred decoding a proposed memo: {err}")
598            }
599            ProposalDecodingError::VersionInvalid(v) => {
600                write!(f, "Unrecognized proposal version {v}")
601            }
602            ProposalDecodingError::FeeRuleNotSupported(r) => {
603                write!(
604                    f,
605                    "Fee calculation using the {r:?} fee rule is not supported."
606                )
607            }
608            ProposalDecodingError::ProposalInvalid(err) => write!(f, "{err}"),
609            ProposalDecodingError::EmptyShieldedInputs(protocol) => write!(
610                f,
611                "An inputs field was present for {protocol:?}, but contained no note references."
612            ),
613            ProposalDecodingError::TransparentMemo => {
614                write!(f, "Transparent outputs cannot have memos.")
615            }
616            ProposalDecodingError::InvalidChangeRecipient(pool_type) => write!(
617                f,
618                "Change outputs to the {pool_type} pool are not supported."
619            ),
620            ProposalDecodingError::InvalidEphemeralRecipient(pool_type) => write!(
621                f,
622                "Ephemeral outputs to the {pool_type} pool are not supported."
623            ),
624            ProposalDecodingError::ConfirmationsPolicyInvalid => {
625                write!(f, "The encoded confirmations policy was not valid.")
626            }
627            ProposalDecodingError::OrchardPaymentProhibited => write!(
628                f,
629                "A payment may not be directed to the Orchard pool once Ironwood is active."
630            ),
631            ProposalDecodingError::MissingShieldedAnchor => write!(
632                f,
633                "A proposal step that produces a shielded bundle must specify an anchor height."
634            ),
635            ProposalDecodingError::ProposedVersionInvalid(header) => write!(
636                f,
637                "The proposal specified an unrecognized transaction version header {header:#x}."
638            ),
639        }
640    }
641}
642
643impl<E: std::error::Error + 'static> std::error::Error for ProposalDecodingError<E> {
644    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
645        match self {
646            ProposalDecodingError::Zip321(e) => Some(e),
647            ProposalDecodingError::InputRetrieval(e) => Some(e),
648            ProposalDecodingError::MemoInvalid(e) => Some(e),
649            _ => None,
650        }
651    }
652}
653
654fn pool_type<T>(pool_id: i32) -> Result<PoolType, ProposalDecodingError<T>> {
655    match proposal::ValuePool::try_from(pool_id) {
656        Ok(proposal::ValuePool::Transparent) => Ok(PoolType::TRANSPARENT),
657        Ok(proposal::ValuePool::Sapling) => Ok(PoolType::SAPLING),
658        Ok(proposal::ValuePool::Orchard) => Ok(PoolType::ORCHARD),
659        Ok(proposal::ValuePool::Ironwood) => Ok(PoolType::IRONWOOD),
660        _ => Err(ProposalDecodingError::ValuePoolNotSupported(pool_id)),
661    }
662}
663
664impl proposal::ReceivedOutput {
665    pub fn parse_txid(&self) -> Result<TxId, TryFromSliceError> {
666        Ok(TxId::from_bytes(self.txid[..].try_into()?))
667    }
668
669    pub fn pool_type<T>(&self) -> Result<PoolType, ProposalDecodingError<T>> {
670        pool_type(self.value_pool)
671    }
672}
673
674impl proposal::ChangeValue {
675    pub fn pool_type<T>(&self) -> Result<PoolType, ProposalDecodingError<T>> {
676        pool_type(self.value_pool)
677    }
678}
679
680impl From<PoolType> for proposal::ValuePool {
681    fn from(value: PoolType) -> Self {
682        match value {
683            PoolType::Transparent => proposal::ValuePool::Transparent,
684            PoolType::Shielded(p) => p.into(),
685        }
686    }
687}
688
689impl From<ShieldedPool> for proposal::ValuePool {
690    fn from(value: ShieldedPool) -> Self {
691        match value {
692            ShieldedPool::Sapling => proposal::ValuePool::Sapling,
693            ShieldedPool::Orchard => proposal::ValuePool::Orchard,
694            ShieldedPool::Ironwood => proposal::ValuePool::Ironwood,
695        }
696    }
697}
698
699impl proposal::Proposal {
700    /// Serializes a [`Proposal`] based upon a supported [`StandardFeeRule`] to its protobuf
701    /// representation.
702    pub fn from_standard_proposal<NoteRef>(value: &Proposal<StandardFeeRule, NoteRef>) -> Self {
703        let steps = value
704            .steps()
705            .iter()
706            .map(|step| {
707                let transaction_request = step.transaction_request().to_uri();
708
709                // A decoded legacy step that defers its anchor encodes as the zero sentinel.
710                let anchor_height = step.anchor_height().map_or(0, u32::from);
711
712                let inputs = step
713                    .transparent_inputs()
714                    .iter()
715                    .map(|utxo| proposal::ProposedInput {
716                        value: Some(proposed_input::Value::ReceivedOutput(ReceivedOutput {
717                            txid: utxo.outpoint().hash().to_vec(),
718                            value_pool: proposal::ValuePool::Transparent.into(),
719                            index: utxo.outpoint().n(),
720                            value: utxo.txout().value().into(),
721                        })),
722                    })
723                    .chain(step.shielded_inputs().iter().flat_map(|s_in| {
724                        s_in.notes().iter().map(|rec_note| proposal::ProposedInput {
725                            value: Some(proposed_input::Value::ReceivedOutput(ReceivedOutput {
726                                txid: rec_note.txid().as_ref().to_vec(),
727                                value_pool: proposal::ValuePool::from(rec_note.note().pool())
728                                    .into(),
729                                index: rec_note.output_index().into(),
730                                value: rec_note.note().value().into(),
731                            })),
732                        })
733                    }))
734                    .chain(step.prior_step_inputs().iter().map(|p_in| {
735                        match p_in.output_index() {
736                            StepOutputIndex::Payment(i) => proposal::ProposedInput {
737                                value: Some(proposed_input::Value::PriorStepOutput(
738                                    PriorStepOutput {
739                                        step_index: p_in
740                                            .step_index()
741                                            .try_into()
742                                            .expect("Step index fits into a u32"),
743                                        payment_index: i
744                                            .try_into()
745                                            .expect("Payment index fits into a u32"),
746                                    },
747                                )),
748                            },
749                            StepOutputIndex::Change(i) => proposal::ProposedInput {
750                                value: Some(proposed_input::Value::PriorStepChange(
751                                    PriorStepChange {
752                                        step_index: p_in
753                                            .step_index()
754                                            .try_into()
755                                            .expect("Step index fits into a u32"),
756                                        change_index: i
757                                            .try_into()
758                                            .expect("Payment index fits into a u32"),
759                                    },
760                                )),
761                            },
762                        }
763                    }))
764                    .collect();
765
766                let payment_output_pools = step
767                    .payment_pools()
768                    .iter()
769                    .map(|(idx, pool_type)| proposal::PaymentOutputPool {
770                        payment_index: u32::try_from(*idx).expect("Payment index fits into a u32"),
771                        value_pool: proposal::ValuePool::from(*pool_type).into(),
772                    })
773                    .collect();
774
775                let balance = Some(proposal::TransactionBalance {
776                    proposed_change: step
777                        .balance()
778                        .proposed_change()
779                        .iter()
780                        .map(|change| proposal::ChangeValue {
781                            value: change.value().into(),
782                            value_pool: proposal::ValuePool::from(change.output_pool()).into(),
783                            memo: change.memo().map(|memo_bytes| proposal::MemoBytes {
784                                value: memo_bytes.as_slice().to_vec(),
785                            }),
786                            is_ephemeral: change.is_ephemeral(),
787                        })
788                        .collect(),
789                    fee_required: step.balance().fee_required().into(),
790                    dummy_outputs: step.balance().dummy_outputs().map(|counts| {
791                        proposal::DummyOutputs {
792                            sapling: counts
793                                .sapling()
794                                .try_into()
795                                .expect("Sapling dummy-output count fits into u32"),
796                            #[cfg(feature = "orchard")]
797                            orchard: counts
798                                .orchard()
799                                .try_into()
800                                .expect("Orchard dummy-output count fits into u32"),
801                            #[cfg(not(feature = "orchard"))]
802                            orchard: 0,
803                            #[cfg(feature = "orchard")]
804                            ironwood: counts
805                                .ironwood()
806                                .try_into()
807                                .expect("Ironwood dummy-output count fits into u32"),
808                            #[cfg(not(feature = "orchard"))]
809                            ironwood: 0,
810                        }
811                    }),
812                });
813
814                proposal::ProposalStep {
815                    transaction_request,
816                    payment_output_pools,
817                    anchor_height,
818                    inputs,
819                    balance,
820                    is_shielding: step.is_shielding(),
821                }
822            })
823            .collect();
824
825        let confirmations_policy = value.confirmations_policy();
826        proposal::Proposal {
827            proto_version: PROPOSAL_SER_V1,
828            fee_rule: match value.fee_rule() {
829                StandardFeeRule::Zip317 => proposal::FeeRule::Zip317,
830            }
831            .into(),
832            min_target_height: value.min_target_height().into(),
833            steps,
834            confirmations_policy: Some(proposal::ConfirmationsPolicy {
835                trusted: confirmations_policy.trusted().into(),
836                untrusted: confirmations_policy.untrusted().into(),
837                #[cfg(feature = "transparent-inputs")]
838                allow_zero_conf_shielding: confirmations_policy.allow_zero_conf_shielding(),
839                #[cfg(not(feature = "transparent-inputs"))]
840                allow_zero_conf_shielding: true,
841            }),
842            proposed_version: value.proposed_version().map(|v| v.header()),
843        }
844    }
845
846    /// Attempts to parse a [`Proposal`] based upon a supported [`StandardFeeRule`] from its
847    /// protobuf representation.
848    pub fn try_into_standard_proposal<ParamsT, DbT, DbError>(
849        &self,
850        params: &ParamsT,
851        wallet_db: &DbT,
852    ) -> Result<Proposal<StandardFeeRule, DbT::NoteRef>, ProposalDecodingError<DbError>>
853    where
854        ParamsT: consensus::Parameters,
855        DbT: InputSource<Error = DbError>,
856    {
857        match self.proto_version {
858            PROPOSAL_SER_V1 => {
859                let fee_rule = match self.fee_rule() {
860                    proposal::FeeRule::Zip317 => StandardFeeRule::Zip317,
861                    other => {
862                        return Err(ProposalDecodingError::FeeRuleNotSupported(other));
863                    }
864                };
865
866                let target_height = TargetHeight::from(self.min_target_height);
867
868                // A proposal created with `lock_for_blocks` locks its own inputs, so
869                // input retrieval during decoding must not filter locked outputs;
870                // otherwise a locked proposal would fail to round-trip through its
871                // serialized form. Double-spend protection is enforced when the
872                // proposal's transactions are created, not here.
873                let lock_filter = LockFilter::Unfiltered;
874
875                // Steps are checked against the Orchard turnstile when Ironwood is
876                // active at the height for which the proposal was constructed.
877                #[cfg(feature = "orchard")]
878                let ironwood_active = params.is_nu_active(
879                    consensus::NetworkUpgrade::Nu6_3,
880                    BlockHeight::from(target_height),
881                );
882                #[cfg(not(feature = "orchard"))]
883                let _ = params;
884
885                let mut steps = Vec::with_capacity(self.steps.len());
886                for step in &self.steps {
887                    let transaction_request =
888                        TransactionRequest::from_uri(&step.transaction_request)?;
889
890                    let payment_pools = step
891                        .payment_output_pools
892                        .iter()
893                        .map(|pop| {
894                            Ok((
895                                usize::try_from(pop.payment_index)
896                                    .expect("Payment index fits into a usize"),
897                                pool_type(pop.value_pool)?,
898                            ))
899                        })
900                        .collect::<Result<BTreeMap<usize, PoolType>, ProposalDecodingError<DbError>>>()?;
901
902                    // With Ironwood active, no payment may be directed to the Orchard pool: an
903                    // Orchard-receiver payment targets the Ironwood pool, and only change may
904                    // return to Orchard. Reject such a payment from untrusted or legacy input here,
905                    // rather than letting it reach the `debug_assert!` in `Step::from_parts`.
906                    #[cfg(feature = "orchard")]
907                    if ironwood_active
908                        && payment_pools
909                            .values()
910                            .any(|pool| *pool == PoolType::ORCHARD)
911                    {
912                        return Err(ProposalDecodingError::OrchardPaymentProhibited);
913                    }
914
915                    #[allow(unused_mut)]
916                    let mut transparent_inputs = vec![];
917                    let mut received_notes = vec![];
918                    let mut prior_step_inputs = vec![];
919                    for (i, input) in step.inputs.iter().enumerate() {
920                        match input
921                            .value
922                            .as_ref()
923                            .ok_or(ProposalDecodingError::NullInput(i))?
924                        {
925                            ReceivedOutput(out) => {
926                                let txid = out
927                                    .parse_txid()
928                                    .map_err(ProposalDecodingError::TxIdInvalid)?;
929
930                                match out.pool_type()? {
931                                    PoolType::Transparent => {
932                                        #[cfg(not(feature = "transparent-inputs"))]
933                                        return Err(ProposalDecodingError::ValuePoolNotSupported(
934                                            out.value_pool,
935                                        ));
936
937                                        #[cfg(feature = "transparent-inputs")]
938                                        {
939                                            let outpoint = OutPoint::new(txid.into(), out.index);
940                                            transparent_inputs.push(
941                                                wallet_db
942                                                    .get_unspent_transparent_output(
943                                                        &outpoint,
944                                                        target_height,
945                                                    )
946                                                    .map_err(ProposalDecodingError::InputRetrieval)?
947                                                    .ok_or({
948                                                        ProposalDecodingError::InputNotFound(
949                                                            txid,
950                                                            PoolType::TRANSPARENT,
951                                                            out.index,
952                                                        )
953                                                    })?
954                                                    .redact_account_data(),
955                                            );
956                                        }
957                                    }
958                                    PoolType::Shielded(protocol) => received_notes.push(
959                                        wallet_db
960                                            .get_spendable_note(
961                                                &txid,
962                                                protocol,
963                                                out.index,
964                                                target_height,
965                                                lock_filter,
966                                            )
967                                            .map_err(ProposalDecodingError::InputRetrieval)
968                                            .and_then(|opt| {
969                                                opt.ok_or({
970                                                    ProposalDecodingError::InputNotFound(
971                                                        txid,
972                                                        PoolType::Shielded(protocol),
973                                                        out.index,
974                                                    )
975                                                })
976                                            })?,
977                                    ),
978                                }
979                            }
980                            PriorStepOutput(s_ref) => {
981                                prior_step_inputs.push(StepOutput::new(
982                                    s_ref
983                                        .step_index
984                                        .try_into()
985                                        .expect("Step index fits into a usize"),
986                                    StepOutputIndex::Payment(
987                                        s_ref
988                                            .payment_index
989                                            .try_into()
990                                            .expect("Payment index fits into a usize"),
991                                    ),
992                                ));
993                            }
994                            PriorStepChange(s_ref) => {
995                                prior_step_inputs.push(StepOutput::new(
996                                    s_ref
997                                        .step_index
998                                        .try_into()
999                                        .expect("Step index fits into a usize"),
1000                                    StepOutputIndex::Change(
1001                                        s_ref
1002                                            .change_index
1003                                            .try_into()
1004                                            .expect("Payment index fits into a usize"),
1005                                    ),
1006                                ));
1007                            }
1008                        }
1009                    }
1010
1011                    let shielded_inputs =
1012                        NonEmpty::from_vec(received_notes).map(ShieldedInputs::from_parts);
1013
1014                    let proto_balance = step
1015                        .balance
1016                        .as_ref()
1017                        .ok_or(ProposalDecodingError::BalanceInvalid)?;
1018                    let balance = TransactionBalance::new(
1019                        proto_balance
1020                            .proposed_change
1021                            .iter()
1022                            .map(|cv| -> Result<ChangeValue, ProposalDecodingError<_>> {
1023                                let value = Zatoshis::from_u64(cv.value)
1024                                    .map_err(|_| ProposalDecodingError::BalanceInvalid)?;
1025                                let memo = cv
1026                                    .memo
1027                                    .as_ref()
1028                                    .map(|bytes| {
1029                                        MemoBytes::from_bytes(&bytes.value)
1030                                            .map_err(ProposalDecodingError::MemoInvalid)
1031                                    })
1032                                    .transpose()?;
1033                                match (cv.pool_type()?, cv.is_ephemeral) {
1034                                    (PoolType::Shielded(ShieldedPool::Sapling), false) => {
1035                                        Ok(ChangeValue::sapling(value, memo))
1036                                    }
1037                                    #[cfg(feature = "orchard")]
1038                                    (PoolType::Shielded(ShieldedPool::Orchard), false) => {
1039                                        Ok(ChangeValue::orchard(value, memo))
1040                                    }
1041                                    #[cfg(feature = "orchard")]
1042                                    (PoolType::Shielded(ShieldedPool::Ironwood), false) => Ok(
1043                                        ChangeValue::shielded(ShieldedPool::Ironwood, value, memo),
1044                                    ),
1045                                    (PoolType::Transparent, _) if memo.is_some() => {
1046                                        Err(ProposalDecodingError::TransparentMemo)
1047                                    }
1048                                    #[cfg(feature = "transparent-inputs")]
1049                                    (PoolType::Transparent, true) => {
1050                                        Ok(ChangeValue::ephemeral_transparent(value))
1051                                    }
1052                                    #[cfg(feature = "transparent-inputs")]
1053                                    (PoolType::Transparent, false) => {
1054                                        Ok(ChangeValue::transparent(value))
1055                                    }
1056                                    // When all pool features are enabled, the explicit arms above
1057                                    // are exhaustive over the non-ephemeral cases; this fallback
1058                                    // remains reachable when some pool features are disabled.
1059                                    #[allow(unreachable_patterns)]
1060                                    (pool, false) => {
1061                                        Err(ProposalDecodingError::InvalidChangeRecipient(pool))
1062                                    }
1063                                    (pool, true) => {
1064                                        Err(ProposalDecodingError::InvalidEphemeralRecipient(pool))
1065                                    }
1066                                }
1067                            })
1068                            .collect::<Result<Vec<_>, _>>()?,
1069                        Zatoshis::from_u64(proto_balance.fee_required)
1070                            .map_err(|_| ProposalDecodingError::BalanceInvalid)?,
1071                    )
1072                    .map_err(|_| ProposalDecodingError::BalanceInvalid)?;
1073                    let balance = match proto_balance.dummy_outputs.as_ref() {
1074                        Some(counts) => {
1075                            #[cfg(feature = "orchard")]
1076                            let dummy_outputs = DummyOutputCounts::new(
1077                                counts.sapling as usize,
1078                                counts.orchard as usize,
1079                                counts.ironwood as usize,
1080                            );
1081                            #[cfg(not(feature = "orchard"))]
1082                            let dummy_outputs = DummyOutputCounts::new(counts.sapling as usize);
1083                            balance.with_dummy_outputs(dummy_outputs)
1084                        }
1085                        // Older proposals did not explicitly model their dummy outputs.
1086                        None => balance,
1087                    };
1088
1089                    // The `anchorHeight` field's zero value is the wire sentinel for a step that
1090                    // carries no anchor. Only a purely transparent step may lack one: any step that
1091                    // produces a shielded bundle binds every shielded-tree lookup — including the
1092                    // dummy spends that pad an output-only bundle — to a real anchor. Reject the
1093                    // invalid combination here at the parse boundary rather than letting it reach
1094                    // `Step::from_parts`.
1095                    let anchor_height = match step.anchor_height {
1096                        0 if produces_shielded_bundle(
1097                            shielded_inputs.is_some(),
1098                            &payment_pools,
1099                            &balance,
1100                        ) =>
1101                        {
1102                            return Err(ProposalDecodingError::MissingShieldedAnchor);
1103                        }
1104                        0 => None,
1105                        h => Some(BlockHeight::from_u32(h)),
1106                    };
1107
1108                    let step = Step::from_parts(
1109                        &steps,
1110                        transaction_request,
1111                        payment_pools,
1112                        transparent_inputs,
1113                        shielded_inputs,
1114                        anchor_height,
1115                        prior_step_inputs,
1116                        balance,
1117                        step.is_shielding,
1118                        #[cfg(feature = "orchard")]
1119                        ironwood_active,
1120                    )
1121                    .map_err(ProposalDecodingError::ProposalInvalid)?;
1122
1123                    steps.push(step);
1124                }
1125
1126                // Reconstruct the confirmations policy the proposal was built under. Proposals
1127                // serialized before this field existed omit it and are interpreted using the
1128                // default policy.
1129                let confirmations_policy = match &self.confirmations_policy {
1130                    Some(cp) => ConfirmationsPolicy::new(
1131                        NonZeroU32::new(cp.trusted)
1132                            .ok_or(ProposalDecodingError::ConfirmationsPolicyInvalid)?,
1133                        NonZeroU32::new(cp.untrusted)
1134                            .ok_or(ProposalDecodingError::ConfirmationsPolicyInvalid)?,
1135                        #[cfg(feature = "transparent-inputs")]
1136                        cp.allow_zero_conf_shielding,
1137                    )
1138                    .map_err(|_| ProposalDecodingError::ConfirmationsPolicyInvalid)?,
1139                    None => ConfirmationsPolicy::default(),
1140                };
1141
1142                // Recover the explicitly-requested transaction version, if any. Proposals
1143                // serialized before this field existed, or built without a version request, omit
1144                // it and fall back to the version implied by the target height.
1145                let proposed_version = self
1146                    .proposed_version
1147                    .map(|header| {
1148                        if header == TxVersion::V5.header() {
1149                            Ok(TxVersion::V5)
1150                        } else if header == TxVersion::V6.header() {
1151                            Ok(TxVersion::V6)
1152                        } else {
1153                            Err(ProposalDecodingError::ProposedVersionInvalid(header))
1154                        }
1155                    })
1156                    .transpose()?;
1157
1158                Proposal::multi_step(
1159                    fee_rule,
1160                    target_height,
1161                    confirmations_policy,
1162                    NonEmpty::from_vec(steps).ok_or(ProposalDecodingError::NoSteps)?,
1163                )
1164                .map(|proposal| proposal.with_proposed_version(proposed_version))
1165                .map_err(ProposalDecodingError::ProposalInvalid)
1166            }
1167            other => Err(ProposalDecodingError::VersionInvalid(other)),
1168        }
1169    }
1170}
1171
1172#[cfg(feature = "lightwalletd-tonic-transport")]
1173impl service::compact_tx_streamer_client::CompactTxStreamerClient<tonic::transport::Channel> {
1174    /// Attempt to create a new client by connecting to a given endpoint.
1175    pub async fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
1176    where
1177        D: TryInto<tonic::transport::Endpoint>,
1178        D::Error: Into<tonic::codegen::StdError>,
1179    {
1180        let conn = tonic::transport::Endpoint::new(dst)?.connect().await?;
1181        Ok(Self::new(conn))
1182    }
1183}
1184
1185#[cfg(test)]
1186mod tests {
1187    use zcash_primitives::block::BlockHash;
1188
1189    use super::service;
1190
1191    /// An arbitrary block height for the tree states under test.
1192    const TREE_STATE_HEIGHT: u64 = 415_000;
1193
1194    #[test]
1195    fn to_chain_state_parses_block_hash() {
1196        /// A block hash whose bytes in internal (little-endian) order are `0x00, 0x01, ..., 0x1f`.
1197        const ASCENDING_BLOCK_HASH: BlockHash = BlockHash([
1198            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
1199            0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
1200            0x1c, 0x1d, 0x1e, 0x1f,
1201        ]);
1202
1203        /// [`ASCENDING_BLOCK_HASH`] in the byte-reversed hex form served by lightwalletd.
1204        const ASCENDING_BLOCK_HASH_HEX: &str =
1205            "1f1e1d1c1b1a191817161514131211100f0e0d0c0b0a09080706050403020100";
1206
1207        let tree_state = service::TreeState {
1208            height: TREE_STATE_HEIGHT,
1209            hash: ASCENDING_BLOCK_HASH_HEX.into(),
1210            ..Default::default()
1211        };
1212        let chain_state = tree_state.to_chain_state().unwrap();
1213        assert_eq!(chain_state.block_hash(), ASCENDING_BLOCK_HASH);
1214    }
1215
1216    #[test]
1217    fn to_chain_state_rejects_malformed_block_hash() {
1218        let one_byte_short = "00".repeat(31);
1219        let not_hex = "zz".repeat(32);
1220        for hash in ["", "00", one_byte_short.as_str(), not_hex.as_str()] {
1221            let tree_state = service::TreeState {
1222                height: TREE_STATE_HEIGHT,
1223                hash: hash.into(),
1224                ..Default::default()
1225            };
1226            assert!(tree_state.to_chain_state().is_err(), "accepted {hash:?}");
1227        }
1228    }
1229}