zakura-client-backend 0.1.0-rc2

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

use incrementalmerkletree::frontier::CommitmentTree;
use nonempty::NonEmpty;
use std::{
    array::TryFromSliceError,
    collections::BTreeMap,
    fmt::{self, Display},
    io,
    num::NonZeroU32,
};
use zcash_address::unified::{self, Encoding};

use self::proposal::proposed_input;
// `parse_standard_proposal` matches the input value's variants bare.
use self::proposal::proposed_input::Value::*;
use self::proposal::{PriorStepChange, PriorStepOutput, ReceivedOutput};

use sapling::{self, Node, note::ExtractedNoteCommitment};
use zcash_note_encryption::{COMPACT_NOTE_SIZE, EphemeralKeyBytes};
use zcash_primitives::{
    block::{BlockHash, BlockHeader},
    merkle_tree::read_commitment_tree,
    transaction::{TxId, TxVersion},
};
use zcash_protocol::{
    PoolType, ShieldedPool,
    consensus::{self, BlockHeight, NetworkType},
    memo::{self, MemoBytes},
    value::Zatoshis,
};
use zip321::{TransactionRequest, Zip321Error};

use crate::{
    data_api::{
        InputSource,
        chain::ChainState,
        wallet::{ConfirmationsPolicy, TargetHeight, input_selection::LockFilter},
    },
    fees::{ChangeValue, DummyOutputCounts, StandardFeeRule, TransactionBalance},
    proposal::{
        Proposal, ProposalError, ShieldedInputs, Step, StepOutput, StepOutputIndex,
        produces_shielded_bundle,
    },
};

#[cfg(feature = "transparent-inputs")]
use transparent::bundle::OutPoint;

#[cfg(feature = "orchard")]
use orchard::tree::MerkleHashOrchard;

#[rustfmt::skip]
#[allow(unknown_lints)]
#[allow(clippy::derive_partial_eq_without_eq)]
#[allow(clippy::doc_overindented_list_items)]
pub mod compact_formats;

#[rustfmt::skip]
#[allow(unknown_lints)]
#[allow(clippy::derive_partial_eq_without_eq)]
#[allow(clippy::doc_overindented_list_items)]
pub mod proposal;

#[rustfmt::skip]
#[allow(unknown_lints)]
#[allow(clippy::derive_partial_eq_without_eq)]
#[allow(clippy::doc_overindented_list_items)]
pub mod service;

impl compact_formats::CompactBlock {
    /// Returns the [`BlockHash`] for this block.
    ///
    /// # Panics
    ///
    /// This function will panic if [`field@Self::header`] is not set and
    /// [`field@Self::hash`] is not exactly 32 bytes.
    pub fn hash(&self) -> BlockHash {
        if let Some(header) = self.header() {
            header.hash()
        } else {
            BlockHash::from_slice(&self.hash)
        }
    }

    /// Returns the [`BlockHash`] for this block's parent.
    ///
    /// # Panics
    ///
    /// This function will panic if [`field@Self::header`] is not set and
    /// [`field@Self::prev_hash`] is not exactly 32 bytes.
    pub fn prev_hash(&self) -> BlockHash {
        if let Some(header) = self.header() {
            header.prev_block
        } else {
            BlockHash::from_slice(&self.prev_hash)
        }
    }

    /// Returns the [`BlockHeight`] value for this block
    ///
    /// # Panics
    ///
    /// This function will panic if [`field@Self::height`] is not representable within a
    /// `u32`.
    pub fn height(&self) -> BlockHeight {
        self.height.try_into().unwrap()
    }

    /// Returns the [`BlockHeader`] for this block if present.
    ///
    /// A convenience method that parses [`field@Self::header`] if present.
    pub fn header(&self) -> Option<BlockHeader> {
        if self.header.is_empty() {
            None
        } else {
            BlockHeader::read(&self.header[..]).ok()
        }
    }
}

impl compact_formats::CompactTx {
    /// Returns the transaction Id
    pub fn txid(&self) -> TxId {
        let mut txid_bytes = [0u8; 32];
        txid_bytes.copy_from_slice(&self.txid);
        TxId::from_bytes(txid_bytes)
    }
}

/// An error indicating that a field of a compact format structure could not be parsed.
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum CompactFormatError {
    /// A byte slice had an invalid length for the expected field.
    InvalidLength(TryFromSliceError),
    /// A field value did not represent a valid protocol element.
    InvalidValue,
}

impl Display for CompactFormatError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CompactFormatError::InvalidLength(e) => write!(f, "Invalid compact format field: {e}"),
            CompactFormatError::InvalidValue => {
                write!(f, "Compact format field is not a valid protocol element")
            }
        }
    }
}

impl compact_formats::CompactSaplingOutput {
    /// Returns the note commitment for this output.
    ///
    /// A convenience method that parses [`field@Self::cmu`].
    pub fn cmu(&self) -> Result<ExtractedNoteCommitment, CompactFormatError> {
        let mut repr = [0; 32];
        repr.copy_from_slice(&self.cmu[..]);
        Option::from(ExtractedNoteCommitment::from_bytes(&repr))
            .ok_or(CompactFormatError::InvalidValue)
    }

    /// Returns the ephemeral public key for this output.
    ///
    /// A convenience method that parses [`field@Self::ephemeral_key`].
    pub fn ephemeral_key(&self) -> Result<EphemeralKeyBytes, CompactFormatError> {
        self.ephemeral_key[..]
            .try_into()
            .map(EphemeralKeyBytes)
            .map_err(CompactFormatError::InvalidLength)
    }
}

impl<Proof> From<&sapling::bundle::OutputDescription<Proof>>
    for compact_formats::CompactSaplingOutput
{
    fn from(
        out: &sapling::bundle::OutputDescription<Proof>,
    ) -> compact_formats::CompactSaplingOutput {
        compact_formats::CompactSaplingOutput {
            cmu: out.cmu().to_bytes().to_vec(),
            ephemeral_key: out.ephemeral_key().as_ref().to_vec(),
            ciphertext: out.enc_ciphertext()[..COMPACT_NOTE_SIZE].to_vec(),
        }
    }
}

impl TryFrom<compact_formats::CompactSaplingOutput>
    for sapling::note_encryption::CompactOutputDescription
{
    type Error = CompactFormatError;

    fn try_from(value: compact_formats::CompactSaplingOutput) -> Result<Self, Self::Error> {
        (&value).try_into()
    }
}

impl TryFrom<&compact_formats::CompactSaplingOutput>
    for sapling::note_encryption::CompactOutputDescription
{
    type Error = CompactFormatError;

    fn try_from(value: &compact_formats::CompactSaplingOutput) -> Result<Self, Self::Error> {
        Ok(sapling::note_encryption::CompactOutputDescription {
            cmu: value.cmu()?,
            ephemeral_key: value.ephemeral_key()?,
            enc_ciphertext: value.ciphertext[..]
                .try_into()
                .map_err(CompactFormatError::InvalidLength)?,
        })
    }
}

impl compact_formats::CompactSaplingSpend {
    /// Returns the nullifier for this spend.
    ///
    /// A convenience method that parses [`field@Self::nf`].
    pub fn nf(&self) -> Result<sapling::Nullifier, CompactFormatError> {
        sapling::Nullifier::from_slice(&self.nf).map_err(CompactFormatError::InvalidLength)
    }
}

#[cfg(feature = "orchard")]
impl TryFrom<&compact_formats::CompactOrchardAction> for orchard::note_encryption::CompactAction {
    type Error = CompactFormatError;

    fn try_from(value: &compact_formats::CompactOrchardAction) -> Result<Self, Self::Error> {
        Ok(orchard::note_encryption::CompactAction::from_parts(
            value.nf()?,
            value.cmx()?,
            value.ephemeral_key()?,
            value.ciphertext[..]
                .try_into()
                .map_err(CompactFormatError::InvalidLength)?,
        ))
    }
}

#[cfg(feature = "orchard")]
impl compact_formats::CompactOrchardAction {
    /// Returns the note commitment for the output of this action.
    ///
    /// A convenience method that parses [`field@Self::cmx`].
    pub fn cmx(&self) -> Result<orchard::note::ExtractedNoteCommitment, CompactFormatError> {
        Option::from(orchard::note::ExtractedNoteCommitment::from_bytes(
            &self.cmx[..]
                .try_into()
                .map_err(CompactFormatError::InvalidLength)?,
        ))
        .ok_or(CompactFormatError::InvalidValue)
    }

    /// Returns the nullifier for the spend of this action.
    ///
    /// A convenience method that parses [`field@Self::nullifier`].
    pub fn nf(&self) -> Result<orchard::note::Nullifier, CompactFormatError> {
        let nf_bytes: [u8; 32] = self.nullifier[..]
            .try_into()
            .map_err(CompactFormatError::InvalidLength)?;
        Option::from(orchard::note::Nullifier::from_bytes(&nf_bytes))
            .ok_or(CompactFormatError::InvalidValue)
    }

    /// Returns the ephemeral public key for the output of this action.
    ///
    /// A convenience method that parses [`field@Self::ephemeral_key`].
    pub fn ephemeral_key(&self) -> Result<EphemeralKeyBytes, CompactFormatError> {
        self.ephemeral_key[..]
            .try_into()
            .map(EphemeralKeyBytes)
            .map_err(CompactFormatError::InvalidLength)
    }
}

impl<A: sapling::bundle::Authorization> From<&sapling::bundle::SpendDescription<A>>
    for compact_formats::CompactSaplingSpend
{
    fn from(spend: &sapling::bundle::SpendDescription<A>) -> compact_formats::CompactSaplingSpend {
        compact_formats::CompactSaplingSpend {
            nf: spend.nullifier().to_vec(),
        }
    }
}

#[cfg(feature = "orchard")]
impl<SpendAuth> From<&orchard::Action<SpendAuth>> for compact_formats::CompactOrchardAction {
    fn from(action: &orchard::Action<SpendAuth>) -> compact_formats::CompactOrchardAction {
        compact_formats::CompactOrchardAction {
            nullifier: action.nullifier().to_bytes().to_vec(),
            cmx: action.cmx().to_bytes().to_vec(),
            ephemeral_key: action.encrypted_note().epk_bytes.to_vec(),
            ciphertext: action.encrypted_note().enc_ciphertext[..COMPACT_NOTE_SIZE].to_vec(),
        }
    }
}

impl service::LightdInfo {
    /// Returns the network type for the chain this server is following, or `None` if it
    /// is not recognised.
    pub fn chain_name(&self) -> Option<NetworkType> {
        match self.chain_name.as_str() {
            "main" => Some(NetworkType::Main),
            "test" => Some(NetworkType::Test),
            "regtest" => Some(NetworkType::Regtest),
            _ => None,
        }
    }

    /// Returns the Sapling activation height for the chain this server is following.
    ///
    /// # Panics
    ///
    /// This function will panic if [`field@Self::sapling_activation_height`] is not
    /// representable within a `u32`.
    pub fn sapling_activation_height(&self) -> BlockHeight {
        self.sapling_activation_height
            .try_into()
            .expect("lightwalletd should provide in-range heights")
    }

    /// Returns the current consensus branch ID for the chain tip of the chain this server
    /// is following, or `None` if it is not recognised.
    pub fn consensus_branch_id(&self) -> Option<consensus::BranchId> {
        u32::from_str_radix(&self.consensus_branch_id, 16)
            .ok()?
            .try_into()
            .ok()
    }

    /// Returns the chain tip height reported by the full node backing this server.
    ///
    /// If the full node is still syncing, this may not be the network's chain tip; in
    /// this case, [`Self::estimated_height`] will report a larger height.
    ///
    /// # Panics
    ///
    /// This function will panic if [`field@Self::block_height`] is not representable
    /// within a `u32`.
    pub fn block_height(&self) -> BlockHeight {
        self.block_height
            .try_into()
            .expect("lightwalletd should provide in-range heights")
    }

    /// Returns the estimated chain tip height for the chain this server is following.
    ///
    /// If the full node backing this server is fully synced, this is always equal to
    /// [`Self::block_height`].
    ///
    /// # Panics
    ///
    /// This function will panic if [`field@Self::estimated_height`] is not representable
    /// within a `u32`.
    pub fn estimated_height(&self) -> BlockHeight {
        self.estimated_height
            .try_into()
            .expect("lightwalletd should provide in-range heights")
    }

    /// Returns the donation address for this server.
    ///
    /// Returns `None` if:
    /// - no donation address was provided.
    /// - the provided donation address is not a valid [`unified::Address`].
    /// - the provided donation address is for a different chain.
    pub fn donation_address(&self) -> Option<unified::Address> {
        if self.donation_address.is_empty() {
            None
        } else {
            let (network_type, address) = unified::Address::decode(&self.donation_address).ok()?;
            (Some(network_type) == self.chain_name()).then_some(address)
        }
    }
}

impl service::TreeState {
    /// Deserializes and returns the Sapling note commitment tree field of the tree state.
    pub fn sapling_tree(
        &self,
    ) -> io::Result<CommitmentTree<Node, { sapling::NOTE_COMMITMENT_TREE_DEPTH }>> {
        if self.sapling_tree.is_empty() {
            Ok(CommitmentTree::empty())
        } else {
            let sapling_tree_bytes = hex::decode(&self.sapling_tree).map_err(|e| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Hex decoding of Sapling tree bytes failed: {e:?}"),
                )
            })?;
            read_commitment_tree::<Node, _, { sapling::NOTE_COMMITMENT_TREE_DEPTH }>(
                &sapling_tree_bytes[..],
            )
        }
    }

    /// Deserializes and returns the Sapling note commitment tree field of the tree state.
    #[cfg(feature = "orchard")]
    pub fn orchard_tree(
        &self,
    ) -> io::Result<CommitmentTree<MerkleHashOrchard, { orchard::NOTE_COMMITMENT_TREE_DEPTH as u8 }>>
    {
        if self.orchard_tree.is_empty() {
            Ok(CommitmentTree::empty())
        } else {
            let orchard_tree_bytes = hex::decode(&self.orchard_tree).map_err(|e| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Hex decoding of Orchard tree bytes failed: {e:?}"),
                )
            })?;
            read_commitment_tree::<
                MerkleHashOrchard,
                _,
                { orchard::NOTE_COMMITMENT_TREE_DEPTH as u8 },
            >(&orchard_tree_bytes[..])
        }
    }

    /// Deserializes and returns the Ironwood note commitment tree field of the tree state.
    ///
    /// The Ironwood tree is Orchard-shaped, but Ironwood is a distinct pool tracked separately
    /// from Orchard. An empty field yields an empty tree, which is the correct treestate at the
    /// Ironwood pool's activation.
    #[cfg(feature = "orchard")]
    pub fn ironwood_tree(
        &self,
    ) -> io::Result<CommitmentTree<MerkleHashOrchard, { orchard::NOTE_COMMITMENT_TREE_DEPTH as u8 }>>
    {
        if self.ironwood_tree.is_empty() {
            Ok(CommitmentTree::empty())
        } else {
            let ironwood_tree_bytes = hex::decode(&self.ironwood_tree).map_err(|e| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("Hex decoding of Ironwood tree bytes failed: {e:?}"),
                )
            })?;
            read_commitment_tree::<
                MerkleHashOrchard,
                _,
                { orchard::NOTE_COMMITMENT_TREE_DEPTH as u8 },
            >(&ironwood_tree_bytes[..])
        }
    }

    /// Parses this tree state into a [`ChainState`] for use with [`scan_cached_blocks`].
    ///
    /// [`scan_cached_blocks`]: crate::data_api::chain::scan_cached_blocks
    pub fn to_chain_state(&self) -> io::Result<ChainState> {
        let mut hash_bytes = hex::decode(&self.hash).map_err(|e| {
            io::Error::new(
                io::ErrorKind::InvalidData,
                format!("Block hash is not valid hex: {e:?}"),
            )
        })?;
        // Zcashd hex strings for block hashes are byte-reversed.
        hash_bytes.reverse();

        Ok(ChainState::new(
            self.height
                .try_into()
                .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid block height"))?,
            BlockHash::try_from_slice(&hash_bytes).ok_or_else(|| {
                io::Error::new(io::ErrorKind::InvalidData, "Invalid block hash length.")
            })?,
            self.sapling_tree()?.to_frontier(),
            #[cfg(feature = "orchard")]
            self.orchard_tree()?.to_frontier(),
            #[cfg(feature = "orchard")]
            self.ironwood_tree()?.to_frontier(),
        ))
    }
}

/// Constant for the V1 proposal serialization version.
pub const PROPOSAL_SER_V1: u32 = 1;

/// Errors that can occur in the process of decoding a [`Proposal`] from its protobuf
/// representation.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum ProposalDecodingError<DbError> {
    /// The encoded proposal contained no steps.
    NoSteps,
    /// The ZIP 321 transaction request URI was invalid.
    Zip321(Zip321Error),
    /// A proposed input was null.
    NullInput(usize),
    /// A transaction identifier string did not decode to a valid transaction ID.
    TxIdInvalid(TryFromSliceError),
    /// An invalid value pool identifier was encountered.
    ValuePoolNotSupported(i32),
    /// A failure occurred trying to retrieve an unspent note or UTXO from the wallet database.
    InputRetrieval(DbError),
    /// The unspent note or UTXO corresponding to a proposal input was not found in the wallet
    /// database.
    InputNotFound(TxId, PoolType, u32),
    /// The transaction balance, or a component thereof, failed to decode correctly.
    BalanceInvalid,
    /// Failed to decode a ZIP-302-compliant memo from the provided memo bytes.
    MemoInvalid(memo::Error),
    /// The serialization version returned by the protobuf was not recognized.
    VersionInvalid(u32),
    /// The fee rule specified by the proposal is not supported by the wallet.
    FeeRuleNotSupported(proposal::FeeRule),
    /// The proposal violated balance or structural constraints.
    ProposalInvalid(ProposalError),
    /// An inputs field for the given protocol was present, but contained no input note references.
    EmptyShieldedInputs(ShieldedPool),
    /// A memo field was provided for a transparent output.
    TransparentMemo,
    /// Change outputs to the specified pool are not supported.
    InvalidChangeRecipient(PoolType),
    /// Ephemeral outputs to the specified pool are not supported.
    InvalidEphemeralRecipient(PoolType),
    /// The encoded confirmations policy was not valid (for example, a zero confirmation count or
    /// trusted confirmations exceeding untrusted).
    ConfirmationsPolicyInvalid,
    /// A payment was directed to the Orchard pool while Ironwood is active at the proposal's target
    /// height. Once Ironwood is active, Orchard-receiver payments target the Ironwood pool and only
    /// change may return to Orchard, so such a payment cannot appear in a well-formed proposal.
    OrchardPaymentProhibited,
    /// A proposal step produces a shielded bundle (it spends shielded notes, pays to a shielded
    /// pool, or returns shielded change) but its encoded anchor height is the zero sentinel. Every
    /// shielded-tree lookup the step performs — including the dummy spends that pad an output-only
    /// bundle — must be bound to a real anchor, so this combination cannot appear in a well-formed
    /// proposal.
    MissingShieldedAnchor,
    /// The proposal specified an explicit transaction version header that the wallet does not
    /// recognize.
    ProposedVersionInvalid(u32),
}

impl<E> From<Zip321Error> for ProposalDecodingError<E> {
    fn from(value: Zip321Error) -> Self {
        Self::Zip321(value)
    }
}

impl<E: Display> Display for ProposalDecodingError<E> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ProposalDecodingError::NoSteps => write!(f, "The proposal had no steps."),
            ProposalDecodingError::Zip321(err) => write!(f, "Transaction request invalid: {err}"),
            ProposalDecodingError::NullInput(i) => {
                write!(f, "Proposed input was null at index {i}")
            }
            ProposalDecodingError::TxIdInvalid(err) => {
                write!(f, "Invalid transaction id: {err:?}")
            }
            ProposalDecodingError::ValuePoolNotSupported(id) => {
                write!(f, "Invalid value pool identifier: {id:?}")
            }
            ProposalDecodingError::InputRetrieval(err) => {
                write!(f, "An error occurred retrieving a transaction input: {err}")
            }
            ProposalDecodingError::InputNotFound(txid, pool, idx) => {
                write!(f, "No {pool} input found for txid {txid}, index {idx}")
            }
            ProposalDecodingError::BalanceInvalid => {
                write!(f, "An error occurred decoding the proposal balance.")
            }
            ProposalDecodingError::MemoInvalid(err) => {
                write!(f, "An error occurred decoding a proposed memo: {err}")
            }
            ProposalDecodingError::VersionInvalid(v) => {
                write!(f, "Unrecognized proposal version {v}")
            }
            ProposalDecodingError::FeeRuleNotSupported(r) => {
                write!(
                    f,
                    "Fee calculation using the {r:?} fee rule is not supported."
                )
            }
            ProposalDecodingError::ProposalInvalid(err) => write!(f, "{err}"),
            ProposalDecodingError::EmptyShieldedInputs(protocol) => write!(
                f,
                "An inputs field was present for {protocol:?}, but contained no note references."
            ),
            ProposalDecodingError::TransparentMemo => {
                write!(f, "Transparent outputs cannot have memos.")
            }
            ProposalDecodingError::InvalidChangeRecipient(pool_type) => write!(
                f,
                "Change outputs to the {pool_type} pool are not supported."
            ),
            ProposalDecodingError::InvalidEphemeralRecipient(pool_type) => write!(
                f,
                "Ephemeral outputs to the {pool_type} pool are not supported."
            ),
            ProposalDecodingError::ConfirmationsPolicyInvalid => {
                write!(f, "The encoded confirmations policy was not valid.")
            }
            ProposalDecodingError::OrchardPaymentProhibited => write!(
                f,
                "A payment may not be directed to the Orchard pool once Ironwood is active."
            ),
            ProposalDecodingError::MissingShieldedAnchor => write!(
                f,
                "A proposal step that produces a shielded bundle must specify an anchor height."
            ),
            ProposalDecodingError::ProposedVersionInvalid(header) => write!(
                f,
                "The proposal specified an unrecognized transaction version header {header:#x}."
            ),
        }
    }
}

impl<E: std::error::Error + 'static> std::error::Error for ProposalDecodingError<E> {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            ProposalDecodingError::Zip321(e) => Some(e),
            ProposalDecodingError::InputRetrieval(e) => Some(e),
            ProposalDecodingError::MemoInvalid(e) => Some(e),
            _ => None,
        }
    }
}

fn pool_type<T>(pool_id: i32) -> Result<PoolType, ProposalDecodingError<T>> {
    match proposal::ValuePool::try_from(pool_id) {
        Ok(proposal::ValuePool::Transparent) => Ok(PoolType::TRANSPARENT),
        Ok(proposal::ValuePool::Sapling) => Ok(PoolType::SAPLING),
        Ok(proposal::ValuePool::Orchard) => Ok(PoolType::ORCHARD),
        Ok(proposal::ValuePool::Ironwood) => Ok(PoolType::IRONWOOD),
        _ => Err(ProposalDecodingError::ValuePoolNotSupported(pool_id)),
    }
}

impl proposal::ReceivedOutput {
    pub fn parse_txid(&self) -> Result<TxId, TryFromSliceError> {
        Ok(TxId::from_bytes(self.txid[..].try_into()?))
    }

    pub fn pool_type<T>(&self) -> Result<PoolType, ProposalDecodingError<T>> {
        pool_type(self.value_pool)
    }
}

impl proposal::ChangeValue {
    pub fn pool_type<T>(&self) -> Result<PoolType, ProposalDecodingError<T>> {
        pool_type(self.value_pool)
    }
}

impl From<PoolType> for proposal::ValuePool {
    fn from(value: PoolType) -> Self {
        match value {
            PoolType::Transparent => proposal::ValuePool::Transparent,
            PoolType::Shielded(p) => p.into(),
        }
    }
}

impl From<ShieldedPool> for proposal::ValuePool {
    fn from(value: ShieldedPool) -> Self {
        match value {
            ShieldedPool::Sapling => proposal::ValuePool::Sapling,
            ShieldedPool::Orchard => proposal::ValuePool::Orchard,
            ShieldedPool::Ironwood => proposal::ValuePool::Ironwood,
        }
    }
}

impl proposal::Proposal {
    /// Serializes a [`Proposal`] based upon a supported [`StandardFeeRule`] to its protobuf
    /// representation.
    pub fn from_standard_proposal<NoteRef>(value: &Proposal<StandardFeeRule, NoteRef>) -> Self {
        let steps = value
            .steps()
            .iter()
            .map(|step| {
                let transaction_request = step.transaction_request().to_uri();

                // A decoded legacy step that defers its anchor encodes as the zero sentinel.
                let anchor_height = step.anchor_height().map_or(0, u32::from);

                let inputs = step
                    .transparent_inputs()
                    .iter()
                    .map(|utxo| proposal::ProposedInput {
                        value: Some(proposed_input::Value::ReceivedOutput(ReceivedOutput {
                            txid: utxo.outpoint().hash().to_vec(),
                            value_pool: proposal::ValuePool::Transparent.into(),
                            index: utxo.outpoint().n(),
                            value: utxo.txout().value().into(),
                        })),
                    })
                    .chain(step.shielded_inputs().iter().flat_map(|s_in| {
                        s_in.notes().iter().map(|rec_note| proposal::ProposedInput {
                            value: Some(proposed_input::Value::ReceivedOutput(ReceivedOutput {
                                txid: rec_note.txid().as_ref().to_vec(),
                                value_pool: proposal::ValuePool::from(rec_note.note().pool())
                                    .into(),
                                index: rec_note.output_index().into(),
                                value: rec_note.note().value().into(),
                            })),
                        })
                    }))
                    .chain(step.prior_step_inputs().iter().map(|p_in| {
                        match p_in.output_index() {
                            StepOutputIndex::Payment(i) => proposal::ProposedInput {
                                value: Some(proposed_input::Value::PriorStepOutput(
                                    PriorStepOutput {
                                        step_index: p_in
                                            .step_index()
                                            .try_into()
                                            .expect("Step index fits into a u32"),
                                        payment_index: i
                                            .try_into()
                                            .expect("Payment index fits into a u32"),
                                    },
                                )),
                            },
                            StepOutputIndex::Change(i) => proposal::ProposedInput {
                                value: Some(proposed_input::Value::PriorStepChange(
                                    PriorStepChange {
                                        step_index: p_in
                                            .step_index()
                                            .try_into()
                                            .expect("Step index fits into a u32"),
                                        change_index: i
                                            .try_into()
                                            .expect("Payment index fits into a u32"),
                                    },
                                )),
                            },
                        }
                    }))
                    .collect();

                let payment_output_pools = step
                    .payment_pools()
                    .iter()
                    .map(|(idx, pool_type)| proposal::PaymentOutputPool {
                        payment_index: u32::try_from(*idx).expect("Payment index fits into a u32"),
                        value_pool: proposal::ValuePool::from(*pool_type).into(),
                    })
                    .collect();

                let balance = Some(proposal::TransactionBalance {
                    proposed_change: step
                        .balance()
                        .proposed_change()
                        .iter()
                        .map(|change| proposal::ChangeValue {
                            value: change.value().into(),
                            value_pool: proposal::ValuePool::from(change.output_pool()).into(),
                            memo: change.memo().map(|memo_bytes| proposal::MemoBytes {
                                value: memo_bytes.as_slice().to_vec(),
                            }),
                            is_ephemeral: change.is_ephemeral(),
                        })
                        .collect(),
                    fee_required: step.balance().fee_required().into(),
                    dummy_outputs: step.balance().dummy_outputs().map(|counts| {
                        proposal::DummyOutputs {
                            sapling: counts
                                .sapling()
                                .try_into()
                                .expect("Sapling dummy-output count fits into u32"),
                            #[cfg(feature = "orchard")]
                            orchard: counts
                                .orchard()
                                .try_into()
                                .expect("Orchard dummy-output count fits into u32"),
                            #[cfg(not(feature = "orchard"))]
                            orchard: 0,
                            #[cfg(feature = "orchard")]
                            ironwood: counts
                                .ironwood()
                                .try_into()
                                .expect("Ironwood dummy-output count fits into u32"),
                            #[cfg(not(feature = "orchard"))]
                            ironwood: 0,
                        }
                    }),
                });

                proposal::ProposalStep {
                    transaction_request,
                    payment_output_pools,
                    anchor_height,
                    inputs,
                    balance,
                    is_shielding: step.is_shielding(),
                }
            })
            .collect();

        let confirmations_policy = value.confirmations_policy();
        proposal::Proposal {
            proto_version: PROPOSAL_SER_V1,
            fee_rule: match value.fee_rule() {
                StandardFeeRule::Zip317 => proposal::FeeRule::Zip317,
            }
            .into(),
            min_target_height: value.min_target_height().into(),
            steps,
            confirmations_policy: Some(proposal::ConfirmationsPolicy {
                trusted: confirmations_policy.trusted().into(),
                untrusted: confirmations_policy.untrusted().into(),
                #[cfg(feature = "transparent-inputs")]
                allow_zero_conf_shielding: confirmations_policy.allow_zero_conf_shielding(),
                #[cfg(not(feature = "transparent-inputs"))]
                allow_zero_conf_shielding: true,
            }),
            proposed_version: value.proposed_version().map(|v| v.header()),
        }
    }

    /// Attempts to parse a [`Proposal`] based upon a supported [`StandardFeeRule`] from its
    /// protobuf representation.
    pub fn try_into_standard_proposal<ParamsT, DbT, DbError>(
        &self,
        params: &ParamsT,
        wallet_db: &DbT,
    ) -> Result<Proposal<StandardFeeRule, DbT::NoteRef>, ProposalDecodingError<DbError>>
    where
        ParamsT: consensus::Parameters,
        DbT: InputSource<Error = DbError>,
    {
        match self.proto_version {
            PROPOSAL_SER_V1 => {
                let fee_rule = match self.fee_rule() {
                    proposal::FeeRule::Zip317 => StandardFeeRule::Zip317,
                    other => {
                        return Err(ProposalDecodingError::FeeRuleNotSupported(other));
                    }
                };

                let target_height = TargetHeight::from(self.min_target_height);

                // A proposal created with `lock_for_blocks` locks its own inputs, so
                // input retrieval during decoding must not filter locked outputs;
                // otherwise a locked proposal would fail to round-trip through its
                // serialized form. Double-spend protection is enforced when the
                // proposal's transactions are created, not here.
                let lock_filter = LockFilter::Unfiltered;

                // Steps are checked against the Orchard turnstile when Ironwood is
                // active at the height for which the proposal was constructed.
                #[cfg(feature = "orchard")]
                let ironwood_active = params.is_nu_active(
                    consensus::NetworkUpgrade::Nu6_3,
                    BlockHeight::from(target_height),
                );
                #[cfg(not(feature = "orchard"))]
                let _ = params;

                let mut steps = Vec::with_capacity(self.steps.len());
                for step in &self.steps {
                    let transaction_request =
                        TransactionRequest::from_uri(&step.transaction_request)?;

                    let payment_pools = step
                        .payment_output_pools
                        .iter()
                        .map(|pop| {
                            Ok((
                                usize::try_from(pop.payment_index)
                                    .expect("Payment index fits into a usize"),
                                pool_type(pop.value_pool)?,
                            ))
                        })
                        .collect::<Result<BTreeMap<usize, PoolType>, ProposalDecodingError<DbError>>>()?;

                    // With Ironwood active, no payment may be directed to the Orchard pool: an
                    // Orchard-receiver payment targets the Ironwood pool, and only change may
                    // return to Orchard. Reject such a payment from untrusted or legacy input here,
                    // rather than letting it reach the `debug_assert!` in `Step::from_parts`.
                    #[cfg(feature = "orchard")]
                    if ironwood_active
                        && payment_pools
                            .values()
                            .any(|pool| *pool == PoolType::ORCHARD)
                    {
                        return Err(ProposalDecodingError::OrchardPaymentProhibited);
                    }

                    #[allow(unused_mut)]
                    let mut transparent_inputs = vec![];
                    let mut received_notes = vec![];
                    let mut prior_step_inputs = vec![];
                    for (i, input) in step.inputs.iter().enumerate() {
                        match input
                            .value
                            .as_ref()
                            .ok_or(ProposalDecodingError::NullInput(i))?
                        {
                            ReceivedOutput(out) => {
                                let txid = out
                                    .parse_txid()
                                    .map_err(ProposalDecodingError::TxIdInvalid)?;

                                match out.pool_type()? {
                                    PoolType::Transparent => {
                                        #[cfg(not(feature = "transparent-inputs"))]
                                        return Err(ProposalDecodingError::ValuePoolNotSupported(
                                            out.value_pool,
                                        ));

                                        #[cfg(feature = "transparent-inputs")]
                                        {
                                            let outpoint = OutPoint::new(txid.into(), out.index);
                                            transparent_inputs.push(
                                                wallet_db
                                                    .get_unspent_transparent_output(
                                                        &outpoint,
                                                        target_height,
                                                    )
                                                    .map_err(ProposalDecodingError::InputRetrieval)?
                                                    .ok_or({
                                                        ProposalDecodingError::InputNotFound(
                                                            txid,
                                                            PoolType::TRANSPARENT,
                                                            out.index,
                                                        )
                                                    })?
                                                    .redact_account_data(),
                                            );
                                        }
                                    }
                                    PoolType::Shielded(protocol) => received_notes.push(
                                        wallet_db
                                            .get_spendable_note(
                                                &txid,
                                                protocol,
                                                out.index,
                                                target_height,
                                                lock_filter,
                                            )
                                            .map_err(ProposalDecodingError::InputRetrieval)
                                            .and_then(|opt| {
                                                opt.ok_or({
                                                    ProposalDecodingError::InputNotFound(
                                                        txid,
                                                        PoolType::Shielded(protocol),
                                                        out.index,
                                                    )
                                                })
                                            })?,
                                    ),
                                }
                            }
                            PriorStepOutput(s_ref) => {
                                prior_step_inputs.push(StepOutput::new(
                                    s_ref
                                        .step_index
                                        .try_into()
                                        .expect("Step index fits into a usize"),
                                    StepOutputIndex::Payment(
                                        s_ref
                                            .payment_index
                                            .try_into()
                                            .expect("Payment index fits into a usize"),
                                    ),
                                ));
                            }
                            PriorStepChange(s_ref) => {
                                prior_step_inputs.push(StepOutput::new(
                                    s_ref
                                        .step_index
                                        .try_into()
                                        .expect("Step index fits into a usize"),
                                    StepOutputIndex::Change(
                                        s_ref
                                            .change_index
                                            .try_into()
                                            .expect("Payment index fits into a usize"),
                                    ),
                                ));
                            }
                        }
                    }

                    let shielded_inputs =
                        NonEmpty::from_vec(received_notes).map(ShieldedInputs::from_parts);

                    let proto_balance = step
                        .balance
                        .as_ref()
                        .ok_or(ProposalDecodingError::BalanceInvalid)?;
                    let balance = TransactionBalance::new(
                        proto_balance
                            .proposed_change
                            .iter()
                            .map(|cv| -> Result<ChangeValue, ProposalDecodingError<_>> {
                                let value = Zatoshis::from_u64(cv.value)
                                    .map_err(|_| ProposalDecodingError::BalanceInvalid)?;
                                let memo = cv
                                    .memo
                                    .as_ref()
                                    .map(|bytes| {
                                        MemoBytes::from_bytes(&bytes.value)
                                            .map_err(ProposalDecodingError::MemoInvalid)
                                    })
                                    .transpose()?;
                                match (cv.pool_type()?, cv.is_ephemeral) {
                                    (PoolType::Shielded(ShieldedPool::Sapling), false) => {
                                        Ok(ChangeValue::sapling(value, memo))
                                    }
                                    #[cfg(feature = "orchard")]
                                    (PoolType::Shielded(ShieldedPool::Orchard), false) => {
                                        Ok(ChangeValue::orchard(value, memo))
                                    }
                                    #[cfg(feature = "orchard")]
                                    (PoolType::Shielded(ShieldedPool::Ironwood), false) => Ok(
                                        ChangeValue::shielded(ShieldedPool::Ironwood, value, memo),
                                    ),
                                    (PoolType::Transparent, _) if memo.is_some() => {
                                        Err(ProposalDecodingError::TransparentMemo)
                                    }
                                    #[cfg(feature = "transparent-inputs")]
                                    (PoolType::Transparent, true) => {
                                        Ok(ChangeValue::ephemeral_transparent(value))
                                    }
                                    #[cfg(feature = "transparent-inputs")]
                                    (PoolType::Transparent, false) => {
                                        Ok(ChangeValue::transparent(value))
                                    }
                                    // When all pool features are enabled, the explicit arms above
                                    // are exhaustive over the non-ephemeral cases; this fallback
                                    // remains reachable when some pool features are disabled.
                                    #[allow(unreachable_patterns)]
                                    (pool, false) => {
                                        Err(ProposalDecodingError::InvalidChangeRecipient(pool))
                                    }
                                    (pool, true) => {
                                        Err(ProposalDecodingError::InvalidEphemeralRecipient(pool))
                                    }
                                }
                            })
                            .collect::<Result<Vec<_>, _>>()?,
                        Zatoshis::from_u64(proto_balance.fee_required)
                            .map_err(|_| ProposalDecodingError::BalanceInvalid)?,
                    )
                    .map_err(|_| ProposalDecodingError::BalanceInvalid)?;
                    let balance = match proto_balance.dummy_outputs.as_ref() {
                        Some(counts) => {
                            #[cfg(feature = "orchard")]
                            let dummy_outputs = DummyOutputCounts::new(
                                counts.sapling as usize,
                                counts.orchard as usize,
                                counts.ironwood as usize,
                            );
                            #[cfg(not(feature = "orchard"))]
                            let dummy_outputs = DummyOutputCounts::new(counts.sapling as usize);
                            balance.with_dummy_outputs(dummy_outputs)
                        }
                        // Older proposals did not explicitly model their dummy outputs.
                        None => balance,
                    };

                    // The `anchorHeight` field's zero value is the wire sentinel for a step that
                    // carries no anchor. Only a purely transparent step may lack one: any step that
                    // produces a shielded bundle binds every shielded-tree lookup — including the
                    // dummy spends that pad an output-only bundle — to a real anchor. Reject the
                    // invalid combination here at the parse boundary rather than letting it reach
                    // `Step::from_parts`.
                    let anchor_height = match step.anchor_height {
                        0 if produces_shielded_bundle(
                            shielded_inputs.is_some(),
                            &payment_pools,
                            &balance,
                        ) =>
                        {
                            return Err(ProposalDecodingError::MissingShieldedAnchor);
                        }
                        0 => None,
                        h => Some(BlockHeight::from_u32(h)),
                    };

                    let step = Step::from_parts(
                        &steps,
                        transaction_request,
                        payment_pools,
                        transparent_inputs,
                        shielded_inputs,
                        anchor_height,
                        prior_step_inputs,
                        balance,
                        step.is_shielding,
                        #[cfg(feature = "orchard")]
                        ironwood_active,
                    )
                    .map_err(ProposalDecodingError::ProposalInvalid)?;

                    steps.push(step);
                }

                // Reconstruct the confirmations policy the proposal was built under. Proposals
                // serialized before this field existed omit it and are interpreted using the
                // default policy.
                let confirmations_policy = match &self.confirmations_policy {
                    Some(cp) => ConfirmationsPolicy::new(
                        NonZeroU32::new(cp.trusted)
                            .ok_or(ProposalDecodingError::ConfirmationsPolicyInvalid)?,
                        NonZeroU32::new(cp.untrusted)
                            .ok_or(ProposalDecodingError::ConfirmationsPolicyInvalid)?,
                        #[cfg(feature = "transparent-inputs")]
                        cp.allow_zero_conf_shielding,
                    )
                    .map_err(|_| ProposalDecodingError::ConfirmationsPolicyInvalid)?,
                    None => ConfirmationsPolicy::default(),
                };

                // Recover the explicitly-requested transaction version, if any. Proposals
                // serialized before this field existed, or built without a version request, omit
                // it and fall back to the version implied by the target height.
                let proposed_version = self
                    .proposed_version
                    .map(|header| {
                        if header == TxVersion::V5.header() {
                            Ok(TxVersion::V5)
                        } else if header == TxVersion::V6.header() {
                            Ok(TxVersion::V6)
                        } else {
                            Err(ProposalDecodingError::ProposedVersionInvalid(header))
                        }
                    })
                    .transpose()?;

                Proposal::multi_step(
                    fee_rule,
                    target_height,
                    confirmations_policy,
                    NonEmpty::from_vec(steps).ok_or(ProposalDecodingError::NoSteps)?,
                )
                .map(|proposal| proposal.with_proposed_version(proposed_version))
                .map_err(ProposalDecodingError::ProposalInvalid)
            }
            other => Err(ProposalDecodingError::VersionInvalid(other)),
        }
    }
}

#[cfg(feature = "lightwalletd-tonic-transport")]
impl service::compact_tx_streamer_client::CompactTxStreamerClient<tonic::transport::Channel> {
    /// Attempt to create a new client by connecting to a given endpoint.
    pub async fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
    where
        D: TryInto<tonic::transport::Endpoint>,
        D::Error: Into<tonic::codegen::StdError>,
    {
        let conn = tonic::transport::Endpoint::new(dst)?.connect().await?;
        Ok(Self::new(conn))
    }
}