tendermint/
evidence.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
//! Evidence of malfeasance by validators (i.e. signing conflicting votes).

use core::{
    convert::{TryFrom, TryInto},
    slice,
};

use serde::{Deserialize, Serialize};
use tendermint_proto::google::protobuf::Duration as RawDuration;
use tendermint_proto::Protobuf;

use crate::{
    block::{signed_header::SignedHeader, Height},
    error::Error,
    prelude::*,
    serializers, validator,
    vote::Power,
    Time, Vote,
};

/// Evidence of malfeasance by validators (i.e. signing conflicting votes or light client attack).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Evidence {
    /// Duplicate vote evidence
    DuplicateVote(Box<DuplicateVoteEvidence>),

    /// LightClient attack evidence
    LightClientAttack(Box<LightClientAttackEvidence>),
}

impl From<LightClientAttackEvidence> for Evidence {
    fn from(ev: LightClientAttackEvidence) -> Self {
        Self::LightClientAttack(Box::new(ev))
    }
}

impl From<DuplicateVoteEvidence> for Evidence {
    fn from(ev: DuplicateVoteEvidence) -> Self {
        Self::DuplicateVote(Box::new(ev))
    }
}

/// Duplicate vote evidence
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct DuplicateVoteEvidence {
    pub vote_a: Vote,
    pub vote_b: Vote,
    pub total_voting_power: Power,
    pub validator_power: Power,
    pub timestamp: Time,
}

impl DuplicateVoteEvidence {
    /// constructor
    pub fn new(vote_a: Vote, vote_b: Vote) -> Result<Self, Error> {
        if vote_a.height != vote_b.height {
            return Err(Error::invalid_evidence());
        }

        // Todo: make more assumptions about what is considered a valid evidence for duplicate vote
        Ok(Self {
            vote_a,
            vote_b,
            total_voting_power: Default::default(),
            validator_power: Default::default(),
            timestamp: Time::unix_epoch(),
        })
    }

    /// Get votes
    pub fn votes(&self) -> (&Vote, &Vote) {
        (&self.vote_a, &self.vote_b)
    }
}

/// Conflicting block detected in light client attack
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ConflictingBlock {
    pub signed_header: SignedHeader,
    pub validator_set: validator::Set,
}

/// Light client attack evidence
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LightClientAttackEvidence {
    pub conflicting_block: ConflictingBlock,
    pub common_height: Height,
    pub byzantine_validators: Vec<validator::Info>,
    pub total_voting_power: Power,
    pub timestamp: Time,
}

/// A list of `Evidence`.
///
/// <https://github.com/tendermint/spec/blob/d46cd7f573a2c6a2399fcab2cde981330aa63f37/spec/core/data_structures.md#evidencedata>
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct List(Vec<Evidence>);

impl List {
    /// Create a new evidence data collection
    pub fn new<I>(into_evidence: I) -> List
    where
        I: Into<Vec<Evidence>>,
    {
        List(into_evidence.into())
    }

    /// Convert this evidence data into a vector
    pub fn into_vec(self) -> Vec<Evidence> {
        self.0
    }

    /// Iterate over the evidence data
    pub fn iter(&self) -> slice::Iter<'_, Evidence> {
        self.0.iter()
    }
}

impl AsRef<[Evidence]> for List {
    fn as_ref(&self) -> &[Evidence] {
        &self.0
    }
}

/// EvidenceParams determine how we handle evidence of malfeasance.
///
/// [Tendermint documentation](https://docs.tendermint.com/master/spec/core/data_structures.html#evidenceparams)
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Params {
    /// Max age of evidence, in blocks.
    #[serde(with = "serializers::from_str")]
    pub max_age_num_blocks: u64,

    /// Max age of evidence, in time.
    ///
    /// It should correspond with an app's "unbonding period" or other similar
    /// mechanism for handling [Nothing-At-Stake attacks][nas].
    ///
    /// [nas]: https://github.com/ethereum/wiki/wiki/Proof-of-Stake-FAQ#what-is-the-nothing-at-stake-problem-and-how-can-it-be-fixed
    pub max_age_duration: Duration,

    /// This sets the maximum size of total evidence in bytes that can be
    /// committed in a single block, and should fall comfortably under the max
    /// block bytes. The default is 1048576 or 1MB.
    #[serde(with = "serializers::from_str", default)]
    pub max_bytes: i64,
}

// =============================================================================
// Protobuf conversions
// =============================================================================

tendermint_pb_modules! {
    use pb::types as raw;

    use super::{List, LightClientAttackEvidence, DuplicateVoteEvidence, ConflictingBlock, Evidence, Params};
    use crate::{error::Error, prelude::*};

    impl Protobuf<raw::Evidence> for Evidence {}

    impl TryFrom<raw::Evidence> for Evidence {
        type Error = Error;

        fn try_from(value: raw::Evidence) -> Result<Self, Self::Error> {
            match value.sum.ok_or_else(Error::invalid_evidence)? {
                raw::evidence::Sum::DuplicateVoteEvidence(ev) => {
                    Ok(Evidence::DuplicateVote(Box::new(ev.try_into()?)))
                },
                raw::evidence::Sum::LightClientAttackEvidence(ev) => {
                    Ok(Evidence::LightClientAttack(Box::new(ev.try_into()?)))
                },
            }
        }
    }

    impl From<Evidence> for raw::Evidence {
        fn from(value: Evidence) -> Self {
            match value {
                Evidence::DuplicateVote(ev) => raw::Evidence {
                    sum: Some(raw::evidence::Sum::DuplicateVoteEvidence((*ev).into())),
                },
                Evidence::LightClientAttack(ev) => raw::Evidence {
                    sum: Some(raw::evidence::Sum::LightClientAttackEvidence((*ev).into())),
                },
            }
        }
    }

    impl Protobuf<raw::DuplicateVoteEvidence> for DuplicateVoteEvidence {}

    impl TryFrom<raw::DuplicateVoteEvidence> for DuplicateVoteEvidence {
        type Error = Error;

        fn try_from(value: raw::DuplicateVoteEvidence) -> Result<Self, Self::Error> {
            Ok(Self {
                vote_a: value
                    .vote_a
                    .ok_or_else(Error::missing_evidence)?
                    .try_into()?,
                vote_b: value
                    .vote_b
                    .ok_or_else(Error::missing_evidence)?
                    .try_into()?,
                total_voting_power: value.total_voting_power.try_into()?,
                validator_power: value.validator_power.try_into()?,
                timestamp: value
                    .timestamp
                    .ok_or_else(Error::missing_timestamp)?
                    .try_into()?,
            })
        }
    }

    impl From<DuplicateVoteEvidence> for raw::DuplicateVoteEvidence {
        fn from(value: DuplicateVoteEvidence) -> Self {
            raw::DuplicateVoteEvidence {
                vote_a: Some(value.vote_a.into()),
                vote_b: Some(value.vote_b.into()),
                total_voting_power: value.total_voting_power.into(),
                validator_power: value.total_voting_power.into(),
                timestamp: Some(value.timestamp.into()),
            }
        }
    }

    impl Protobuf<raw::LightBlock> for ConflictingBlock {}

    impl TryFrom<raw::LightBlock> for ConflictingBlock {
        type Error = Error;

        fn try_from(value: raw::LightBlock) -> Result<Self, Self::Error> {
            Ok(ConflictingBlock {
                signed_header: value
                    .signed_header
                    .ok_or_else(Error::missing_evidence)?
                    .try_into()?,
                validator_set: value
                    .validator_set
                    .ok_or_else(Error::missing_evidence)?
                    .try_into()?,
            })
        }
    }

    impl From<ConflictingBlock> for raw::LightBlock {
        fn from(value: ConflictingBlock) -> Self {
            raw::LightBlock {
                signed_header: Some(value.signed_header.into()),
                validator_set: Some(value.validator_set.into()),
            }
        }
    }

    impl Protobuf<raw::LightClientAttackEvidence> for LightClientAttackEvidence {}

    impl TryFrom<raw::LightClientAttackEvidence> for LightClientAttackEvidence {
        type Error = Error;

        fn try_from(ev: raw::LightClientAttackEvidence) -> Result<Self, Self::Error> {
            Ok(LightClientAttackEvidence {
                conflicting_block: ev
                    .conflicting_block
                    .ok_or_else(Error::missing_evidence)?
                    .try_into()?,
                common_height: ev.common_height.try_into()?,
                byzantine_validators: ev
                    .byzantine_validators
                    .into_iter()
                    .map(TryInto::try_into)
                    .collect::<Result<Vec<_>, _>>()?,
                total_voting_power: ev.total_voting_power.try_into()?,
                timestamp: ev
                    .timestamp
                    .ok_or_else(Error::missing_timestamp)?
                    .try_into()?,
            })
        }
    }

    impl From<LightClientAttackEvidence> for raw::LightClientAttackEvidence {
        fn from(ev: LightClientAttackEvidence) -> Self {
            raw::LightClientAttackEvidence {
                conflicting_block: Some(ev.conflicting_block.into()),
                common_height: ev.common_height.into(),
                byzantine_validators: ev
                    .byzantine_validators
                    .into_iter()
                    .map(Into::into)
                    .collect(),
                total_voting_power: ev.total_voting_power.into(),
                timestamp: Some(ev.timestamp.into()),
            }
        }
    }

    impl Protobuf<raw::EvidenceList> for List {}

    impl TryFrom<raw::EvidenceList> for List {
        type Error = Error;
        fn try_from(value: raw::EvidenceList) -> Result<Self, Self::Error> {
            let evidence = value
                .evidence
                .into_iter()
                .map(TryInto::try_into)
                .collect::<Result<Vec<_>, _>>()?;
            Ok(Self(evidence))
        }
    }

    impl From<List> for raw::EvidenceList {
        fn from(value: List) -> Self {
            raw::EvidenceList {
                evidence: value.0.into_iter().map(Into::into).collect(),
            }
        }
    }

    impl Protobuf<raw::EvidenceParams> for Params {}

    impl TryFrom<raw::EvidenceParams> for Params {
        type Error = Error;

        fn try_from(value: raw::EvidenceParams) -> Result<Self, Self::Error> {
            Ok(Self {
                max_age_num_blocks: value
                    .max_age_num_blocks
                    .try_into()
                    .map_err(Error::negative_max_age_num)?,
                max_age_duration: value
                    .max_age_duration
                    .ok_or_else(Error::missing_max_age_duration)?
                    .try_into()?,
                max_bytes: value.max_bytes,
            })
        }
    }

    impl From<Params> for raw::EvidenceParams {
        fn from(value: Params) -> Self {
            Self {
                // Todo: Implement proper domain types so this becomes infallible
                max_age_num_blocks: value.max_age_num_blocks.try_into().unwrap(),
                max_age_duration: Some(value.max_age_duration.into()),
                max_bytes: value.max_bytes,
            }
        }
    }
}

/// Duration is a wrapper around core::time::Duration
/// essentially, to keep the usages look cleaner
/// i.e. you can avoid using serde annotations everywhere
/// Todo: harmonize google::protobuf::Duration, core::time::Duration and this. Too many structs.
/// <https://github.com/informalsystems/tendermint-rs/issues/741>
#[derive(Copy, Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Duration(#[serde(with = "serializers::time_duration")] pub core::time::Duration);

impl From<Duration> for core::time::Duration {
    fn from(d: Duration) -> core::time::Duration {
        d.0
    }
}

impl Protobuf<RawDuration> for Duration {}

impl TryFrom<RawDuration> for Duration {
    type Error = Error;

    fn try_from(value: RawDuration) -> Result<Self, Self::Error> {
        Ok(Self(core::time::Duration::new(
            value.seconds.try_into().map_err(Error::integer_overflow)?,
            value.nanos.try_into().map_err(Error::integer_overflow)?,
        )))
    }
}

impl From<Duration> for RawDuration {
    fn from(value: Duration) -> Self {
        // Todo: make the struct into a proper domaintype so this becomes infallible.
        Self {
            seconds: value.0.as_secs() as i64,
            nanos: value.0.subsec_nanos() as i32,
        }
    }
}