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
//! Crate specific errors

use crate::merkle_tree::{BatchPath, Path};
use blake2::digest::{Digest, FixedOutput};
use {
    crate::multi_sig::{Signature, VerificationKey, VerificationKeyPoP},
    blst::BLST_ERROR,
};

/// Error types for multi signatures.
#[derive(Debug, thiserror::Error, Eq, PartialEq)]
pub enum MultiSignatureError {
    /// Invalid Single signature
    #[error("Invalid single signature")]
    SignatureInvalid(Signature),

    /// Invalid aggregate signature
    #[error("Invalid aggregated signature")]
    AggregateSignatureInvalid,

    /// This error occurs when the the serialization of the raw bytes failed
    #[error("Invalid bytes")]
    SerializationError,

    /// Incorrect proof of possession
    #[error("Key with invalid PoP")]
    KeyInvalid(Box<VerificationKeyPoP>),

    /// At least one signature in the batch is invalid
    #[error("One signature in the batch is invalid")]
    BatchInvalid,
}

/// Errors which can be output by Mithril single signature verification.
#[derive(Debug, Clone, thiserror::Error)]
pub enum StmSignatureError {
    /// There is an index out of bounds
    #[error("Received index, {0}, is higher than what the security parameter allows, {1}.")]
    IndexBoundFailed(u64, u64),

    /// MSP.Eval was computed incorrectly
    #[error("The claimed evaluation of function phi is incorrect.")]
    EvalInvalid([u8; 64]),

    /// The lottery was actually lost for the signature
    #[error("Lottery for this epoch was lost.")]
    LotteryLost,

    /// A party submitted an invalid signature
    #[error("A provided signature is invalid")]
    SignatureInvalid(Signature),

    /// Batch verification of STM signatures failed
    #[error("Batch verification of STM signatures failed")]
    BatchInvalid,

    /// This error occurs when the the serialization of the raw bytes failed
    #[error("Invalid bytes")]
    SerializationError,
}

/// Errors which can be output by Mithril aggregate verification.
#[derive(Debug, Clone, thiserror::Error)]
pub enum StmAggregateSignatureError<D: Digest + FixedOutput> {
    /// The IVK is invalid after aggregating the keys
    #[error("Aggregated key does not correspond to the expected key.")]
    IvkInvalid(Box<VerificationKey>),

    /// This error occurs when the the serialization of the raw bytes failed
    #[error("Invalid bytes")]
    SerializationError,

    /// Invalid merkle batch path
    #[error("Batch path does not verify against root")]
    PathInvalid(BatchPath<D>),

    /// Batch verification of STM aggregate signatures failed
    #[error("Batch verification of STM aggregate signatures failed")]
    BatchInvalid,

    /// `CoreVerifier` check failed
    #[error("Core verification error: {0}")]
    CoreVerificationError(#[source] CoreVerifierError),
}

/// Errors which can be output by `CoreVerifier`.
#[derive(Debug, Clone, thiserror::Error)]
pub enum CoreVerifierError {
    /// No quorum was found
    #[error("No Quorum was found. Expected {0} signatures but got {1}")]
    NoQuorum(u64, u64),

    /// There is a duplicate index
    #[error("Indices are not unique.")]
    IndexNotUnique,

    /// The aggregated signature is invalid
    #[error("Aggregate signature is invalid")]
    AggregateSignatureInvalid,

    /// One of the aggregated signatures is invalid
    #[error("Individual signature is invalid: {0}")]
    IndividualSignatureInvalid(#[source] StmSignatureError),
}

/// Error types for aggregation.
#[derive(Debug, Clone, thiserror::Error)]
pub enum AggregationError {
    /// Not enough signatures were collected, got this many instead.
    #[error("Not enough signatures. Got only {0} out of {1}.")]
    NotEnoughSignatures(u64, u64),

    /// This error happens when we try to convert a u64 to a usize and it does not fit
    #[error("Invalid usize conversion")]
    UsizeConversionInvalid,
}

/// Error types related to merkle trees.
#[derive(Debug, Clone, thiserror::Error)]
pub enum MerkleTreeError<D: Digest + FixedOutput> {
    /// Serialization error
    #[error("Serialization of a merkle tree failed")]
    SerializationError,

    /// Invalid merkle path
    #[error("Path does not verify against root")]
    PathInvalid(Path<D>),

    /// Invalid merkle batch path
    #[error("Batch path does not verify against root")]
    BatchPathInvalid(BatchPath<D>),
}

/// Errors which can be outputted by key registration.
#[derive(Debug, Clone, thiserror::Error, PartialEq, Eq)]
pub enum RegisterError {
    /// This key has already been registered by a participant
    #[error("This key has already been registered.")]
    KeyRegistered(Box<VerificationKey>),

    /// The supplied key is not valid
    #[error("The verification of correctness of the supplied key is invalid.")]
    KeyInvalid(Box<VerificationKeyPoP>),

    /// Serialization error
    #[error("Serialization error")]
    SerializationError,

    /// UnregisteredInitializer error
    #[error("Initializer not registered. Cannot participate as a signer.")]
    UnregisteredInitializer,
}

impl From<MultiSignatureError> for StmSignatureError {
    fn from(e: MultiSignatureError) -> Self {
        match e {
            MultiSignatureError::SerializationError => Self::SerializationError,
            MultiSignatureError::SignatureInvalid(e) => Self::SignatureInvalid(e),
            MultiSignatureError::BatchInvalid => unreachable!(),
            MultiSignatureError::KeyInvalid(_) => unreachable!(),
            MultiSignatureError::AggregateSignatureInvalid => unreachable!(),
        }
    }
}

impl<D: Digest + FixedOutput> From<MerkleTreeError<D>> for StmSignatureError {
    fn from(e: MerkleTreeError<D>) -> Self {
        match e {
            MerkleTreeError::SerializationError => Self::SerializationError,
            _ => unreachable!(),
        }
    }
}

impl<D: Digest + FixedOutput> From<MerkleTreeError<D>> for StmAggregateSignatureError<D> {
    fn from(e: MerkleTreeError<D>) -> Self {
        match e {
            MerkleTreeError::BatchPathInvalid(e) => Self::PathInvalid(e),
            MerkleTreeError::SerializationError => Self::SerializationError,
            MerkleTreeError::PathInvalid(_e) => unreachable!(),
        }
    }
}

impl<D: Digest + FixedOutput> From<MultiSignatureError> for StmAggregateSignatureError<D> {
    fn from(e: MultiSignatureError) -> Self {
        match e {
            MultiSignatureError::AggregateSignatureInvalid => {
                Self::from(CoreVerifierError::from(e))
            }
            MultiSignatureError::BatchInvalid => Self::BatchInvalid,
            MultiSignatureError::SerializationError => unreachable!(),
            MultiSignatureError::KeyInvalid(_) => unreachable!(),
            MultiSignatureError::SignatureInvalid(_) => {
                Self::CoreVerificationError(CoreVerifierError::from(e))
            }
        }
    }
}

impl<D: Digest + FixedOutput> From<CoreVerifierError> for StmAggregateSignatureError<D> {
    fn from(e: CoreVerifierError) -> Self {
        Self::CoreVerificationError(e)
    }
}

impl<D: Digest + FixedOutput> From<StmSignatureError> for StmAggregateSignatureError<D> {
    fn from(e: StmSignatureError) -> Self {
        match e {
            StmSignatureError::SerializationError => Self::SerializationError,
            _ => unreachable!(),
        }
    }
}

impl From<AggregationError> for CoreVerifierError {
    fn from(e: AggregationError) -> Self {
        match e {
            AggregationError::NotEnoughSignatures(e, _e) => Self::NoQuorum(e, e),
            AggregationError::UsizeConversionInvalid => unreachable!(),
        }
    }
}

impl From<MultiSignatureError> for CoreVerifierError {
    fn from(e: MultiSignatureError) -> Self {
        match e {
            MultiSignatureError::AggregateSignatureInvalid => Self::AggregateSignatureInvalid,
            MultiSignatureError::BatchInvalid => unreachable!(),
            MultiSignatureError::SerializationError => unreachable!(),
            MultiSignatureError::KeyInvalid(_) => unreachable!(),
            MultiSignatureError::SignatureInvalid(_e) => unreachable!(),
        }
    }
}

impl From<StmSignatureError> for CoreVerifierError {
    fn from(e: StmSignatureError) -> Self {
        CoreVerifierError::IndividualSignatureInvalid(e)
    }
}

impl From<MultiSignatureError> for RegisterError {
    fn from(e: MultiSignatureError) -> Self {
        match e {
            MultiSignatureError::SerializationError => Self::SerializationError,
            MultiSignatureError::KeyInvalid(e) => Self::KeyInvalid(e),
            _ => unreachable!(),
        }
    }
}

/// If verifying a single signature, the signature should be provided. If verifying a multi-sig,
/// no need to provide the signature
pub(crate) fn blst_err_to_mithril(
    e: BLST_ERROR,
    sig: Option<Signature>,
) -> Result<(), MultiSignatureError> {
    match e {
        BLST_ERROR::BLST_SUCCESS => Ok(()),
        BLST_ERROR::BLST_VERIFY_FAIL => {
            if let Some(s) = sig {
                Err(MultiSignatureError::SignatureInvalid(s))
            } else {
                Err(MultiSignatureError::AggregateSignatureInvalid)
            }
        }
        _ => Err(MultiSignatureError::SerializationError),
    }
}