Skip to main content

phoenix_core/
error.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at http://mozilla.org/MPL/2.0/.
4//
5// Copyright (c) DUSK NETWORK. All rights reserved.
6
7use core::fmt;
8
9use aes_gcm::Error as AesError;
10use dusk_bytes::{BadLength, Error as DuskBytesError, InvalidChar};
11
12/// All possible errors for Phoenix's Core
13#[allow(missing_docs)]
14#[derive(Debug, Clone)]
15pub enum Error {
16    /// Invalid u8 as Note Type (expected `0` or `1`, found {0})
17    InvalidNoteType(u8),
18    /// ViewKey required for decrypt data from Obfuscated Note
19    MissingViewKey,
20    /// Failure to encrypt / decrypt
21    InvalidEncryption,
22    /// Dusk-bytes InvalidData error
23    InvalidData,
24    /// Dusk-bytes BadLength error
25    BadLength(usize, usize),
26    /// Dusk-bytes InvalidChar error
27    InvalidChar(char, usize),
28}
29
30impl fmt::Display for Error {
31    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
32        write!(f, "Phoenix-Core Error: {:?}", &self)
33    }
34}
35
36impl From<AesError> for Error {
37    fn from(aes_error: AesError) -> Self {
38        match aes_error {
39            AesError => Self::InvalidEncryption,
40        }
41    }
42}
43
44impl From<DuskBytesError> for Error {
45    fn from(err: DuskBytesError) -> Self {
46        match err {
47            DuskBytesError::InvalidData => Error::InvalidData,
48            DuskBytesError::BadLength { found, expected } => {
49                Error::BadLength(found, expected)
50            }
51            DuskBytesError::InvalidChar { ch, index } => {
52                Error::InvalidChar(ch, index)
53            }
54        }
55    }
56}
57
58impl From<Error> for DuskBytesError {
59    fn from(err: Error) -> Self {
60        match err {
61            Error::InvalidData => DuskBytesError::InvalidData,
62            Error::BadLength(found, expected) => {
63                DuskBytesError::BadLength { found, expected }
64            }
65            Error::InvalidChar(ch, index) => {
66                DuskBytesError::InvalidChar { ch, index }
67            }
68            _ => unreachable!(),
69        }
70    }
71}
72
73impl BadLength for Error {
74    fn bad_length(found: usize, expected: usize) -> Self {
75        Error::BadLength(found, expected)
76    }
77}
78
79impl InvalidChar for Error {
80    fn invalid_char(ch: char, index: usize) -> Self {
81        Error::InvalidChar(ch, index)
82    }
83}