|
| 1 | +// Copyright 2018 Kodebox, Inc. |
| 2 | +// This file is part of CodeChain. |
| 3 | +// |
| 4 | +// This program is free software: you can redistribute it and/or modify |
| 5 | +// it under the terms of the GNU Affero General Public License as |
| 6 | +// published by the Free Software Foundation, either version 3 of the |
| 7 | +// License, or (at your option) any later version. |
| 8 | +// |
| 9 | +// This program is distributed in the hope that it will be useful, |
| 10 | +// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 | +// GNU Affero General Public License for more details. |
| 13 | +// |
| 14 | +// You should have received a copy of the GNU Affero General Public License |
| 15 | +// along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 16 | + |
| 17 | +use std::fs::create_dir_all; |
| 18 | +use std::path::PathBuf; |
| 19 | +use std::sync::Arc; |
| 20 | +use std::thread::spawn; |
| 21 | + |
| 22 | +use ccore::{BlockChainClient, BlockId, ChainNotify}; |
| 23 | +use ctypes::H256; |
| 24 | + |
| 25 | +pub struct Service { |
| 26 | + client: Arc<BlockChainClient>, |
| 27 | + /// Snapshot root directory |
| 28 | + root_dir: String, |
| 29 | + /// Snapshot creation period in unit of block numbers |
| 30 | + period: u64, |
| 31 | +} |
| 32 | + |
| 33 | +impl Service { |
| 34 | + pub fn new(client: Arc<BlockChainClient>, root_dir: String, period: u64) -> Arc<Self> { |
| 35 | + Arc::new(Self { |
| 36 | + client, |
| 37 | + root_dir, |
| 38 | + period, |
| 39 | + }) |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +impl ChainNotify for Service { |
| 44 | + /// fires when chain has new blocks. |
| 45 | + fn new_blocks( |
| 46 | + &self, |
| 47 | + _imported: Vec<H256>, |
| 48 | + _invalid: Vec<H256>, |
| 49 | + enacted: Vec<H256>, |
| 50 | + _retracted: Vec<H256>, |
| 51 | + _sealed: Vec<H256>, |
| 52 | + _duration: u64, |
| 53 | + ) { |
| 54 | + let best_number = self.client.chain_info().best_block_number; |
| 55 | + let is_checkpoint = enacted |
| 56 | + .iter() |
| 57 | + .map(|hash| self.client.block_number(BlockId::Hash(*hash)).expect("Enacted block must exist")) |
| 58 | + .any(|number| number % self.period == 0); |
| 59 | + if is_checkpoint && best_number > self.period { |
| 60 | + let root_dir = self.root_dir.clone(); |
| 61 | + let period = self.period; |
| 62 | + spawn(move || { |
| 63 | + let target = (best_number / period - 1) * period; |
| 64 | + let path: PathBuf = [root_dir, target.to_string()].iter().collect(); |
| 65 | + if let Ok(_) = create_dir_all(path) { |
| 66 | + // FIXME: implement this |
| 67 | + // unimplemented!() |
| 68 | + } |
| 69 | + }); |
| 70 | + } |
| 71 | + } |
| 72 | +} |
0 commit comments