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
use std::{cmp::max, hash::Hash, ops::Index};

use parity_scale_codec::{Decode, Encode};
use sp_runtime::SaturatedConversion;

use crate::{
    phron_primitives::{BlockHash, BlockNumber},
    data_io::legacy::MAX_DATA_BRANCH_LEN,
    BlockId, SessionBoundaries,
};

/// Represents a proposal we obtain from another node. Note that since the proposal might come from
/// a malicious node there is no guarantee that the block hashes in the proposal correspond to real blocks
/// and even if they do then they could not match the provided number. Moreover, the block number in the
/// proposal might be completely arbitrary and hence we perform initial validation of the block number and
/// the branch length before we transform it into a safer `PhronProposal` type that guarantees we will not
/// fail on  any integer over- or underflows.
/// We expect that honest nodes create UnvalidatedPhronProposal {branch: [h_0, h_1, ..., h_n], number: num} objects
/// that represent an ascending sequence of blocks b_0, b_1, ..., b_n satisfying the following conditions:
///     1) hash(b_i) = h_i for i = 0, 1, ..., n,
///     2) parent(b_{i+1}) = b_i for i = 0, 1, ..., (n-1),
///     3) height(b_n) = num,
///     4) The parent of b_0 has been finalized (prior to creating this PhronData).
/// Such an UnvalidatedPhronProposal  object should be thought of as a proposal for block b_n to be finalized.
/// We refer for to `DataProvider` for a precise description of honest nodes' algorithm of creating proposals.
#[derive(Clone, Debug, Encode, Decode, Hash, PartialEq, Eq)]
pub struct UnvalidatedPhronProposal {
    pub branch: Vec<BlockHash>,
    pub number: BlockNumber,
}

/// Represents possible invalid states as described in [UnvalidatedPhronProposal].
#[derive(Debug, PartialEq, Eq)]
pub enum ValidationError {
    BranchEmpty,
    BranchTooLong {
        branch_size: usize,
    },
    BlockNumberOutOfBounds {
        branch_size: usize,
        block_number: BlockNumber,
    },
    BlockOutsideSessionBoundaries {
        session_start: BlockNumber,
        session_end: BlockNumber,
        top_block: BlockNumber,
        bottom_block: BlockNumber,
    },
}

impl UnvalidatedPhronProposal {
    pub(crate) fn new(branch: Vec<BlockHash>, block_number: BlockNumber) -> Self {
        UnvalidatedPhronProposal {
            branch,
            number: block_number,
        }
    }

    pub(crate) fn validate_bounds(
        &self,
        session_boundaries: &SessionBoundaries,
    ) -> Result<PhronProposal, ValidationError> {
        use ValidationError::*;

        if self.branch.len() > MAX_DATA_BRANCH_LEN {
            return Err(BranchTooLong {
                branch_size: self.branch.len(),
            });
        }
        if self.branch.is_empty() {
            return Err(BranchEmpty);
        }
        if self.number < <BlockNumber>::saturated_from(self.branch.len()) {
            // Note that this also excludes branches starting at the genesis (0th) block.
            return Err(BlockNumberOutOfBounds {
                branch_size: self.branch.len(),
                block_number: self.number,
            });
        }

        let bottom_block = self.number - <BlockNumber>::saturated_from(self.branch.len() - 1);
        let top_block = self.number;
        let session_start = session_boundaries.first_block();
        let session_end = session_boundaries.last_block();
        if session_start > bottom_block || top_block > session_end {
            return Err(BlockOutsideSessionBoundaries {
                session_start,
                session_end,
                top_block,
                bottom_block,
            });
        }

        Ok(PhronProposal {
            branch: self.branch.clone(),
            number: self.number,
        })
    }
}

/// A version of UnvalidatedPhronProposal that has been initially validated and fits
/// within session bounds.
#[derive(Clone, Debug, Encode, Decode, Hash, PartialEq, Eq)]
pub struct PhronProposal {
    branch: Vec<BlockHash>,
    number: BlockNumber,
}

impl Index<usize> for PhronProposal {
    type Output = BlockHash;
    fn index(&self, index: usize) -> &Self::Output {
        &self.branch[index]
    }
}

impl PhronProposal {
    /// Outputs the length the branch.
    pub fn len(&self) -> usize {
        self.branch.len()
    }

    /// Outputs the highest block in the branch.
    pub fn top_block(&self) -> BlockId {
        (
            *self
                .branch
                .last()
                .expect("cannot be empty for correct data"),
            self.number_top_block(),
        )
            .into()
    }

    /// Outputs the lowest block in the branch.
    pub fn bottom_block(&self) -> BlockId {
        // Assumes that the data is within bounds
        (
            *self
                .branch
                .first()
                .expect("cannot be empty for correct data"),
            self.number_bottom_block(),
        )
            .into()
    }

    /// Outputs the number one below the lowest block in the branch.
    pub fn number_below_branch(&self) -> BlockNumber {
        // Assumes that data is within bounds
        self.number - <BlockNumber>::saturated_from(self.branch.len())
    }

    /// Outputs the number of the lowest block in the branch.
    pub fn number_bottom_block(&self) -> BlockNumber {
        // Assumes that data is within bounds
        self.number - <BlockNumber>::saturated_from(self.branch.len() - 1)
    }

    /// Outputs the number of the highest block in the branch.
    pub fn number_top_block(&self) -> BlockNumber {
        self.number
    }

    /// Outputs the block corresponding to the number in the proposed branch in case num is
    /// between the lowest and highest block number of the branch. Otherwise returns None.
    pub fn block_at_num(&self, num: BlockNumber) -> Option<BlockId> {
        if self.number_bottom_block() <= num && num <= self.number_top_block() {
            let ind: usize = (num - self.number_bottom_block()).saturated_into();
            return Some((self.branch[ind], num).into());
        }
        None
    }

    /// Outputs an iterator over blocks starting at num. If num is too high, the iterator is
    /// empty, if it's too low the whole branch is returned.
    pub fn blocks_from_num(&self, num: BlockNumber) -> impl Iterator<Item = BlockId> + '_ {
        let num = max(num, self.number_bottom_block());
        self.branch
            .iter()
            .skip((num - self.number_bottom_block()).saturated_into())
            .cloned()
            .zip(0u32..)
            .map(move |(hash, index)| (hash, num + index).into())
    }
}

#[derive(PartialEq, Eq, Clone, Debug)]
pub enum PendingProposalStatus {
    PendingTopBlock,
    TopBlockImportedButIncorrectBranch,
    TopBlockImportedButNotFinalizedAncestor,
}

#[derive(PartialEq, Eq, Clone, Debug)]
pub enum ProposalStatus {
    Finalize(Vec<BlockId>),
    Ignore,
    Pending(PendingProposalStatus),
}

#[cfg(test)]
mod tests {
    use sp_core::hash::H256;

    use super::{UnvalidatedPhronProposal, ValidationError::*};
    use crate::{
        phron_primitives::BlockNumber, data_io::MAX_DATA_BRANCH_LEN, SessionBoundaryInfo,
        SessionId, SessionPeriod,
    };

    #[test]
    fn proposal_with_empty_branch_is_invalid() {
        let session_boundaries =
            SessionBoundaryInfo::new(SessionPeriod(20)).boundaries_for_session(SessionId(1));
        let branch = vec![];
        let proposal = UnvalidatedPhronProposal::new(branch, session_boundaries.first_block());
        assert_eq!(
            proposal.validate_bounds(&session_boundaries),
            Err(BranchEmpty)
        );
    }

    #[test]
    fn too_long_proposal_is_invalid() {
        let session_boundaries =
            SessionBoundaryInfo::new(SessionPeriod(20)).boundaries_for_session(SessionId(1));
        let session_end = session_boundaries.last_block();
        let branch = vec![H256::default(); MAX_DATA_BRANCH_LEN + 1];
        let branch_size = branch.len();
        let proposal = UnvalidatedPhronProposal::new(branch, session_end);
        assert_eq!(
            proposal.validate_bounds(&session_boundaries),
            Err(BranchTooLong { branch_size })
        );
    }

    #[test]
    fn proposal_not_within_session_is_invalid() {
        let session_boundaries =
            SessionBoundaryInfo::new(SessionPeriod(20)).boundaries_for_session(SessionId(1));
        let session_start = session_boundaries.first_block();
        let session_end = session_boundaries.last_block();
        let branch = vec![H256::default(); 2];

        let proposal = UnvalidatedPhronProposal::new(branch.clone(), session_start);
        assert_eq!(
            proposal.validate_bounds(&session_boundaries),
            Err(BlockOutsideSessionBoundaries {
                session_start,
                session_end,
                bottom_block: session_start - 1,
                top_block: session_start
            })
        );

        let proposal = UnvalidatedPhronProposal::new(branch, session_end + 1);
        assert_eq!(
            proposal.validate_bounds(&session_boundaries),
            Err(BlockOutsideSessionBoundaries {
                session_start,
                session_end,
                bottom_block: session_end,
                top_block: session_end + 1
            })
        );
    }

    #[test]
    fn proposal_starting_at_zero_block_is_invalid() {
        let session_boundaries =
            SessionBoundaryInfo::new(SessionPeriod(20)).boundaries_for_session(SessionId(0));
        let branch = vec![H256::default(); 2];

        let proposal = UnvalidatedPhronProposal::new(branch, 1);
        assert_eq!(
            proposal.validate_bounds(&session_boundaries),
            Err(BlockNumberOutOfBounds {
                branch_size: 2,
                block_number: 1
            })
        );
    }

    #[test]
    fn valid_proposal_is_validated_positively() {
        let session_boundaries =
            SessionBoundaryInfo::new(SessionPeriod(20)).boundaries_for_session(SessionId(0));

        let branch = vec![H256::default(); MAX_DATA_BRANCH_LEN];
        let proposal =
            UnvalidatedPhronProposal::new(branch, (MAX_DATA_BRANCH_LEN + 1) as BlockNumber);
        assert!(proposal.validate_bounds(&session_boundaries).is_ok());

        let branch = vec![H256::default(); 1];
        let proposal =
            UnvalidatedPhronProposal::new(branch, (MAX_DATA_BRANCH_LEN + 1) as BlockNumber);
        assert!(proposal.validate_bounds(&session_boundaries).is_ok());
    }
}