// Copyright 2015-2019 Parity Technologies (UK) Ltd.
// This file is part of Parity Ethereum.
// Parity Ethereum is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity Ethereum is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity Ethereum. If not, see .
//! Snapshot network service implementation.
use std::collections::HashSet;
use std::io::{self, Read, ErrorKind};
use std::fs::{self, File};
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::cmp;
use blockchain::{BlockChain, BlockChainDB, BlockChainDBHandler};
use bytes::Bytes;
use common_types::{
io_message::ClientIoMessage,
errors::{EthcoreError as Error, SnapshotError, SnapshotError::UnlinkedAncientBlockChain},
ids::BlockId,
snapshot::{ManifestData, Progress, RestorationStatus},
};
use client_traits::ChainInfo;
use engine::Engine;
use ethereum_types::H256;
use ethcore_io::IoChannel;
use journaldb::Algorithm;
use keccak_hash::keccak;
use kvdb::DBTransaction;
use log::{debug, error, info, trace, warn};
use parking_lot::{Mutex, RwLock, RwLockReadGuard};
use snappy;
use trie_db::TrieError;
use crate::{SnapshotClient, SnapshotWriter};
use super::{
StateRebuilder,
SnapshotService,
Rebuilder,
MAX_CHUNK_SIZE,
io::{SnapshotReader, LooseReader, LooseWriter},
chunker,
};
/// Helper for removing directories in case of error.
pub struct Guard(bool, PathBuf);
impl Guard {
fn new(path: PathBuf) -> Self { Guard(true, path) }
#[cfg(any(test, feature = "test-helpers"))]
pub fn benign() -> Self { Guard(false, PathBuf::default()) }
fn disarm(mut self) { self.0 = false }
}
impl Drop for Guard {
fn drop(&mut self) {
if self.0 {
let _ = fs::remove_dir_all(&self.1);
}
}
}
/// State restoration manager.
pub struct Restoration {
manifest: ManifestData,
state_chunks_left: HashSet,
block_chunks_left: HashSet,
state: StateRebuilder,
secondary: Box,
writer: Option,
snappy_buffer: Bytes,
final_state_root: H256,
guard: Guard,
db: Arc,
}
/// Params to initialise restoration
pub struct RestorationParams<'a> {
manifest: ManifestData, // manifest to base restoration on.
pruning: Algorithm, // pruning algorithm for the database.
db: Arc, // database
writer: Option, // writer for recovered snapshot.
genesis: &'a [u8], // genesis block of the chain.
guard: Guard, // guard for the restoration directory.
engine: &'a dyn Engine,
}
#[cfg(any(test, feature = "test-helpers"))]
impl<'a> RestorationParams<'a> {
pub fn new(
manifest: ManifestData,
pruning: Algorithm,
db: Arc,
writer: Option,
genesis: &'a [u8],
guard: Guard,
engine: &'a dyn Engine,
) -> Self {
Self { manifest, pruning, db, writer, genesis, guard, engine }
}
}
impl Restoration {
/// Build a Restoration using the given parameters.
pub fn new(params: RestorationParams) -> Result {
let manifest = params.manifest;
let state_chunks = manifest.state_hashes.iter().cloned().collect();
let block_chunks = manifest.block_hashes.iter().cloned().collect();
let raw_db = params.db;
let chain = BlockChain::new(Default::default(), params.genesis, raw_db.clone());
let chunker = chunker(params.engine.snapshot_mode())
.ok_or_else(|| Error::Snapshot(SnapshotError::SnapshotsUnsupported))?;
let secondary = chunker.rebuilder(chain, raw_db.clone(), &manifest)?;
let final_state_root = manifest.state_root.clone();
Ok(Restoration {
manifest,
state_chunks_left: state_chunks,
block_chunks_left: block_chunks,
state: StateRebuilder::new(raw_db.key_value().clone(), params.pruning),
secondary,
writer: params.writer,
snappy_buffer: Vec::new(),
final_state_root,
guard: params.guard,
db: raw_db,
})
}
/// Feeds a chunk of state data to the Restoration. Aborts early if `flag` becomes false.
pub fn feed_state(&mut self, hash: H256, chunk: &[u8], flag: &AtomicBool) -> Result<(), Error> {
if self.state_chunks_left.contains(&hash) {
let expected_len = snappy::decompressed_len(chunk)?;
if expected_len > MAX_CHUNK_SIZE {
trace!(target: "snapshot", "Discarding large chunk: {} vs {}", expected_len, MAX_CHUNK_SIZE);
return Err(SnapshotError::ChunkTooLarge.into());
}
let len = snappy::decompress_into(chunk, &mut self.snappy_buffer)?;
self.state.feed(&self.snappy_buffer[..len], flag)?;
if let Some(ref mut writer) = self.writer.as_mut() {
writer.write_state_chunk(hash, chunk)?;
}
self.state_chunks_left.remove(&hash);
}
Ok(())
}
/// Feeds a chunk of block data to the `Restoration`. Aborts early if `flag` becomes false.
pub fn feed_blocks(&mut self, hash: H256, chunk: &[u8], engine: &dyn Engine, flag: &AtomicBool) -> Result<(), Error> {
if self.block_chunks_left.contains(&hash) {
let expected_len = snappy::decompressed_len(chunk)?;
if expected_len > MAX_CHUNK_SIZE {
trace!(target: "snapshot", "Discarding large chunk: {} vs {}", expected_len, MAX_CHUNK_SIZE);
return Err(SnapshotError::ChunkTooLarge.into());
}
let len = snappy::decompress_into(chunk, &mut self.snappy_buffer)?;
self.secondary.feed(&self.snappy_buffer[..len], engine, flag)?;
if let Some(ref mut writer) = self.writer.as_mut() {
writer.write_block_chunk(hash, chunk)?;
}
self.block_chunks_left.remove(&hash);
}
Ok(())
}
// finish up restoration.
fn finalize(mut self) -> Result<(), Error> {
if !self.is_done() { return Ok(()) }
// verify final state root.
let root = self.state.state_root();
if root != self.final_state_root {
warn!("Final restored state has wrong state root: expected {:?}, got {:?}", self.final_state_root, root);
return Err(TrieError::InvalidStateRoot(root).into());
}
// check for missing code.
self.state.finalize(self.manifest.block_number, self.manifest.block_hash)?;
// connect out-of-order chunks and verify chain integrity.
self.secondary.finalize()?;
if let Some(writer) = self.writer {
writer.finish(self.manifest)?;
}
self.guard.disarm();
trace!(target: "snapshot", "Restoration finalised correctly");
Ok(())
}
/// Check if we're done restoring: no more block chunks and no more state chunks to process.
pub fn is_done(&self) -> bool {
self.block_chunks_left.is_empty() && self.state_chunks_left.is_empty()
}
}
/// Type alias for client io channel.
pub type Channel = IoChannel>;
/// Snapshot service parameters.
pub struct ServiceParams {
/// The consensus engine this is built on.
pub engine: Arc,
/// The chain's genesis block.
pub genesis_block: Bytes,
/// State pruning algorithm.
pub pruning: Algorithm,
/// Handler for opening a restoration DB.
pub restoration_db_handler: Box,
/// Async IO channel for sending messages.
pub channel: Channel,
/// The directory to put snapshots in.
/// Usually "/snapshot"
pub snapshot_root: PathBuf,
/// A handle for database restoration.
pub client: Arc,
}
/// `SnapshotService` implementation.
/// This controls taking snapshots and restoring from them.
pub struct Service {
restoration: Mutex