1use std::{
4 collections::HashMap,
5 error,
6 fmt::{self, Debug, Display, Write},
7 hash::Hash,
8};
9
10use shardtree::error::ShardTreeError;
11use zcash_address::ConversionError;
12use zcash_keys::address::UnifiedAddress;
13use zcash_primitives::transaction::builder;
14use zcash_protocol::{
15 PoolType,
16 consensus::BlockHeight,
17 value::{BalanceError, Zatoshis},
18};
19
20use crate::{
21 data_api::wallet::input_selection::InputSelectorError, fees::ChangeError,
22 proposal::ProposalError, wallet::NoteId,
23};
24
25#[cfg(feature = "transparent-inputs")]
26use ::transparent::address::TransparentAddress;
27
28#[derive(Debug)]
30#[non_exhaustive]
31pub enum Error<DataSourceError, CommitmentTreeError, SelectionError, FeeError, ChangeErrT, NoteRefT>
32{
33 DataSource(DataSourceError),
35
36 CommitmentTree(ShardTreeError<CommitmentTreeError>),
38
39 NoteSelection(SelectionError),
41
42 Change(ChangeError<ChangeErrT, NoteRefT>),
44
45 Proposal(ProposalError),
47
48 ProposalNotSupported,
54
55 AccountIdNotRecognized,
57
58 KeyNotRecognized,
60
61 AccountCannotSpend,
64
65 BalanceError(BalanceError),
67
68 InsufficientFunds {
70 available: Zatoshis,
71 required: Zatoshis,
72 },
73
74 ScanRequired,
83
84 Builder(builder::Error<FeeError>),
86
87 Payment(zip321::PaymentError),
89
90 UnsupportedChangeType(PoolType),
96
97 NoSupportedReceivers(Box<UnifiedAddress>),
99
100 KeyNotAvailable(PoolType),
103
104 NoteMismatch(NoteId),
107
108 Address(ConversionError<&'static str>),
110
111 #[cfg(feature = "transparent-inputs")]
114 AddressNotRecognized(TransparentAddress),
115
116 ExpiryHeightBelowTargetHeight {
119 expiry_height: BlockHeight,
120 min_target_height: BlockHeight,
121 },
122
123 ExpiryHeightConflictsWithCanonicalCrossing { requested: BlockHeight },
131
132 RecipientAddressExpiry {
136 payment_index: usize,
137 error: AddressExpiryError,
138 },
139
140 #[cfg(feature = "pczt")]
142 Pczt(PcztError),
143}
144
145#[non_exhaustive]
147pub enum RewindError<AccountId: Hash + Eq, E> {
148 DataSource(E),
150 RewindBeyondBirthdays(HashMap<AccountId, BlockHeight>),
164}
165
166impl<AccountId: Hash + Eq + Debug, E: Debug> Debug for RewindError<AccountId, E> {
167 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168 match self {
169 RewindError::DataSource(e) => f.debug_tuple("DataSource").field(e).finish(),
170 RewindError::RewindBeyondBirthdays(birthdays) => f
171 .debug_tuple("RewindBeyondBirthdays")
172 .field(birthdays)
173 .finish(),
174 }
175 }
176}
177
178impl<AccountId: Hash + Eq + Debug, E: Display> Display for RewindError<AccountId, E> {
179 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
180 match self {
181 RewindError::DataSource(e) => write!(f, "Wallet data source error: {e}"),
182 RewindError::RewindBeyondBirthdays(birthdays) => write!(
183 f,
184 "Rewind would precede the birthday height of one or more accounts: {birthdays:?}"
185 ),
186 }
187 }
188}
189
190impl<AccountId: Hash + Eq + Debug, E: error::Error + 'static> error::Error
191 for RewindError<AccountId, E>
192{
193 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
194 match self {
195 RewindError::DataSource(e) => Some(e),
196 RewindError::RewindBeyondBirthdays(_) => None,
197 }
198 }
199}
200
201#[cfg(feature = "pczt")]
203#[derive(Debug)]
204#[non_exhaustive]
205pub enum PcztError {
206 Build,
208
209 IoFinalization(pczt::roles::io_finalizer::Error),
211
212 UpdateOrchard(pczt::roles::updater::OrchardError),
214
215 UpdateSapling(pczt::roles::updater::SaplingError),
217
218 UpdateTransparent(pczt::roles::updater::TransparentError),
220
221 SpendFinalization(pczt::roles::spend_finalizer::Error),
223
224 Extraction(pczt::roles::tx_extractor::Error),
226
227 Invalid(String),
229}
230
231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
234#[non_exhaustive]
235pub enum AddressExpiryError {
236 TimeExpired {
238 expiry_time: u64,
240 },
241 HeightExpired {
243 address_expiry: BlockHeight,
245 chain_height: BlockHeight,
247 },
248 ExpiryHeightConflict {
254 address_expiry: BlockHeight,
255 transaction_expiry: BlockHeight,
256 },
257 TransactionExpiryDisabled { address_expiry: BlockHeight },
260}
261
262impl fmt::Display for AddressExpiryError {
263 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
264 match self {
265 AddressExpiryError::TimeExpired { expiry_time } => write!(
266 f,
267 "the address expired at {expiry_time} (seconds since the Unix epoch)"
268 ),
269 AddressExpiryError::HeightExpired {
270 address_expiry,
271 chain_height,
272 } => write!(
273 f,
274 "the address expired at height {address_expiry}, and the chain has \
275 reached height {chain_height}"
276 ),
277 AddressExpiryError::ExpiryHeightConflict {
278 address_expiry,
279 transaction_expiry,
280 } => write!(
281 f,
282 "the transaction would expire at height {transaction_expiry}, after the \
283 address's expiry height {address_expiry}"
284 ),
285 AddressExpiryError::TransactionExpiryDisabled { address_expiry } => write!(
286 f,
287 "the address expires at height {address_expiry}, which requires the \
288 transaction to carry a nonzero expiry height, but transaction expiry \
289 was disabled"
290 ),
291 }
292 }
293}
294
295impl error::Error for AddressExpiryError {}
296
297impl<DE, TE, SE, FE, CE, N> fmt::Display for Error<DE, TE, SE, FE, CE, N>
298where
299 DE: fmt::Display,
300 TE: fmt::Display,
301 SE: fmt::Display,
302 FE: fmt::Display,
303 CE: fmt::Display,
304 N: fmt::Display,
305{
306 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
307 match self {
308 Error::DataSource(e) => {
309 write!(
310 f,
311 "The underlying datasource produced the following error: {e}"
312 )
313 }
314 Error::CommitmentTree(e) => {
315 write!(
316 f,
317 "An error occurred in querying or updating a note commitment tree: {e}"
318 )
319 }
320 Error::NoteSelection(e) => {
321 write!(f, "Note selection encountered the following error: {e}")
322 }
323 Error::Change(e) => {
324 write!(f, "Change output generation failed: {e}")
325 }
326 Error::Proposal(e) => {
327 write!(
328 f,
329 "Input selection attempted to construct an invalid proposal: {e}"
330 )
331 }
332 Error::ProposalNotSupported => write!(
333 f,
334 "The proposal was valid but tried to do something that is not supported \
335 (spend shielded outputs of prior transaction steps or use a feature that \
336 is not enabled).",
337 ),
338 Error::KeyNotRecognized => {
339 write!(
340 f,
341 "Wallet does not contain an account corresponding to the provided spending key"
342 )
343 }
344 Error::AccountCannotSpend => {
345 write!(
346 f,
347 "The given account cannot be used for spending, because it is unable to maintain an accurate balance.",
348 )
349 }
350 Error::AccountIdNotRecognized => {
351 write!(
352 f,
353 "Wallet does not contain an account corresponding to the provided ID"
354 )
355 }
356 Error::BalanceError(e) => write!(
357 f,
358 "The value lies outside the valid range of Zcash amounts: {e:?}."
359 ),
360 Error::InsufficientFunds {
361 available,
362 required,
363 } => write!(
364 f,
365 "Insufficient balance (have {}, need {} including fee)",
366 u64::from(*available),
367 u64::from(*required)
368 ),
369 Error::ScanRequired => write!(f, "Must scan blocks first"),
370 Error::Builder(e) => write!(f, "An error occurred building the transaction: {e}"),
371 Error::Payment(e) => write!(f, "An error occurred constructing a payment: {e}"),
372 Error::UnsupportedChangeType(t) => write!(
373 f,
374 "Attempted to send change to an unsupported pool type: {t}"
375 ),
376 Error::NoSupportedReceivers(ua) => write!(
377 f,
378 "A recipient's unified address does not contain any receivers to which the wallet can send funds; required one of {}",
379 ua.receiver_types()
380 .iter()
381 .enumerate()
382 .fold(String::new(), |mut acc, (i, tc)| {
383 let _ = write!(acc, "{}{:?}", if i > 0 { ", " } else { "" }, tc);
384 acc
385 })
386 ),
387 Error::KeyNotAvailable(pool) => write!(
388 f,
389 "A key required for transaction construction was not available for pool type {pool}"
390 ),
391 Error::NoteMismatch(n) => write!(
392 f,
393 "A note being spent ({n:?}) does not correspond to either the internal or external full viewing key for the provided spending key."
394 ),
395
396 Error::Address(e) => {
397 write!(
398 f,
399 "An error occurred decoding the address from a payment request: {e}."
400 )
401 }
402 #[cfg(feature = "transparent-inputs")]
403 Error::AddressNotRecognized(_) => {
404 write!(
405 f,
406 "The specified transparent address was not recognized as belonging to the wallet."
407 )
408 }
409 Error::ExpiryHeightConflictsWithCanonicalCrossing { requested } => write!(
410 f,
411 "An expiry height of {requested} was requested for a canonical ZIP 318 crossing, \
412 which takes the ZIP 318 rolling expiry; pass `None` to accept it."
413 ),
414 Error::RecipientAddressExpiry {
415 payment_index,
416 error,
417 } => write!(
418 f,
419 "The recipient address of the payment at index {payment_index} cannot be \
420 paid: {error}. Try to obtain a currently-valid address for the intended \
421 recipient."
422 ),
423 Error::ExpiryHeightBelowTargetHeight {
424 expiry_height,
425 min_target_height,
426 } => write!(
427 f,
428 "The requested expiry height {expiry_height} is below the proposal's \
429 minimum target height {min_target_height}; the transaction would already be \
430 expired at the earliest height at which it could be mined."
431 ),
432 #[cfg(feature = "pczt")]
433 Error::Pczt(e) => write!(f, "PCZT error: {e}"),
434 }
435 }
436}
437
438#[cfg(feature = "pczt")]
439impl fmt::Display for PcztError {
440 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
441 match self {
442 PcztError::Build => {
443 write!(
444 f,
445 "Failed to generate the PCZT prior to proving or signing."
446 )
447 }
448 PcztError::IoFinalization(e) => {
449 write!(f, "Failed to finalize IO: {e:?}.")
450 }
451 PcztError::UpdateOrchard(e) => {
452 write!(f, "Failed to updating Orchard PCZT data: {e:?}.")
453 }
454 PcztError::UpdateSapling(e) => {
455 write!(f, "Failed to updating Sapling PCZT data: {e:?}.")
456 }
457 PcztError::UpdateTransparent(e) => {
458 write!(f, "Failed to updating transparent PCZT data: {e:?}.")
459 }
460 PcztError::SpendFinalization(e) => {
461 write!(f, "Failed to finalize the PCZT spends: {e:?}.")
462 }
463 PcztError::Extraction(e) => {
464 write!(f, "Failed to extract the final transaction: {e:?}.")
465 }
466 PcztError::Invalid(e) => {
467 write!(f, "PCZT parsing resulted in an invalid condition: {e}.")
468 }
469 }
470 }
471}
472
473impl<DE, TE, SE, FE, CE, N> error::Error for Error<DE, TE, SE, FE, CE, N>
474where
475 DE: Debug + Display + error::Error + 'static,
476 TE: Debug + Display + error::Error + 'static,
477 SE: Debug + Display + error::Error + 'static,
478 FE: Debug + Display + 'static,
479 CE: Debug + Display + error::Error + 'static,
480 N: Debug + Display + 'static,
481{
482 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
483 match &self {
484 Error::DataSource(e) => Some(e),
485 Error::CommitmentTree(e) => Some(e),
486 Error::NoteSelection(e) => Some(e),
487 Error::Proposal(e) => Some(e),
488 Error::Builder(e) => Some(e),
489 #[cfg(feature = "pczt")]
490 Error::Pczt(e) => Some(e),
491 _ => None,
492 }
493 }
494}
495
496#[cfg(feature = "pczt")]
497impl error::Error for PcztError {}
498
499impl<DE, TE, SE, FE, CE, N> From<builder::Error<FE>> for Error<DE, TE, SE, FE, CE, N> {
500 fn from(e: builder::Error<FE>) -> Self {
501 Error::Builder(e)
502 }
503}
504
505impl<DE, TE, SE, FE, CE, N> From<ProposalError> for Error<DE, TE, SE, FE, CE, N> {
506 fn from(e: ProposalError) -> Self {
507 Error::Proposal(e)
508 }
509}
510
511impl<DE, TE, SE, FE, CE, N> From<BalanceError> for Error<DE, TE, SE, FE, CE, N> {
512 fn from(e: BalanceError) -> Self {
513 Error::BalanceError(e)
514 }
515}
516
517impl<DE, TE, SE, FE, CE, N> From<ConversionError<&'static str>> for Error<DE, TE, SE, FE, CE, N> {
518 fn from(value: ConversionError<&'static str>) -> Self {
519 Error::Address(value)
520 }
521}
522
523impl<DE, TE, SE, FE, CE, N> From<InputSelectorError<DE, SE, CE, N>>
524 for Error<DE, TE, SE, FE, CE, N>
525{
526 fn from(e: InputSelectorError<DE, SE, CE, N>) -> Self {
527 match e {
528 InputSelectorError::DataSource(e) => Error::DataSource(e),
529 InputSelectorError::Selection(e) => Error::NoteSelection(e),
530 InputSelectorError::Change(e) => Error::Change(e),
531 InputSelectorError::Proposal(e) => Error::Proposal(e),
532 InputSelectorError::InsufficientFunds {
533 available,
534 required,
535 } => Error::InsufficientFunds {
536 available,
537 required,
538 },
539 InputSelectorError::SyncRequired => Error::ScanRequired,
540 InputSelectorError::Address(e) => Error::Address(e),
541 }
542 }
543}
544
545impl<DE, TE, SE, FE, CE, N> From<sapling::builder::Error> for Error<DE, TE, SE, FE, CE, N> {
546 fn from(e: sapling::builder::Error) -> Self {
547 Error::Builder(builder::Error::SaplingBuild(e))
548 }
549}
550
551impl<DE, TE, SE, FE, CE, N> From<transparent::builder::Error> for Error<DE, TE, SE, FE, CE, N> {
552 fn from(e: ::transparent::builder::Error) -> Self {
553 Error::Builder(builder::Error::TransparentBuild(e))
554 }
555}
556
557impl<DE, TE, SE, FE, CE, N> From<ShardTreeError<TE>> for Error<DE, TE, SE, FE, CE, N> {
558 fn from(e: ShardTreeError<TE>) -> Self {
559 Error::CommitmentTree(e)
560 }
561}
562
563#[cfg(feature = "pczt")]
564impl<DE, TE, SE, FE, CE, N> From<PcztError> for Error<DE, TE, SE, FE, CE, N> {
565 fn from(e: PcztError) -> Self {
566 Error::Pczt(e)
567 }
568}
569
570#[cfg(feature = "pczt")]
571impl<DE, TE, SE, FE, CE, N> From<pczt::roles::io_finalizer::Error>
572 for Error<DE, TE, SE, FE, CE, N>
573{
574 fn from(e: pczt::roles::io_finalizer::Error) -> Self {
575 Error::Pczt(PcztError::IoFinalization(e))
576 }
577}
578
579#[cfg(feature = "pczt")]
580impl<DE, TE, SE, FE, CE, N> From<pczt::roles::updater::OrchardError>
581 for Error<DE, TE, SE, FE, CE, N>
582{
583 fn from(e: pczt::roles::updater::OrchardError) -> Self {
584 Error::Pczt(PcztError::UpdateOrchard(e))
585 }
586}
587
588#[cfg(feature = "pczt")]
589impl<DE, TE, SE, FE, CE, N> From<pczt::roles::updater::SaplingError>
590 for Error<DE, TE, SE, FE, CE, N>
591{
592 fn from(e: pczt::roles::updater::SaplingError) -> Self {
593 Error::Pczt(PcztError::UpdateSapling(e))
594 }
595}
596
597#[cfg(feature = "pczt")]
598impl<DE, TE, SE, FE, CE, N> From<pczt::roles::updater::TransparentError>
599 for Error<DE, TE, SE, FE, CE, N>
600{
601 fn from(e: pczt::roles::updater::TransparentError) -> Self {
602 Error::Pczt(PcztError::UpdateTransparent(e))
603 }
604}
605
606#[cfg(feature = "pczt")]
607impl<DE, TE, SE, FE, CE, N> From<pczt::roles::spend_finalizer::Error>
608 for Error<DE, TE, SE, FE, CE, N>
609{
610 fn from(e: pczt::roles::spend_finalizer::Error) -> Self {
611 Error::Pczt(PcztError::SpendFinalization(e))
612 }
613}
614
615#[cfg(feature = "pczt")]
616impl<DE, TE, SE, FE, CE, N> From<pczt::roles::tx_extractor::Error>
617 for Error<DE, TE, SE, FE, CE, N>
618{
619 fn from(e: pczt::roles::tx_extractor::Error) -> Self {
620 Error::Pczt(PcztError::Extraction(e))
621 }
622}
623
624#[derive(Debug)]
626#[non_exhaustive]
627pub enum FindAccountForAddressError<E> {
628 Backend(E),
630
631 UnifiedAddressConflict,
633}
634
635impl<E> From<E> for FindAccountForAddressError<E> {
636 fn from(err: E) -> Self {
637 Self::Backend(err)
638 }
639}
640
641impl<E: Display> Display for FindAccountForAddressError<E> {
642 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
643 match self {
644 FindAccountForAddressError::Backend(e) => {
645 write!(f, "Wallet backend error: {e}")
646 }
647 FindAccountForAddressError::UnifiedAddressConflict => write!(
648 f,
649 "Receivers of the provided Unified Address map to different wallet accounts."
650 ),
651 }
652 }
653}
654
655impl<E: error::Error + 'static> error::Error for FindAccountForAddressError<E> {
656 fn source(&self) -> Option<&(dyn error::Error + 'static)> {
657 match self {
658 FindAccountForAddressError::Backend(e) => Some(e),
659 FindAccountForAddressError::UnifiedAddressConflict => None,
660 }
661 }
662}
663
664pub use super::locking::LockError;