dusk_node_data/ledger/
faults.rs

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
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) DUSK NETWORK. All rights reserved.

use dusk_bytes::Serializable as DuskSerializeble;
use dusk_core::signatures::bls::{
    Error as BlsSigError, MultisigPublicKey as BlsMultisigPublicKey,
    MultisigSignature as BlsMultisigSignature,
};
use dusk_core::stake::EPOCH;
use thiserror::Error;
use tracing::error;

use super::*;
use crate::bls::PublicKey;
use crate::message::payload::{
    Candidate, Ratification, RatificationResult, Validation, Vote,
};
use crate::message::{ConsensusHeader, SignInfo, SignedStepMessage};

#[derive(Debug, Clone)]
#[cfg_attr(any(feature = "faker", test), derive(fake::Dummy, Eq, PartialEq))]
pub enum Fault {
    DoubleCandidate(FaultData<Hash>, FaultData<Hash>),
    DoubleRatificationVote(FaultData<Vote>, FaultData<Vote>),
    DoubleValidationVote(FaultData<Vote>, FaultData<Vote>),
}

impl Fault {
    pub fn size(&self) -> usize {
        // prev_block_hash + round + iter
        const FAULT_CONSENSUS_HEADER_SIZE: usize = 32 + u64::SIZE + u8::SIZE;
        // signer + signature
        const FAULT_SIG_INFO_SIZE: usize =
            BlsMultisigPublicKey::SIZE + BlsMultisigSignature::SIZE;

        const HEADERS: usize = FAULT_CONSENSUS_HEADER_SIZE * 2;
        const SIG_INFOS: usize = FAULT_SIG_INFO_SIZE * 2;
        let faults_data_size = match self {
            Fault::DoubleCandidate(..) => 32 * 2,
            Fault::DoubleRatificationVote(a, b) => {
                a.data.size() + b.data.size()
            }
            Fault::DoubleValidationVote(a, b) => a.data.size() + b.data.size(),
        };

        HEADERS + SIG_INFOS + faults_data_size
    }
}

#[derive(Debug, Error)]
pub enum InvalidFault {
    #[error("Inner faults have same data")]
    Duplicated,
    #[error("Fault is expired")]
    Expired,
    #[error("Fault is from future")]
    Future,
    #[error("Fault is from genesis block")]
    Genesis,
    #[error("Previous hash mismatch")]
    PrevHashMismatch,
    #[error("Iteration mismatch")]
    IterationMismatch,
    #[error("Faults related to emergency iteration")]
    EmergencyIteration,
    #[error("Round mismatch")]
    RoundMismatch,
    #[error("Invalid Signature {0}")]
    InvalidSignature(BlsSigError),
    #[error("Generic error {0}")]
    Other(String),
}

impl From<BlsSigError> for InvalidFault {
    fn from(value: BlsSigError) -> Self {
        Self::InvalidSignature(value)
    }
}

impl Fault {
    // TODO: change to HEIGHT|TYPE|PROV_KEY once faults collection is
    // implemented
    pub fn id(&self) -> [u8; 32] {
        self.digest()
    }

    /// Digest the serialized form
    pub fn digest(&self) -> [u8; 32] {
        let mut b = vec![];
        self.write(&mut b).expect("Write to a vec shall not fail");
        sha3::Sha3_256::digest(&b[..]).into()
    }

    pub fn same(&self, other: &Fault) -> bool {
        let (a, b) = &self.faults_id();
        other.has_id(a) && other.has_id(b)
    }

    fn has_id(&self, id: &[u8; 32]) -> bool {
        let (a, b) = &self.faults_id();
        a == id || b == id
    }

    /// Return the IDs of the inner faults.
    fn faults_id(&self) -> (Hash, Hash) {
        match self {
            Fault::DoubleCandidate(a, b) => {
                let seed = Candidate::SIGN_SEED;
                let a = sha3::Sha3_256::digest(a.get_signed_data(seed)).into();
                let b = sha3::Sha3_256::digest(b.get_signed_data(seed)).into();
                (a, b)
            }
            Fault::DoubleRatificationVote(a, b) => {
                let seed = Ratification::SIGN_SEED;
                let a = sha3::Sha3_256::digest(a.get_signed_data(seed)).into();
                let b = sha3::Sha3_256::digest(b.get_signed_data(seed)).into();
                (a, b)
            }
            Fault::DoubleValidationVote(a, b) => {
                let seed = Validation::SIGN_SEED;
                let a = sha3::Sha3_256::digest(a.get_signed_data(seed)).into();
                let b = sha3::Sha3_256::digest(b.get_signed_data(seed)).into();
                (a, b)
            }
        }
    }

    fn to_culprit(&self) -> PublicKey {
        match self {
            Fault::DoubleRatificationVote(a, _)
            | Fault::DoubleValidationVote(a, _) => a.sig.signer.clone(),
            Fault::DoubleCandidate(a, _) => a.sig.signer.clone(),
        }
    }

    /// Get the ConsensusHeader related to the inner FaultDatas
    fn consensus_header(&self) -> (&ConsensusHeader, &ConsensusHeader) {
        match self {
            Fault::DoubleRatificationVote(a, b)
            | Fault::DoubleValidationVote(a, b) => (&a.header, &b.header),
            Fault::DoubleCandidate(a, b) => (&a.header, &b.header),
        }
    }

    /// Check if both faults are related to the same consensus header and
    /// validate their signatures.
    ///
    /// Return the related ConsensusHeader
    pub fn validate(
        &self,
        current_height: u64,
    ) -> Result<&ConsensusHeader, InvalidFault> {
        let (h1, h2) = self.consensus_header();
        // Check that both consensus headers are the same
        if h1.iteration != h2.iteration {
            return Err(InvalidFault::IterationMismatch);
        }
        if h1.round != h2.round {
            return Err(InvalidFault::RoundMismatch);
        }
        if h1.prev_block_hash != h2.prev_block_hash {
            return Err(InvalidFault::PrevHashMismatch);
        }

        // Check that fault refers to different fault_data
        let (id_a, id_b) = self.faults_id();
        if id_a == id_b {
            return Err(InvalidFault::Duplicated);
        }

        if h1.round == 0 {
            return Err(InvalidFault::Genesis);
        }

        // Check that fault is not expired. A fault expires after an epoch
        if h1.round < current_height.saturating_sub(EPOCH) {
            return Err(InvalidFault::Expired);
        }

        // Check that fault is related to something that is already processed
        if h1.round > current_height {
            return Err(InvalidFault::Future);
        }

        // Verify signatures
        self.verify_sigs()?;

        Ok(h1)
    }

    /// Check if both faults are signed properly
    fn verify_sigs(&self) -> Result<(), BlsSigError> {
        match self {
            Fault::DoubleCandidate(a, b) => {
                let seed = Candidate::SIGN_SEED;
                let msg = a.get_signed_data(seed);
                Self::verify_signature(&a.sig, &msg)?;
                let msg = b.get_signed_data(seed);
                Self::verify_signature(&b.sig, &msg)?;
                Ok(())
            }
            Fault::DoubleRatificationVote(a, b) => {
                let seed = Ratification::SIGN_SEED;
                let msg = a.get_signed_data(seed);
                Self::verify_signature(&a.sig, &msg)?;
                let msg = b.get_signed_data(seed);
                Self::verify_signature(&b.sig, &msg)?;
                Ok(())
            }
            Fault::DoubleValidationVote(a, b) => {
                let seed = Validation::SIGN_SEED;
                let msg = a.get_signed_data(seed);
                Self::verify_signature(&a.sig, &msg)?;
                let msg = b.get_signed_data(seed);
                Self::verify_signature(&b.sig, &msg)?;
                Ok(())
            }
        }
    }

    fn verify_signature(
        sign_info: &SignInfo,
        msg: &[u8],
    ) -> Result<(), BlsSigError> {
        let signature = sign_info.signature.inner();
        let sig = BlsMultisigSignature::from_bytes(signature)?;
        let pk = BlsMultisigPublicKey::aggregate(&[*sign_info.signer.inner()])?;
        pk.verify(&sig, msg)
    }
}

impl FaultData<Hash> {
    fn get_signed_data(&self, seed: &[u8]) -> Vec<u8> {
        let mut signable = self.header.signable();
        signable.extend_from_slice(seed);
        signable.extend_from_slice(&self.data);
        signable
    }
}
impl FaultData<Vote> {
    fn get_signed_data(&self, seed: &[u8]) -> Vec<u8> {
        let mut signable = self.header.signable();
        signable.extend_from_slice(seed);
        self.data
            .write(&mut signable)
            .expect("Writing to vec should succeed");
        signable
    }
}

#[derive(Debug, Clone)]
#[cfg_attr(any(feature = "faker", test), derive(fake::Dummy, Eq, PartialEq))]
#[allow(clippy::large_enum_variant)]
pub struct FaultData<V> {
    header: ConsensusHeader,
    sig: SignInfo,
    data: V,
}

impl<V: Serializable> Serializable for FaultData<V> {
    fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
        self.header.write(w)?;
        self.sig.write(w)?;
        self.data.write(w)?;
        Ok(())
    }

    fn read<R: Read>(r: &mut R) -> io::Result<Self>
    where
        Self: Sized,
    {
        let header = ConsensusHeader::read(r)?;
        let sig = SignInfo::read(r)?;
        let data = V::read(r)?;

        Ok(Self { header, sig, data })
    }
}

impl Serializable for Fault {
    fn write<W: Write>(&self, w: &mut W) -> io::Result<()> {
        match self {
            Fault::DoubleCandidate(a, b) => {
                w.write_all(&[0u8])?;
                a.write(w)?;
                b.write(w)?;
            }
            Fault::DoubleRatificationVote(a, b) => {
                w.write_all(&[1u8])?;
                a.write(w)?;
                b.write(w)?;
            }
            Fault::DoubleValidationVote(a, b) => {
                w.write_all(&[2u8])?;
                a.write(w)?;
                b.write(w)?;
            }
        }

        Ok(())
    }

    fn read<R: Read>(r: &mut R) -> io::Result<Self>
    where
        Self: Sized,
    {
        let fault = Self::read_u8(r)?;
        let fault = match fault {
            0 => {
                Fault::DoubleCandidate(FaultData::read(r)?, FaultData::read(r)?)
            }
            1 => Fault::DoubleRatificationVote(
                FaultData::read(r)?,
                FaultData::read(r)?,
            ),
            2 => Fault::DoubleValidationVote(
                FaultData::read(r)?,
                FaultData::read(r)?,
            ),
            p => Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("Invalid fault: {p}"),
            ))?,
        };
        Ok(fault)
    }
}

#[derive(Clone, Debug)]
pub struct Slash {
    pub provisioner: PublicKey,
    pub r#type: SlashType,
}

#[derive(Clone, Debug)]
pub enum SlashType {
    Soft,
    Hard,
    HardWithSeverity(u8),
}

impl Slash {
    fn from_iteration_info(
        value: &IterationInfo,
    ) -> Result<Option<Self>, dusk_bytes::Error> {
        let (attestation, provisioner) = value;
        let slash = match attestation.result {
            RatificationResult::Fail(Vote::NoCandidate) => SlashType::Soft,
            RatificationResult::Fail(Vote::Invalid(_)) => SlashType::Hard,
            _ => {
                return Ok(None);
            }
        };
        let provisioner = (*provisioner.inner()).try_into().map_err(|e| {
            error!("Unable to generate provisioners from IterationInfo: {e:?}");
            e
        })?;
        Ok(Some(Self {
            provisioner,
            r#type: slash,
        }))
    }

    pub fn from_block(block: &Block) -> Result<Vec<Slash>, io::Error> {
        Self::from_iterations_and_faults(
            &block.header().failed_iterations,
            block.faults(),
        )
    }

    pub fn from_iterations_and_faults(
        failed_iterations: &IterationsInfo,
        faults: &[Fault],
    ) -> Result<Vec<Slash>, io::Error> {
        let mut slashing = failed_iterations
            .att_list
            .iter()
            .flatten()
            .flat_map(Slash::from_iteration_info)
            .flatten()
            .collect::<Vec<_>>();
        slashing.extend(faults.iter().map(Slash::from));
        Ok(slashing)
    }
}

impl From<&Fault> for Slash {
    fn from(value: &Fault) -> Self {
        let slash_type = match value {
            Fault::DoubleCandidate(_, _)
            | Fault::DoubleRatificationVote(_, _)
            | Fault::DoubleValidationVote(_, _) => {
                SlashType::HardWithSeverity(2u8)
            }
        };
        let provisioner = value.to_culprit();
        Self {
            provisioner,
            r#type: slash_type,
        }
    }
}