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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
// Copyright 2019 Conflux Foundation. All rights reserved.
// Conflux is free software and distributed under GNU General Public License.
// See http://www.gnu.org/licenses/

use crate::sync::Error;
use cfx_storage::{
    rlp_key_value_len,
    storage_db::{
        key_value_db::KeyValueDbIterableTrait, snapshot_db::SnapshotDbTrait,
        OpenSnapshotMptTrait,
    },
    MptSlicer, StorageManager, TrieProof,
};
use cfx_types::H256;
use fallible_iterator::FallibleIterator;
use malloc_size_of_derive::MallocSizeOf as DeriveMallocSizeOf;
use primitives::{EpochId, MerkleHash};
use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream};
use rlp_derive::{RlpDecodable, RlpEncodable};

#[derive(
    Clone, Hash, Ord, PartialOrd, PartialEq, Eq, Debug, DeriveMallocSizeOf,
)]
pub enum SnapshotSyncCandidate {
    OneStepSync {
        height: u64,
        snapshot_epoch_id: EpochId,
    },
    FullSync {
        height: u64,
        snapshot_epoch_id: EpochId,
    },
    IncSync {
        height: u64,
        base_snapshot_epoch_id: EpochId,
        snapshot_epoch_id: EpochId,
    },
}

impl SnapshotSyncCandidate {
    fn to_type_id(&self) -> u8 {
        match self {
            SnapshotSyncCandidate::OneStepSync { .. } => 0,
            SnapshotSyncCandidate::FullSync { .. } => 1,
            SnapshotSyncCandidate::IncSync { .. } => 2,
        }
    }

    pub fn get_snapshot_epoch_id(&self) -> &EpochId {
        match self {
            SnapshotSyncCandidate::OneStepSync {
                snapshot_epoch_id, ..
            } => snapshot_epoch_id,
            SnapshotSyncCandidate::FullSync {
                snapshot_epoch_id, ..
            } => snapshot_epoch_id,
            SnapshotSyncCandidate::IncSync {
                snapshot_epoch_id, ..
            } => snapshot_epoch_id,
        }
    }
}

impl Encodable for SnapshotSyncCandidate {
    fn rlp_append(&self, s: &mut RlpStream) {
        match &self {
            SnapshotSyncCandidate::OneStepSync {
                height,
                snapshot_epoch_id,
            } => {
                s.begin_list(3)
                    .append(&self.to_type_id())
                    .append(height)
                    .append(snapshot_epoch_id);
            }
            SnapshotSyncCandidate::FullSync {
                height,
                snapshot_epoch_id,
            } => {
                s.begin_list(3)
                    .append(&self.to_type_id())
                    .append(height)
                    .append(snapshot_epoch_id);
            }
            SnapshotSyncCandidate::IncSync {
                height,
                base_snapshot_epoch_id,
                snapshot_epoch_id,
            } => {
                s.begin_list(4)
                    .append(&self.to_type_id())
                    .append(height)
                    .append(base_snapshot_epoch_id)
                    .append(snapshot_epoch_id);
            }
        }
    }
}

impl Decodable for SnapshotSyncCandidate {
    fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
        let type_id: u8 = rlp.val_at(0)?;
        let parsed = match type_id {
            0 => SnapshotSyncCandidate::OneStepSync {
                height: rlp.val_at(1)?,
                snapshot_epoch_id: rlp.val_at(2)?,
            },
            1 => SnapshotSyncCandidate::FullSync {
                height: rlp.val_at(1)?,
                snapshot_epoch_id: rlp.val_at(2)?,
            },
            2 => SnapshotSyncCandidate::IncSync {
                height: rlp.val_at(1)?,
                base_snapshot_epoch_id: rlp.val_at(2)?,
                snapshot_epoch_id: rlp.val_at(3)?,
            },
            _ => {
                return Err(DecoderError::Custom(
                    "Unknown SnapshotSyncCandidate type id",
                ))
            }
        };
        debug_assert_eq!(parsed.to_type_id(), type_id);
        Ok(parsed)
    }
}

#[derive(
    Clone,
    RlpEncodable,
    RlpDecodable,
    Ord,
    PartialOrd,
    Eq,
    PartialEq,
    Debug,
    Hash,
    DeriveMallocSizeOf,
)]
pub struct ChunkKey {
    lower_bound_incl: Option<Vec<u8>>,
    pub upper_bound_excl: Option<Vec<u8>>,
}

/// FIXME Handle the case `next.is_some()`
#[derive(Default, Clone)]
pub struct RangedManifest {
    pub chunk_boundaries: Vec<Vec<u8>>,
    pub chunk_boundary_proofs: Vec<TrieProof>,
    pub next: Option<Vec<u8>>,
}

impl Encodable for RangedManifest {
    fn rlp_append(&self, s: &mut RlpStream) {
        s.begin_list(3)
            .append_list::<Vec<u8>, Vec<u8>>(&self.chunk_boundaries)
            .append_list(&self.chunk_boundary_proofs)
            .append(&self.next);
    }
}

impl Decodable for RangedManifest {
    fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
        Ok(RangedManifest {
            chunk_boundaries: rlp.list_at(0)?,
            chunk_boundary_proofs: rlp.list_at(1)?,
            next: rlp.val_at(2)?,
        })
    }
}

impl RangedManifest {
    /// Validate the manifest with specified snapshot merkle root and the
    /// requested start chunk key. Basically, the retrieved chunks should
    /// not be empty, and the proofs of all chunk keys are valid.
    pub fn validate(&self, snapshot_root: &MerkleHash) -> Result<(), Error> {
        if self.chunk_boundaries.len() != self.chunk_boundary_proofs.len() {
            bail!(Error::InvalidSnapshotManifest(
                "chunk and proof number do not match".into(),
            ));
        }
        if let Some(next) = &self.next {
            if next != self.chunk_boundaries.last().unwrap() {
                bail!(Error::InvalidSnapshotManifest(
                    "next does not match last boundary".into(),
                ));
            }
        }

        // validate the trie proof for all chunks
        for (chunk_index, proof) in
            self.chunk_boundary_proofs.iter().enumerate()
        {
            if proof.get_merkle_root() != snapshot_root {
                warn!(
                    "Manifest merkle root should be {:?}, get {:?}",
                    snapshot_root,
                    proof.get_merkle_root()
                );
                bail!(Error::InvalidSnapshotManifest(
                    "invalid proof merkle root".into(),
                ));
            }
            if !proof.if_proves_key(&self.chunk_boundaries[chunk_index]).0 {
                bail!(Error::InvalidSnapshotManifest("invalid proof".into(),));
            }
        }
        Ok(())
    }

    pub fn convert_boundaries_to_chunks(
        chunk_boundaries: Vec<Vec<u8>>,
    ) -> Vec<ChunkKey> {
        let mut chunks = Vec::with_capacity(chunk_boundaries.len());
        let mut lower = None;
        for key in chunk_boundaries {
            chunks.push(ChunkKey {
                lower_bound_incl: lower,
                upper_bound_excl: Some(key.clone()),
            });
            lower = Some(key);
        }
        chunks.push(ChunkKey {
            lower_bound_incl: lower,
            upper_bound_excl: None,
        });
        chunks
    }

    pub fn load(
        snapshot_to_sync: &SnapshotSyncCandidate, start_key: Option<Vec<u8>>,
        storage_manager: &StorageManager, chunk_size: u64, max_chunks: usize,
    ) -> Result<Option<(RangedManifest, MerkleHash)>, Error> {
        let snapshot_epoch_id = match snapshot_to_sync {
            SnapshotSyncCandidate::FullSync {
                snapshot_epoch_id, ..
            } => snapshot_epoch_id,
            SnapshotSyncCandidate::IncSync { .. } => {
                unimplemented!();
            }
            SnapshotSyncCandidate::OneStepSync { .. } => {
                unimplemented!();
            }
        };
        debug!(
            "begin to load manifest, snapshot_epoch_id = {:?}, start_key = {:?}",
            snapshot_epoch_id, start_key
        );

        let snapshot_db_manager =
            storage_manager.get_storage_manager().get_snapshot_manager();

        let snapshot_db = match snapshot_db_manager.get_snapshot_by_epoch_id(
            snapshot_epoch_id,
            /* try_open = */ true,
            true,
        )? {
            Some(db) => db,
            None => {
                debug!(
                    "failed to load manifest, cannot find snapshot {:?}",
                    snapshot_epoch_id
                );
                return Ok(None);
            }
        };
        let mut snapshot_mpt = snapshot_db.open_snapshot_mpt_shared()?;
        let merkle_root = snapshot_mpt.merkle_root;
        let mut slicer = match start_key {
            Some(ref key) => MptSlicer::new_from_key(&mut snapshot_mpt, key)?,
            None => MptSlicer::new(&mut snapshot_mpt)?,
        };

        let mut manifest = RangedManifest::default();
        let mut has_next = true;

        for i in 0..max_chunks {
            trace!("cut chunks for manifest, loop = {}", i);
            slicer.advance(chunk_size)?;
            match slicer.get_range_end_key() {
                None => {
                    has_next = false;
                    break;
                }
                Some(key) => {
                    manifest.chunk_boundaries.push(key.to_vec());
                    manifest.chunk_boundary_proofs.push(slicer.to_proof());
                }
            }
        }

        if has_next {
            manifest.next = Some(
                manifest
                    .chunk_boundaries
                    .last()
                    .expect("boundaries not empty if has next")
                    .clone(),
            );
        }

        debug!(
            "succeed to load manifest, chunks = {}, next_chunk_key = {:?}",
            manifest.chunk_boundaries.len(),
            manifest.next
        );

        Ok(Some((manifest, merkle_root)))
    }
}

#[derive(Default)]
pub struct Chunk {
    pub keys: Vec<Vec<u8>>,
    pub values: Vec<Vec<u8>>,
}

impl Encodable for Chunk {
    fn rlp_append(&self, s: &mut RlpStream) {
        s.begin_list(2)
            .append_list::<Vec<u8>, Vec<u8>>(&self.keys)
            .append_list::<Vec<u8>, Vec<u8>>(&self.values);
    }
}

impl Decodable for Chunk {
    fn decode(rlp: &Rlp) -> Result<Self, DecoderError> {
        Ok(Chunk {
            keys: rlp.list_at(0)?,
            values: rlp.list_at(1)?,
        })
    }
}

impl Chunk {
    /// Validate the chunk with specified key.
    pub fn validate(&self, key: &ChunkKey) -> Result<(), Error> {
        // chunk should not be empty
        if self.keys.is_empty() {
            // TODO: Now this may happen if the requested peer has opened
            // maximal number of snapshots and cannot give a
            // response temporarily, we should differentiate this
            // from dishonest behaviors.
            return Err(Error::EmptySnapshotChunk.into());
        }
        if self.keys.len() != self.values.len() {
            return Err(Error::InvalidSnapshotChunk(
                "keys and values do not match".into(),
            )
            .into());
        }
        // the key of first item in chunk should match with the requested key
        if let Some(ref start_key) = key.lower_bound_incl {
            if start_key != &self.keys[0] {
                return Err(
                    Error::InvalidSnapshotChunk("key mismatch".into()).into()
                );
            }
        }

        Ok(())
    }

    pub fn load(
        snapshot_epoch_id: &H256, chunk_key: &ChunkKey,
        storage_manager: &StorageManager, max_chunk_size: u64,
    ) -> Result<Option<Chunk>, Error> {
        debug!(
            "begin to load chunk, snapshot_epoch_id = {:?}, key = {:?}",
            snapshot_epoch_id, chunk_key
        );

        let snapshot_db_manager =
            storage_manager.get_storage_manager().get_snapshot_manager();

        let snapshot_db = match snapshot_db_manager.get_snapshot_by_epoch_id(
            snapshot_epoch_id,
            /* try_open = */ true,
            false,
        )? {
            Some(db) => db,
            None => {
                debug!("failed to load chunk, cannot find snapshot by checkpoint {:?}",
                       snapshot_epoch_id);
                return Ok(None);
            }
        };

        let mut kv_iterator = snapshot_db.snapshot_kv_iterator()?.take();
        let lower_bound_incl =
            chunk_key.lower_bound_incl.clone().unwrap_or_default();
        let upper_bound_excl =
            chunk_key.upper_bound_excl.as_ref().map(|k| k.as_slice());
        let mut kvs = kv_iterator
            .iter_range(lower_bound_incl.as_slice(), upper_bound_excl)?
            .take();

        let mut keys = Vec::new();
        let mut values = Vec::new();
        let mut chunk_size = 0;
        while let Some((key, value)) = kvs.next()? {
            chunk_size += rlp_key_value_len(key.len() as u16, value.len());
            if chunk_size > max_chunk_size {
                let msg =
                    format!("Exceed max allowed chunk size {}", max_chunk_size);
                error!("{}", msg);
                return Err(Error::InvalidSnapshotChunk(msg).into());
            }

            keys.push(key);
            values.push(value.into());
        }

        debug!(
            "complete to load chunk, items = {}, chunk_key = {:?}",
            keys.len(),
            chunk_key
        );

        Ok(Some(Chunk { keys, values }))
    }
}

// todo add necessary unit tests when code is stable