openethereum/src/sync/chain.rs

970 lines
32 KiB
Rust
Raw Normal View History

2016-01-09 18:40:13 +01:00
///
/// BlockChain synchronization strategy.
/// Syncs to peers and keeps up to date.
/// This implementation uses ethereum protocol v63
///
/// Syncing strategy.
///
/// 1. A peer arrives with a total difficulty better than ours
/// 2. Find a common best block between our an peer chain.
/// Start with out best block and request headers from peer backwards until a common block is found
/// 3. Download headers and block bodies from peers in parallel.
/// As soon as a set of the blocks is fully downloaded at the head of the queue it is fed to the blockchain
/// 4. Maintain sync by handling NewBlocks/NewHashes messages
///
2016-01-10 14:11:23 +01:00
use util::*;
2015-12-22 22:19:50 +01:00
use std::mem::{replace};
2015-12-28 12:03:05 +01:00
use views::{HeaderView};
use header::{BlockNumber, Header as BlockHeader};
use client::{BlockChainClient, BlockStatus};
2015-12-25 14:55:55 +01:00
use sync::range_collection::{RangeCollection, ToUsize, FromUsize};
2016-01-10 23:37:09 +01:00
use error::*;
2016-01-09 18:40:13 +01:00
use sync::io::SyncIo;
2015-12-22 22:19:50 +01:00
2015-12-25 14:55:55 +01:00
impl ToUsize for BlockNumber {
fn to_usize(&self) -> usize {
*self as usize
}
}
impl FromUsize for BlockNumber {
fn from_usize(s: usize) -> BlockNumber {
s as BlockNumber
}
}
2016-01-08 17:52:25 +01:00
type PacketDecodeError = DecoderError;
2015-12-24 17:18:47 +01:00
const PROTOCOL_VERSION: u8 = 63u8;
const MAX_BODIES_TO_SEND: usize = 256;
2015-12-27 00:48:03 +01:00
const MAX_HEADERS_TO_SEND: usize = 512;
2015-12-24 17:18:47 +01:00
const MAX_NODE_DATA_TO_SEND: usize = 1024;
const MAX_RECEIPTS_TO_SEND: usize = 1024;
2015-12-27 00:48:03 +01:00
const MAX_HEADERS_TO_REQUEST: usize = 512;
2015-12-25 14:55:55 +01:00
const MAX_BODIES_TO_REQUEST: usize = 256;
2015-12-24 17:18:47 +01:00
2015-12-22 22:19:50 +01:00
const STATUS_PACKET: u8 = 0x00;
const NEW_BLOCK_HASHES_PACKET: u8 = 0x01;
const TRANSACTIONS_PACKET: u8 = 0x02;
const GET_BLOCK_HEADERS_PACKET: u8 = 0x03;
const BLOCK_HEADERS_PACKET: u8 = 0x04;
const GET_BLOCK_BODIES_PACKET: u8 = 0x05;
const BLOCK_BODIES_PACKET: u8 = 0x06;
const NEW_BLOCK_PACKET: u8 = 0x07;
const GET_NODE_DATA_PACKET: u8 = 0x0d;
const NODE_DATA_PACKET: u8 = 0x0e;
const GET_RECEIPTS_PACKET: u8 = 0x0f;
const RECEIPTS_PACKET: u8 = 0x10;
2016-01-10 14:11:23 +01:00
const NETWORK_ID: U256 = ONE_U256; //TODO: get this from parent
2015-12-22 22:19:50 +01:00
struct Header {
2016-01-09 18:40:13 +01:00
/// Header data
2015-12-22 22:19:50 +01:00
data: Bytes,
/// Block hash
hash: H256,
/// Parent hash
parent: H256,
}
/// Used to identify header by transactions and uncles hashes
#[derive(Eq, PartialEq, Hash)]
struct HeaderId {
transactions_root: H256,
uncles: H256
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
2016-01-10 23:37:09 +01:00
/// Sync state
2015-12-22 22:19:50 +01:00
pub enum SyncState {
/// Initial chain sync has not started yet
NotSynced,
/// Initial chain sync complete. Waiting for new packets
Idle,
2016-01-10 23:37:09 +01:00
/// Block downloading paused. Waiting for block queue to process blocks and free some space
2015-12-22 22:19:50 +01:00
Waiting,
/// Downloading blocks
Blocks,
/// Downloading blocks learned from NewHashes packet
NewBlocks,
}
2016-01-09 18:40:13 +01:00
/// Syncing status and statistics
2015-12-22 22:19:50 +01:00
pub struct SyncStatus {
2016-01-09 18:40:13 +01:00
/// State
2015-12-25 14:55:55 +01:00
pub state: SyncState,
2016-01-09 18:40:13 +01:00
/// Syncing protocol version. That's the maximum protocol version we connect to.
2015-12-25 14:55:55 +01:00
pub protocol_version: u8,
2016-01-09 18:40:13 +01:00
/// BlockChain height for the moment the sync started.
2015-12-25 14:55:55 +01:00
pub start_block_number: BlockNumber,
2016-01-09 18:40:13 +01:00
/// Last fully downloaded and imported block number.
2016-01-08 16:26:00 +01:00
pub last_imported_block_number: BlockNumber,
2016-01-09 18:40:13 +01:00
/// Highest block number in the download queue.
2015-12-25 14:55:55 +01:00
pub highest_block_number: BlockNumber,
2016-01-09 18:40:13 +01:00
/// Total number of blocks for the sync process.
2015-12-25 14:55:55 +01:00
pub blocks_total: usize,
2016-01-09 18:40:13 +01:00
/// Number of blocks downloaded so far.
2016-01-08 16:26:00 +01:00
pub blocks_received: usize,
2016-01-22 04:54:38 +01:00
/// Total number of connected peers
pub num_peers: usize,
/// Total number of active peers
pub num_active_peers: usize,
2015-12-22 22:19:50 +01:00
}
#[derive(PartialEq, Eq, Debug)]
2016-01-10 23:37:09 +01:00
/// Peer data type requested
2016-01-08 16:26:00 +01:00
enum PeerAsking {
2015-12-22 22:19:50 +01:00
Nothing,
BlockHeaders,
BlockBodies,
}
2016-01-10 23:37:09 +01:00
/// Syncing peer information
2015-12-22 22:19:50 +01:00
struct PeerInfo {
2016-01-10 23:37:09 +01:00
/// eth protocol version
2015-12-22 22:19:50 +01:00
protocol_version: u32,
2016-01-10 23:37:09 +01:00
/// Peer chain genesis hash
2015-12-22 22:19:50 +01:00
genesis: H256,
2016-01-10 23:37:09 +01:00
/// Peer network id
2015-12-22 22:19:50 +01:00
network_id: U256,
2016-01-10 23:37:09 +01:00
/// Peer best block hash
2015-12-22 22:19:50 +01:00
latest: H256,
2016-01-10 23:37:09 +01:00
/// Peer total difficulty
2015-12-22 22:19:50 +01:00
difficulty: U256,
2016-01-10 23:37:09 +01:00
/// Type of data currenty being requested from peer.
2015-12-22 22:19:50 +01:00
asking: PeerAsking,
2016-01-10 23:37:09 +01:00
/// A set of block numbers being requested
2016-01-08 16:26:00 +01:00
asking_blocks: Vec<BlockNumber>,
2015-12-22 22:19:50 +01:00
}
2016-01-10 23:37:09 +01:00
/// Blockchain sync handler.
/// See module documentation for more details.
2015-12-22 22:19:50 +01:00
pub struct ChainSync {
/// Sync state
state: SyncState,
/// Last block number for the start of sync
starting_block: BlockNumber,
/// Highest block number seen
highest_block: BlockNumber,
/// Set of block header numbers being downloaded
downloading_headers: HashSet<BlockNumber>,
/// Set of block body numbers being downloaded
downloading_bodies: HashSet<BlockNumber>,
/// Downloaded headers.
2016-01-08 16:26:00 +01:00
headers: Vec<(BlockNumber, Vec<Header>)>, //TODO: use BTreeMap once range API is sable. For now it is a vector sorted in descending order
2015-12-22 22:19:50 +01:00
/// Downloaded bodies
2016-01-10 23:37:09 +01:00
bodies: Vec<(BlockNumber, Vec<Bytes>)>, //TODO: use BTreeMap once range API is sable. For now it is a vector sorted in descending order
2015-12-22 22:19:50 +01:00
/// Peer info
peers: HashMap<PeerId, PeerInfo>,
/// Used to map body to header
header_ids: HashMap<HeaderId, BlockNumber>,
/// Last impoted block number
last_imported_block: BlockNumber,
2015-12-27 00:48:03 +01:00
/// Last impoted block hash
last_imported_hash: H256,
2015-12-22 22:19:50 +01:00
/// Syncing total difficulty
syncing_difficulty: U256,
/// True if common block for our and remote chain has been found
have_common_block: bool,
}
impl ChainSync {
2016-01-09 19:13:58 +01:00
/// Create a new instance of syncing strategy.
2015-12-25 14:55:55 +01:00
pub fn new() -> ChainSync {
ChainSync {
2015-12-22 22:19:50 +01:00
state: SyncState::NotSynced,
starting_block: 0,
highest_block: 0,
downloading_headers: HashSet::new(),
downloading_bodies: HashSet::new(),
headers: Vec::new(),
bodies: Vec::new(),
peers: HashMap::new(),
header_ids: HashMap::new(),
last_imported_block: 0,
2015-12-27 00:48:03 +01:00
last_imported_hash: H256::new(),
2015-12-22 22:19:50 +01:00
syncing_difficulty: U256::from(0u64),
2016-01-08 16:26:00 +01:00
have_common_block: false,
2015-12-25 14:55:55 +01:00
}
2015-12-22 22:19:50 +01:00
}
/// @returns Synchonization status
pub fn status(&self) -> SyncStatus {
SyncStatus {
state: self.state.clone(),
protocol_version: 63,
start_block_number: self.starting_block,
2016-01-08 16:26:00 +01:00
last_imported_block_number: self.last_imported_block,
2015-12-22 22:19:50 +01:00
highest_block_number: self.highest_block,
2016-01-22 04:54:38 +01:00
blocks_received: (self.last_imported_block - self.starting_block) as usize,
blocks_total: (self.highest_block - self.starting_block) as usize,
num_peers: self.peers.len(),
num_active_peers: self.peers.values().filter(|p| p.asking != PeerAsking::Nothing).count(),
2015-12-22 22:19:50 +01:00
}
}
/// Abort all sync activity
pub fn abort(&mut self, io: &mut SyncIo) {
self.restart(io);
self.peers.clear();
}
2016-01-09 18:40:13 +01:00
/// Rest sync. Clear all downloaded data but keep the queue
2015-12-22 22:19:50 +01:00
fn reset(&mut self) {
self.downloading_headers.clear();
self.downloading_bodies.clear();
self.headers.clear();
self.bodies.clear();
2016-01-17 15:56:09 +01:00
for (_, ref mut p) in &mut self.peers {
2015-12-22 22:19:50 +01:00
p.asking_blocks.clear();
}
self.header_ids.clear();
self.syncing_difficulty = From::from(0u64);
self.state = SyncState::Idle;
}
/// Restart sync
pub fn restart(&mut self, io: &mut SyncIo) {
self.reset();
self.last_imported_block = 0;
2015-12-27 00:48:03 +01:00
self.last_imported_hash = H256::new();
2015-12-22 22:19:50 +01:00
self.starting_block = 0;
self.highest_block = 0;
self.have_common_block = false;
2015-12-26 15:47:07 +01:00
io.chain().clear_queue();
2016-01-07 20:43:37 +01:00
self.starting_block = io.chain().chain_info().best_block_number;
2015-12-22 22:19:50 +01:00
self.state = SyncState::NotSynced;
}
/// Called by peer to report status
2016-01-14 19:03:48 +01:00
fn on_peer_status(&mut self, io: &mut SyncIo, peer_id: PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
2015-12-22 22:19:50 +01:00
let peer = PeerInfo {
2016-01-08 17:52:25 +01:00
protocol_version: try!(r.val_at(0)),
network_id: try!(r.val_at(1)),
difficulty: try!(r.val_at(2)),
latest: try!(r.val_at(3)),
genesis: try!(r.val_at(4)),
2015-12-22 22:19:50 +01:00
asking: PeerAsking::Nothing,
asking_blocks: Vec::new(),
};
2015-12-25 14:55:55 +01:00
2016-01-10 14:11:23 +01:00
trace!(target: "sync", "New peer {} (protocol: {}, network: {:?}, difficulty: {:?}, latest:{}, genesis:{})", peer_id, peer.protocol_version, peer.network_id, peer.difficulty, peer.latest, peer.genesis);
let chain_info = io.chain().chain_info();
if peer.genesis != chain_info.genesis_hash {
io.disable_peer(peer_id);
trace!(target: "sync", "Peer {} genesis hash not matched", peer_id);
return Ok(());
}
if peer.network_id != NETWORK_ID {
io.disable_peer(peer_id);
trace!(target: "sync", "Peer {} network id not matched", peer_id);
return Ok(());
}
2015-12-25 14:55:55 +01:00
2015-12-22 22:19:50 +01:00
let old = self.peers.insert(peer_id.clone(), peer);
if old.is_some() {
panic!("ChainSync: new peer already exists");
}
2016-01-14 19:03:48 +01:00
info!(target: "sync", "Connected {}:{}", peer_id, io.peer_info(peer_id));
2015-12-22 22:19:50 +01:00
self.sync_peer(io, peer_id, false);
2016-01-08 17:52:25 +01:00
Ok(())
2015-12-22 22:19:50 +01:00
}
2016-01-19 11:10:38 +01:00
#[allow(cyclomatic_complexity)]
2015-12-22 22:19:50 +01:00
/// Called by peer once it has new block headers during sync
2016-01-14 19:03:48 +01:00
fn on_peer_block_headers(&mut self, io: &mut SyncIo, peer_id: PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
2015-12-27 00:48:03 +01:00
self.reset_peer_asking(peer_id, PeerAsking::BlockHeaders);
2015-12-22 22:19:50 +01:00
let item_count = r.item_count();
2016-01-08 16:26:00 +01:00
trace!(target: "sync", "{} -> BlockHeaders ({} entries)", peer_id, item_count);
2015-12-22 22:19:50 +01:00
self.clear_peer_download(peer_id);
if self.state != SyncState::Blocks && self.state != SyncState::NewBlocks && self.state != SyncState::Waiting {
trace!(target: "sync", "Ignored unexpected block headers");
2016-01-08 17:52:25 +01:00
return Ok(());
2015-12-22 22:19:50 +01:00
}
2016-01-08 16:26:00 +01:00
if self.state == SyncState::Waiting {
2015-12-22 22:19:50 +01:00
trace!(target: "sync", "Ignored block headers while waiting");
2016-01-08 17:52:25 +01:00
return Ok(());
2015-12-22 22:19:50 +01:00
}
2015-12-24 17:18:47 +01:00
for i in 0..item_count {
2016-01-08 17:52:25 +01:00
let info: BlockHeader = try!(r.val_at(i));
let number = BlockNumber::from(info.number);
2015-12-24 17:18:47 +01:00
if number <= self.last_imported_block || self.headers.have_item(&number) {
trace!(target: "sync", "Skipping existing block header");
continue;
}
if number > self.highest_block {
self.highest_block = number;
}
2016-01-08 17:52:25 +01:00
let hash = info.hash();
2015-12-28 12:03:05 +01:00
match io.chain().block_status(&hash) {
2015-12-24 17:18:47 +01:00
BlockStatus::InChain => {
self.have_common_block = true;
self.last_imported_block = number;
2016-01-04 13:25:32 +01:00
self.last_imported_hash = hash.clone();
2015-12-28 12:03:05 +01:00
trace!(target: "sync", "Found common header {} ({})", number, hash);
2015-12-24 17:18:47 +01:00
},
_ => {
if self.have_common_block {
//validate chain
2016-01-08 17:52:25 +01:00
if self.have_common_block && number == self.last_imported_block + 1 && info.parent_hash != self.last_imported_hash {
2015-12-27 02:27:15 +01:00
// TODO: lower peer rating
2015-12-28 12:03:05 +01:00
debug!(target: "sync", "Mismatched block header {} {}", number, hash);
2015-12-27 00:48:03 +01:00
continue;
}
2016-01-08 17:52:25 +01:00
if self.headers.find_item(&(number - 1)).map_or(false, |p| p.hash != info.parent_hash) {
2015-12-24 17:18:47 +01:00
// mismatching parent id, delete the previous block and don't add this one
// TODO: lower peer rating
2015-12-28 12:03:05 +01:00
debug!(target: "sync", "Mismatched block header {} {}", number, hash);
2015-12-24 17:18:47 +01:00
self.remove_downloaded_blocks(number - 1);
continue;
}
2015-12-28 12:03:05 +01:00
if self.headers.find_item(&(number + 1)).map_or(false, |p| p.parent != hash) {
2015-12-24 17:18:47 +01:00
// mismatching parent id for the next block, clear following headers
debug!(target: "sync", "Mismatched block header {}", number + 1);
self.remove_downloaded_blocks(number + 1);
}
}
let hdr = Header {
2016-01-08 17:52:25 +01:00
data: try!(r.at(i)).as_raw().to_vec(),
2016-01-04 13:25:32 +01:00
hash: hash.clone(),
2016-01-08 17:52:25 +01:00
parent: info.parent_hash,
2015-12-24 17:18:47 +01:00
};
self.headers.insert_item(number, hdr);
let header_id = HeaderId {
2016-01-08 17:52:25 +01:00
transactions_root: info.transactions_root,
uncles: info.uncles_hash
2015-12-24 17:18:47 +01:00
};
2015-12-28 12:03:05 +01:00
trace!(target: "sync", "Got header {} ({})", number, hash);
2015-12-24 17:18:47 +01:00
if header_id.transactions_root == rlp::SHA3_NULL_RLP && header_id.uncles == rlp::SHA3_EMPTY_LIST_RLP {
//empty body, just mark as downloaded
let mut body_stream = RlpStream::new_list(2);
2015-12-26 15:47:07 +01:00
body_stream.append_raw(&rlp::NULL_RLP, 1);
2015-12-27 00:48:03 +01:00
body_stream.append_raw(&rlp::EMPTY_LIST_RLP, 1);
2015-12-24 17:18:47 +01:00
self.bodies.insert_item(number, body_stream.out());
}
else {
self.header_ids.insert(header_id, number);
}
}
}
}
2015-12-27 00:48:03 +01:00
self.collect_blocks(io);
self.continue_sync(io);
2016-01-08 17:52:25 +01:00
Ok(())
2015-12-22 22:19:50 +01:00
}
/// Called by peer once it has new block bodies
2016-01-14 19:03:48 +01:00
fn on_peer_block_bodies(&mut self, io: &mut SyncIo, peer_id: PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
2016-01-08 17:52:25 +01:00
use util::triehash::ordered_trie_root;
2015-12-27 00:48:03 +01:00
self.reset_peer_asking(peer_id, PeerAsking::BlockBodies);
2015-12-24 17:18:47 +01:00
let item_count = r.item_count();
2016-01-08 16:26:00 +01:00
trace!(target: "sync", "{} -> BlockBodies ({} entries)", peer_id, item_count);
2015-12-24 17:18:47 +01:00
self.clear_peer_download(peer_id);
if self.state != SyncState::Blocks && self.state != SyncState::NewBlocks && self.state != SyncState::Waiting {
trace!(target: "sync", "Ignored unexpected block bodies");
2016-01-08 17:52:25 +01:00
return Ok(());
2015-12-24 17:18:47 +01:00
}
if self.state == SyncState::Waiting {
trace!(target: "sync", "Ignored block bodies while waiting");
2016-01-08 17:52:25 +01:00
return Ok(());
2015-12-24 17:18:47 +01:00
}
for i in 0..item_count {
2016-01-08 17:52:25 +01:00
let body = try!(r.at(i));
let tx = try!(body.at(0));
let tx_root = ordered_trie_root(tx.iter().map(|r| r.as_raw().to_vec()).collect()); //TODO: get rid of vectors here
let uncles = try!(body.at(1)).as_raw().sha3();
2015-12-24 17:18:47 +01:00
let header_id = HeaderId {
transactions_root: tx_root,
uncles: uncles
};
2016-01-17 15:56:09 +01:00
match self.header_ids.get(&header_id).cloned() {
2015-12-24 17:18:47 +01:00
Some(n) => {
self.header_ids.remove(&header_id);
2016-01-08 16:00:32 +01:00
self.bodies.insert_item(n, body.as_raw().to_vec());
2015-12-27 00:48:03 +01:00
trace!(target: "sync", "Got body {}", n);
2015-12-24 17:18:47 +01:00
}
None => {
debug!(target: "sync", "Ignored unknown block body");
}
}
}
self.collect_blocks(io);
self.continue_sync(io);
2016-01-08 17:52:25 +01:00
Ok(())
2015-12-22 22:19:50 +01:00
}
/// Called by peer once it has new block bodies
2016-01-14 19:03:48 +01:00
fn on_peer_new_block(&mut self, io: &mut SyncIo, peer_id: PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
2016-01-08 17:52:25 +01:00
let block_rlp = try!(r.at(0));
let header_rlp = try!(block_rlp.at(0));
2016-01-08 16:00:32 +01:00
let h = header_rlp.as_raw().sha3();
2015-12-24 17:18:47 +01:00
2016-01-08 16:26:00 +01:00
trace!(target: "sync", "{} -> NewBlock ({})", peer_id, h);
2016-01-10 15:08:57 +01:00
let header_view = HeaderView::new(header_rlp.as_raw());
// TODO: Decompose block and add to self.headers and self.bodies instead
if header_view.number() == From::from(self.last_imported_block + 1) {
2016-01-17 23:07:58 +01:00
match io.chain().import_block(block_rlp.as_raw().to_vec()) {
2016-01-10 23:37:09 +01:00
Err(ImportError::AlreadyInChain) => {
2016-01-10 15:08:57 +01:00
trace!(target: "sync", "New block already in chain {:?}", h);
},
2016-01-10 23:37:09 +01:00
Err(ImportError::AlreadyQueued) => {
2016-01-10 15:08:57 +01:00
trace!(target: "sync", "New block already queued {:?}", h);
},
Ok(_) => {
2016-01-10 15:08:57 +01:00
trace!(target: "sync", "New block queued {:?}", h);
},
2016-01-10 23:37:09 +01:00
Err(e) => {
debug!(target: "sync", "Bad new block {:?} : {:?}", h, e);
2016-01-10 15:08:57 +01:00
io.disable_peer(peer_id);
2015-12-24 17:18:47 +01:00
}
2016-01-10 15:08:57 +01:00
};
}
2016-01-10 23:37:09 +01:00
else {
trace!(target: "sync", "New block unknown {:?}", h);
//TODO: handle too many unknown blocks
let difficulty: U256 = try!(r.val_at(1));
let peer_difficulty = self.peers.get_mut(&peer_id).expect("ChainSync: unknown peer").difficulty;
if difficulty > peer_difficulty {
trace!(target: "sync", "Received block {:?} with no known parent. Peer needs syncing...", h);
2016-01-21 16:48:37 +01:00
{
let peer = self.peers.get_mut(&peer_id).expect("ChainSync: unknown peer");
peer.latest = header_view.sha3();
}
2016-01-10 23:37:09 +01:00
self.sync_peer(io, peer_id, true);
}
}
2016-01-08 17:52:25 +01:00
Ok(())
2015-12-22 22:19:50 +01:00
}
2016-01-09 18:40:13 +01:00
/// Handles NewHashes packet. Initiates headers download for any unknown hashes.
2016-01-14 19:03:48 +01:00
fn on_peer_new_hashes(&mut self, io: &mut SyncIo, peer_id: PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
2015-12-24 17:18:47 +01:00
if self.peers.get_mut(&peer_id).expect("ChainSync: unknown peer").asking != PeerAsking::Nothing {
trace!(target: "sync", "Ignoring new hashes since we're already downloading.");
2016-01-08 17:52:25 +01:00
return Ok(());
2015-12-24 17:18:47 +01:00
}
2016-01-08 16:26:00 +01:00
trace!(target: "sync", "{} -> NewHashes ({} entries)", peer_id, r.item_count());
2015-12-24 17:18:47 +01:00
let hashes = r.iter().map(|item| (item.val_at::<H256>(0), item.val_at::<U256>(1)));
let mut max_height: U256 = From::from(0);
2016-01-08 17:52:25 +01:00
for (rh, rd) in hashes {
let h = try!(rh);
let d = try!(rd);
2015-12-26 15:47:07 +01:00
match io.chain().block_status(&h) {
2015-12-24 17:18:47 +01:00
BlockStatus::InChain => {
trace!(target: "sync", "New block hash already in chain {:?}", h);
},
2016-01-10 23:37:09 +01:00
BlockStatus::Queued => {
2015-12-24 17:18:47 +01:00
trace!(target: "sync", "New hash block already queued {:?}", h);
},
BlockStatus::Unknown => {
trace!(target: "sync", "New unknown block hash {:?}", h);
if d > max_height {
let peer = self.peers.get_mut(&peer_id).expect("ChainSync: unknown peer");
peer.latest = h.clone();
max_height = d;
}
},
BlockStatus::Bad =>{
debug!(target: "sync", "Bad new block hash {:?}", h);
io.disable_peer(peer_id);
2016-01-08 17:52:25 +01:00
return Ok(());
2015-12-24 17:18:47 +01:00
}
}
2016-01-08 17:52:25 +01:00
};
2016-01-23 18:44:45 +01:00
if max_height != x!(0) {
self.sync_peer(io, peer_id, true);
}
2016-01-08 17:52:25 +01:00
Ok(())
2015-12-22 22:19:50 +01:00
}
/// Called by peer when it is disconnecting
2016-01-14 19:03:48 +01:00
pub fn on_peer_aborting(&mut self, io: &mut SyncIo, peer: PeerId) {
trace!(target: "sync", "== Disconnecting {}", peer);
2016-01-10 14:11:23 +01:00
if self.peers.contains_key(&peer) {
2016-01-18 14:44:06 +01:00
info!(target: "sync", "Disconnected {}:{}", peer, io.peer_info(peer));
2016-01-10 14:11:23 +01:00
self.clear_peer_download(peer);
2016-01-15 12:26:04 +01:00
self.peers.remove(&peer);
2016-01-10 14:11:23 +01:00
self.continue_sync(io);
}
2015-12-24 17:18:47 +01:00
}
2016-01-09 18:40:13 +01:00
/// Called when a new peer is connected
2016-01-14 19:03:48 +01:00
pub fn on_peer_connected(&mut self, io: &mut SyncIo, peer: PeerId) {
2015-12-27 00:48:03 +01:00
trace!(target: "sync", "== Connected {}", peer);
2015-12-24 17:18:47 +01:00
self.send_status(io, peer);
2015-12-22 22:19:50 +01:00
}
2015-12-27 02:27:15 +01:00
/// Resume downloading
2015-12-24 17:18:47 +01:00
fn continue_sync(&mut self, io: &mut SyncIo) {
2015-12-27 02:27:15 +01:00
let mut peers: Vec<(PeerId, U256)> = self.peers.iter().map(|(k, p)| (*k, p.difficulty)).collect();
peers.sort_by(|&(_, d1), &(_, d2)| d1.cmp(&d2).reverse()); //TODO: sort by rating
for (p, _) in peers {
2016-01-14 19:03:48 +01:00
self.sync_peer(io, p, false);
2015-12-24 17:18:47 +01:00
}
2015-12-22 22:19:50 +01:00
}
/// Called after all blocks have been donloaded
fn complete_sync(&mut self) {
2015-12-27 00:48:03 +01:00
trace!(target: "sync", "Sync complete");
2015-12-24 17:18:47 +01:00
self.reset();
self.state = SyncState::Idle;
2015-12-22 22:19:50 +01:00
}
/// Enter waiting state
fn pause_sync(&mut self) {
2015-12-25 14:55:55 +01:00
trace!(target: "sync", "Block queue full, pausing sync");
2015-12-24 17:18:47 +01:00
self.state = SyncState::Waiting;
2015-12-22 22:19:50 +01:00
}
2016-01-09 18:40:13 +01:00
/// Find something to do for a peer. Called for a new peer or when a peer is done with it's task.
2016-01-14 19:03:48 +01:00
fn sync_peer(&mut self, io: &mut SyncIo, peer_id: PeerId, force: bool) {
2015-12-22 22:19:50 +01:00
let (peer_latest, peer_difficulty) = {
let peer = self.peers.get_mut(&peer_id).expect("ChainSync: unknown peer");
2015-12-27 00:48:03 +01:00
if peer.asking != PeerAsking::Nothing {
2015-12-22 22:19:50 +01:00
return;
}
2015-12-27 00:48:03 +01:00
if self.state == SyncState::Waiting {
2015-12-25 14:55:55 +01:00
trace!(target: "sync", "Waiting for block queue");
2015-12-22 22:19:50 +01:00
return;
}
(peer.latest.clone(), peer.difficulty.clone())
};
2016-01-07 20:43:37 +01:00
let td = io.chain().chain_info().pending_total_difficulty;
2015-12-22 22:19:50 +01:00
let syncing_difficulty = max(self.syncing_difficulty, td);
if force || peer_difficulty > syncing_difficulty {
// start sync
self.syncing_difficulty = peer_difficulty;
if self.state == SyncState::Idle || self.state == SyncState::NotSynced {
self.state = SyncState::Blocks;
}
2015-12-27 00:48:03 +01:00
trace!(target: "sync", "Starting sync with better chain");
2015-12-22 22:19:50 +01:00
self.request_headers_by_hash(io, peer_id, &peer_latest, 1, 0, false);
}
else if self.state == SyncState::Blocks {
self.request_blocks(io, peer_id);
}
}
2016-01-09 18:40:13 +01:00
/// Find some headers or blocks to download for a peer.
2016-01-14 19:03:48 +01:00
fn request_blocks(&mut self, io: &mut SyncIo, peer_id: PeerId) {
2015-12-22 22:19:50 +01:00
self.clear_peer_download(peer_id);
2015-12-25 14:55:55 +01:00
2016-01-22 04:54:38 +01:00
if io.chain().queue_info().full {
2015-12-25 14:55:55 +01:00
self.pause_sync();
return;
}
2015-12-22 22:19:50 +01:00
// check to see if we need to download any block bodies first
let mut needed_bodies: Vec<H256> = Vec::new();
let mut needed_numbers: Vec<BlockNumber> = Vec::new();
2015-12-25 14:55:55 +01:00
if self.have_common_block && !self.headers.is_empty() && self.headers.range_iter().next().unwrap().0 == self.last_imported_block + 1 {
for (start, ref items) in self.headers.range_iter() {
2016-01-08 16:26:00 +01:00
if needed_bodies.len() > MAX_BODIES_TO_REQUEST {
2015-12-25 14:55:55 +01:00
break;
2015-12-22 22:19:50 +01:00
}
2015-12-25 14:55:55 +01:00
let mut index: BlockNumber = 0;
while index != items.len() as BlockNumber && needed_bodies.len() < MAX_BODIES_TO_REQUEST {
let block = start + index;
if !self.downloading_bodies.contains(&block) && !self.bodies.have_item(&block) {
needed_bodies.push(items[index as usize].hash.clone());
needed_numbers.push(block);
self.downloading_bodies.insert(block);
}
index += 1;
2015-12-22 22:19:50 +01:00
}
}
}
if !needed_bodies.is_empty() {
2016-01-14 19:03:48 +01:00
replace(&mut self.peers.get_mut(&peer_id).unwrap().asking_blocks, needed_numbers);
2015-12-22 22:19:50 +01:00
self.request_bodies(io, peer_id, needed_bodies);
}
else {
// check if need to download headers
let mut start = 0usize;
if !self.have_common_block {
// download backwards until common block is found 1 header at a time
2016-01-07 20:43:37 +01:00
let chain_info = io.chain().chain_info();
2016-01-07 16:08:12 +01:00
start = chain_info.best_block_number as usize;
2015-12-22 22:19:50 +01:00
if !self.headers.is_empty() {
2015-12-25 14:55:55 +01:00
start = min(start, self.headers.range_iter().next().unwrap().0 as usize - 1);
2015-12-22 22:19:50 +01:00
}
2015-12-27 00:48:03 +01:00
if start == 0 {
2015-12-22 22:19:50 +01:00
self.have_common_block = true; //reached genesis
2015-12-27 02:27:15 +01:00
self.last_imported_hash = chain_info.genesis_hash;
2015-12-22 22:19:50 +01:00
}
}
if self.have_common_block {
let mut headers: Vec<BlockNumber> = Vec::new();
2015-12-25 14:55:55 +01:00
let mut prev = self.last_imported_block + 1;
2015-12-27 00:48:03 +01:00
for (next, ref items) in self.headers.range_iter() {
if !headers.is_empty() {
2015-12-25 14:55:55 +01:00
break;
}
2015-12-27 00:48:03 +01:00
if next <= prev {
prev = next + items.len() as BlockNumber;
2015-12-25 14:55:55 +01:00
continue;
}
2015-12-27 00:48:03 +01:00
let mut block = prev;
while block < next && headers.len() <= MAX_HEADERS_TO_REQUEST {
2015-12-25 14:55:55 +01:00
if !self.downloading_headers.contains(&(block as BlockNumber)) {
headers.push(block as BlockNumber);
self.downloading_headers.insert(block as BlockNumber);
}
2015-12-27 00:48:03 +01:00
block += 1;
2015-12-22 22:19:50 +01:00
}
2015-12-27 00:48:03 +01:00
prev = next + items.len() as BlockNumber;
2015-12-22 22:19:50 +01:00
}
2015-12-25 14:55:55 +01:00
if !headers.is_empty() {
2015-12-27 00:48:03 +01:00
start = headers[0] as usize;
2015-12-25 14:55:55 +01:00
let count = headers.len();
2016-01-14 19:03:48 +01:00
replace(&mut self.peers.get_mut(&peer_id).unwrap().asking_blocks, headers);
2015-12-22 22:19:50 +01:00
assert!(!self.headers.have_item(&(start as BlockNumber)));
self.request_headers_by_number(io, peer_id, start as BlockNumber, count, 0, false);
}
}
else {
self.request_headers_by_number(io, peer_id, start as BlockNumber, 1, 0, false);
}
}
}
2016-01-09 18:40:13 +01:00
/// Clear all blocks/headers marked as being downloaded by a peer.
2016-01-14 19:03:48 +01:00
fn clear_peer_download(&mut self, peer_id: PeerId) {
2015-12-24 17:18:47 +01:00
let peer = self.peers.get_mut(&peer_id).expect("ChainSync: unknown peer");
for b in &peer.asking_blocks {
self.downloading_headers.remove(&b);
self.downloading_bodies.remove(&b);
}
peer.asking_blocks.clear();
2015-12-22 22:19:50 +01:00
}
2015-12-24 17:18:47 +01:00
2016-01-09 18:40:13 +01:00
/// Checks if there are blocks fully downloaded that can be imported into the blockchain and does the import.
2015-12-24 17:18:47 +01:00
fn collect_blocks(&mut self, io: &mut SyncIo) {
if !self.have_common_block || self.headers.is_empty() || self.bodies.is_empty() {
return;
}
let mut restart = false;
// merge headers and bodies
{
2015-12-25 14:55:55 +01:00
let headers = self.headers.range_iter().next().unwrap();
let bodies = self.bodies.range_iter().next().unwrap();
2015-12-24 17:18:47 +01:00
if headers.0 != bodies.0 || headers.0 != self.last_imported_block + 1 {
return;
}
2015-12-27 00:48:03 +01:00
let count = min(headers.1.len(), bodies.1.len());
let mut imported = 0;
for i in 0..count {
2015-12-24 17:18:47 +01:00
let mut block_rlp = RlpStream::new_list(3);
block_rlp.append_raw(&headers.1[i].data, 1);
2015-12-27 00:48:03 +01:00
let body = Rlp::new(&bodies.1[i]);
2016-01-08 16:00:32 +01:00
block_rlp.append_raw(body.at(0).as_raw(), 1);
block_rlp.append_raw(body.at(1).as_raw(), 1);
2015-12-24 17:18:47 +01:00
let h = &headers.1[i].hash;
2016-01-17 23:07:58 +01:00
match io.chain().import_block(block_rlp.out()) {
2016-01-10 23:37:09 +01:00
Err(ImportError::AlreadyInChain) => {
2015-12-24 17:18:47 +01:00
trace!(target: "sync", "Block already in chain {:?}", h);
self.last_imported_block = headers.0 + i as BlockNumber;
2016-01-04 13:25:32 +01:00
self.last_imported_hash = h.clone();
2015-12-24 17:18:47 +01:00
},
2016-01-10 23:37:09 +01:00
Err(ImportError::AlreadyQueued) => {
2015-12-24 17:18:47 +01:00
trace!(target: "sync", "Block already queued {:?}", h);
self.last_imported_block = headers.0 + i as BlockNumber;
2016-01-04 13:25:32 +01:00
self.last_imported_hash = h.clone();
2015-12-24 17:18:47 +01:00
},
Ok(_) => {
2015-12-24 17:18:47 +01:00
trace!(target: "sync", "Block queued {:?}", h);
self.last_imported_block = headers.0 + i as BlockNumber;
2016-01-04 13:25:32 +01:00
self.last_imported_hash = h.clone();
2015-12-27 00:48:03 +01:00
imported += 1;
2015-12-24 17:18:47 +01:00
},
2016-01-10 23:37:09 +01:00
Err(e) => {
debug!(target: "sync", "Bad block {:?} : {:?}", h, e);
2015-12-24 17:18:47 +01:00
restart = true;
}
}
}
2015-12-27 00:48:03 +01:00
trace!(target: "sync", "Imported {} of {}", imported, count);
2015-12-24 17:18:47 +01:00
}
if restart {
self.restart(io);
return;
}
2015-12-25 14:55:55 +01:00
self.headers.remove_head(&(self.last_imported_block + 1));
self.bodies.remove_head(&(self.last_imported_block + 1));
2015-12-24 17:18:47 +01:00
if self.headers.is_empty() {
assert!(self.bodies.is_empty());
self.complete_sync();
}
2015-12-22 22:19:50 +01:00
}
2015-12-24 17:18:47 +01:00
2016-01-09 18:40:13 +01:00
/// Remove downloaded bocks/headers starting from specified number.
/// Used to recover from an error and re-download parts of the chain detected as bad.
2015-12-24 17:18:47 +01:00
fn remove_downloaded_blocks(&mut self, start: BlockNumber) {
for n in self.headers.get_tail(&start) {
2016-01-17 15:56:09 +01:00
if let Some(ref header_data) = self.headers.find_item(&n) {
let header_to_delete = HeaderView::new(&header_data.data);
let header_id = HeaderId {
transactions_root: header_to_delete.transactions_root(),
uncles: header_to_delete.uncles_hash()
};
self.header_ids.remove(&header_id);
2015-12-24 17:18:47 +01:00
}
self.downloading_bodies.remove(&n);
self.downloading_headers.remove(&n);
}
self.headers.remove_tail(&start);
self.bodies.remove_tail(&start);
2015-12-22 22:19:50 +01:00
}
2016-01-09 18:40:13 +01:00
/// Request headers from a peer by block hash
2016-01-14 19:03:48 +01:00
fn request_headers_by_hash(&mut self, sync: &mut SyncIo, peer_id: PeerId, h: &H256, count: usize, skip: usize, reverse: bool) {
2016-01-09 18:40:13 +01:00
trace!(target: "sync", "{} <- GetBlockHeaders: {} entries starting from {}", peer_id, count, h);
2015-12-22 22:19:50 +01:00
let mut rlp = RlpStream::new_list(4);
rlp.append(h);
rlp.append(&count);
rlp.append(&skip);
rlp.append(&if reverse {1u32} else {0u32});
self.send_request(sync, peer_id, PeerAsking::BlockHeaders, GET_BLOCK_HEADERS_PACKET, rlp.out());
}
2016-01-09 18:40:13 +01:00
/// Request headers from a peer by block number
2016-01-14 19:03:48 +01:00
fn request_headers_by_number(&mut self, sync: &mut SyncIo, peer_id: PeerId, n: BlockNumber, count: usize, skip: usize, reverse: bool) {
2015-12-22 22:19:50 +01:00
let mut rlp = RlpStream::new_list(4);
2016-01-09 18:40:13 +01:00
trace!(target: "sync", "{} <- GetBlockHeaders: {} entries starting from {}", peer_id, count, n);
2015-12-22 22:19:50 +01:00
rlp.append(&n);
rlp.append(&count);
rlp.append(&skip);
rlp.append(&if reverse {1u32} else {0u32});
self.send_request(sync, peer_id, PeerAsking::BlockHeaders, GET_BLOCK_HEADERS_PACKET, rlp.out());
}
2016-01-09 18:40:13 +01:00
/// Request block bodies from a peer
2016-01-14 19:03:48 +01:00
fn request_bodies(&mut self, sync: &mut SyncIo, peer_id: PeerId, hashes: Vec<H256>) {
2015-12-22 22:19:50 +01:00
let mut rlp = RlpStream::new_list(hashes.len());
2016-01-09 18:40:13 +01:00
trace!(target: "sync", "{} <- GetBlockBodies: {} entries", peer_id, hashes.len());
2015-12-22 22:19:50 +01:00
for h in hashes {
rlp.append(&h);
}
2015-12-25 14:55:55 +01:00
self.send_request(sync, peer_id, PeerAsking::BlockBodies, GET_BLOCK_BODIES_PACKET, rlp.out());
2015-12-22 22:19:50 +01:00
}
2016-01-09 18:40:13 +01:00
/// Reset peer status after request is complete.
2016-01-14 19:03:48 +01:00
fn reset_peer_asking(&mut self, peer_id: PeerId, asking: PeerAsking) {
2015-12-27 00:48:03 +01:00
let peer = self.peers.get_mut(&peer_id).expect("ChainSync: unknown peer");
if peer.asking != asking {
warn!(target:"sync", "Asking {:?} while expected {:?}", peer.asking, asking);
}
else {
peer.asking = PeerAsking::Nothing;
}
}
2016-01-09 18:40:13 +01:00
/// Generic request sender
2016-01-14 19:03:48 +01:00
fn send_request(&mut self, sync: &mut SyncIo, peer_id: PeerId, asking: PeerAsking, packet_id: PacketId, packet: Bytes) {
2015-12-22 22:19:50 +01:00
{
2015-12-25 14:55:55 +01:00
let peer = self.peers.get_mut(&peer_id).expect("ChainSync: unknown peer");
2015-12-22 22:19:50 +01:00
if peer.asking != PeerAsking::Nothing {
warn!(target:"sync", "Asking {:?} while requesting {:?}", asking, peer.asking);
}
}
2016-01-14 19:03:48 +01:00
match sync.send(peer_id, packet_id, packet) {
2015-12-22 22:19:50 +01:00
Err(e) => {
warn!(target:"sync", "Error sending request: {:?}", e);
sync.disable_peer(peer_id);
2015-12-24 17:18:47 +01:00
self.on_peer_aborting(sync, peer_id);
2015-12-22 22:19:50 +01:00
}
Ok(_) => {
let mut peer = self.peers.get_mut(&peer_id).unwrap();
peer.asking = asking;
}
}
}
2015-12-24 17:18:47 +01:00
2016-01-09 18:40:13 +01:00
/// Called when peer sends us new transactions
2016-01-14 19:03:48 +01:00
fn on_peer_transactions(&mut self, _io: &mut SyncIo, _peer_id: PeerId, _r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
2016-01-08 17:52:25 +01:00
Ok(())
2015-12-24 17:18:47 +01:00
}
2016-01-09 18:40:13 +01:00
/// Send Status message
2016-01-14 19:03:48 +01:00
fn send_status(&mut self, io: &mut SyncIo, peer_id: PeerId) {
2015-12-24 17:18:47 +01:00
let mut packet = RlpStream::new_list(5);
2016-01-07 20:43:37 +01:00
let chain = io.chain().chain_info();
2015-12-24 17:18:47 +01:00
packet.append(&(PROTOCOL_VERSION as u32));
2016-01-10 14:11:23 +01:00
packet.append(&NETWORK_ID); //TODO: network id
2015-12-24 17:18:47 +01:00
packet.append(&chain.total_difficulty);
2016-01-07 16:08:12 +01:00
packet.append(&chain.best_block_hash);
2015-12-24 17:18:47 +01:00
packet.append(&chain.genesis_hash);
2015-12-26 15:47:07 +01:00
//TODO: handle timeout for status request
2016-01-17 15:56:09 +01:00
if let Err(e) = io.send(peer_id, STATUS_PACKET, packet.out()) {
warn!(target:"sync", "Error sending status request: {:?}", e);
io.disable_peer(peer_id);
2015-12-26 15:47:07 +01:00
}
2015-12-24 17:18:47 +01:00
}
2016-01-09 18:40:13 +01:00
/// Respond to GetBlockHeaders request
2016-01-08 17:52:25 +01:00
fn return_block_headers(&self, io: &mut SyncIo, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
2015-12-24 17:18:47 +01:00
// Packet layout:
// [ block: { P , B_32 }, maxHeaders: P, skip: P, reverse: P in { 0 , 1 } ]
2016-01-08 17:52:25 +01:00
let max_headers: usize = try!(r.val_at(1));
let skip: usize = try!(r.val_at(2));
let reverse: bool = try!(r.val_at(3));
2016-01-07 20:43:37 +01:00
let last = io.chain().chain_info().best_block_number;
2016-01-08 17:52:25 +01:00
let mut number = if try!(r.at(0)).size() == 32 {
2015-12-24 17:18:47 +01:00
// id is a hash
2016-01-08 17:52:25 +01:00
let hash: H256 = try!(r.val_at(0));
2015-12-27 00:48:03 +01:00
trace!(target: "sync", "-> GetBlockHeaders (hash: {}, max: {}, skip: {}, reverse:{})", hash, max_headers, skip, reverse);
2015-12-26 15:47:07 +01:00
match io.chain().block_header(&hash) {
2015-12-28 12:03:05 +01:00
Some(hdr) => From::from(HeaderView::new(&hdr).number()),
2015-12-24 17:18:47 +01:00
None => last
}
}
else {
2016-01-08 17:52:25 +01:00
trace!(target: "sync", "-> GetBlockHeaders (number: {}, max: {}, skip: {}, reverse:{})", try!(r.val_at::<BlockNumber>(0)), max_headers, skip, reverse);
try!(r.val_at(0))
2015-12-24 17:18:47 +01:00
};
2015-12-27 00:48:03 +01:00
if reverse {
number = min(last, number);
} else {
number = max(1, number);
}
2015-12-24 17:18:47 +01:00
let max_count = min(MAX_HEADERS_TO_SEND, max_headers);
let mut count = 0;
let mut data = Bytes::new();
2016-01-08 16:26:00 +01:00
let inc = (skip + 1) as BlockNumber;
2015-12-27 00:48:03 +01:00
while number <= last && number > 0 && count < max_count {
2016-01-17 15:56:09 +01:00
if let Some(mut hdr) = io.chain().block_header_at(number) {
data.append(&mut hdr);
count += 1;
2015-12-24 17:18:47 +01:00
}
2015-12-25 14:55:55 +01:00
if reverse {
2016-01-08 16:26:00 +01:00
if number <= inc {
break;
}
number -= inc;
2015-12-25 14:55:55 +01:00
}
else {
2016-01-08 16:26:00 +01:00
number += inc;
2015-12-25 14:55:55 +01:00
}
2015-12-24 17:18:47 +01:00
}
let mut rlp = RlpStream::new_list(count as usize);
rlp.append_raw(&data, count as usize);
2015-12-26 15:47:07 +01:00
io.respond(BLOCK_HEADERS_PACKET, rlp.out()).unwrap_or_else(|e|
2015-12-25 14:55:55 +01:00
debug!(target: "sync", "Error sending headers: {:?}", e));
2015-12-27 00:48:03 +01:00
trace!(target: "sync", "-> GetBlockHeaders: returned {} entries", count);
2016-01-08 17:52:25 +01:00
Ok(())
2015-12-24 17:18:47 +01:00
}
2016-01-09 18:40:13 +01:00
/// Respond to GetBlockBodies request
2016-01-08 17:52:25 +01:00
fn return_block_bodies(&self, io: &mut SyncIo, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
2015-12-24 17:18:47 +01:00
let mut count = r.item_count();
if count == 0 {
debug!(target: "sync", "Empty GetBlockBodies request, ignoring.");
2016-01-08 17:52:25 +01:00
return Ok(());
2015-12-24 17:18:47 +01:00
}
2015-12-27 00:48:03 +01:00
trace!(target: "sync", "-> GetBlockBodies: {} entries", count);
2015-12-24 17:18:47 +01:00
count = min(count, MAX_BODIES_TO_SEND);
let mut added = 0usize;
let mut data = Bytes::new();
for i in 0..count {
2016-01-19 11:10:38 +01:00
if let Some(mut hdr) = io.chain().block_body(&try!(r.val_at::<H256>(i))) {
data.append(&mut hdr);
added += 1;
2015-12-24 17:18:47 +01:00
}
}
let mut rlp = RlpStream::new_list(added);
rlp.append_raw(&data, added);
2015-12-26 15:47:07 +01:00
io.respond(BLOCK_BODIES_PACKET, rlp.out()).unwrap_or_else(|e|
2015-12-25 14:55:55 +01:00
debug!(target: "sync", "Error sending headers: {:?}", e));
2015-12-27 00:48:03 +01:00
trace!(target: "sync", "-> GetBlockBodies: returned {} entries", added);
2016-01-08 17:52:25 +01:00
Ok(())
2015-12-24 17:18:47 +01:00
}
2016-01-09 18:40:13 +01:00
/// Respond to GetNodeData request
2016-01-08 17:52:25 +01:00
fn return_node_data(&self, io: &mut SyncIo, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
2015-12-24 17:18:47 +01:00
let mut count = r.item_count();
if count == 0 {
debug!(target: "sync", "Empty GetNodeData request, ignoring.");
2016-01-08 17:52:25 +01:00
return Ok(());
2015-12-24 17:18:47 +01:00
}
count = min(count, MAX_NODE_DATA_TO_SEND);
let mut added = 0usize;
let mut data = Bytes::new();
for i in 0..count {
2016-01-19 11:10:38 +01:00
if let Some(mut hdr) = io.chain().state_data(&try!(r.val_at::<H256>(i))) {
data.append(&mut hdr);
added += 1;
2015-12-24 17:18:47 +01:00
}
}
let mut rlp = RlpStream::new_list(added);
rlp.append_raw(&data, added);
2015-12-26 15:47:07 +01:00
io.respond(NODE_DATA_PACKET, rlp.out()).unwrap_or_else(|e|
2015-12-25 14:55:55 +01:00
debug!(target: "sync", "Error sending headers: {:?}", e));
2016-01-08 17:52:25 +01:00
Ok(())
2015-12-24 17:18:47 +01:00
}
2016-01-09 18:40:13 +01:00
/// Respond to GetReceipts request
2016-01-08 17:52:25 +01:00
fn return_receipts(&self, io: &mut SyncIo, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
2015-12-24 17:18:47 +01:00
let mut count = r.item_count();
if count == 0 {
debug!(target: "sync", "Empty GetReceipts request, ignoring.");
2016-01-08 17:52:25 +01:00
return Ok(());
2015-12-24 17:18:47 +01:00
}
count = min(count, MAX_RECEIPTS_TO_SEND);
let mut added = 0usize;
let mut data = Bytes::new();
for i in 0..count {
2016-01-19 11:10:38 +01:00
if let Some(mut hdr) = io.chain().block_receipts(&try!(r.val_at::<H256>(i))) {
data.append(&mut hdr);
added += 1;
2015-12-24 17:18:47 +01:00
}
}
let mut rlp = RlpStream::new_list(added);
rlp.append_raw(&data, added);
2015-12-26 15:47:07 +01:00
io.respond(RECEIPTS_PACKET, rlp.out()).unwrap_or_else(|e|
2015-12-25 14:55:55 +01:00
debug!(target: "sync", "Error sending headers: {:?}", e));
2016-01-08 17:52:25 +01:00
Ok(())
2015-12-24 17:18:47 +01:00
}
2016-01-09 18:40:13 +01:00
/// Dispatch incoming requests and responses
2016-01-14 19:03:48 +01:00
pub fn on_packet(&mut self, io: &mut SyncIo, peer: PeerId, packet_id: u8, data: &[u8]) {
2016-01-08 17:52:25 +01:00
let rlp = UntrustedRlp::new(data);
let result = match packet_id {
2015-12-24 17:18:47 +01:00
STATUS_PACKET => self.on_peer_status(io, peer, &rlp),
TRANSACTIONS_PACKET => self.on_peer_transactions(io, peer, &rlp),
2015-12-25 14:55:55 +01:00
GET_BLOCK_HEADERS_PACKET => self.return_block_headers(io, &rlp),
2015-12-24 17:18:47 +01:00
BLOCK_HEADERS_PACKET => self.on_peer_block_headers(io, peer, &rlp),
2015-12-25 14:55:55 +01:00
GET_BLOCK_BODIES_PACKET => self.return_block_bodies(io, &rlp),
2015-12-24 17:18:47 +01:00
BLOCK_BODIES_PACKET => self.on_peer_block_bodies(io, peer, &rlp),
NEW_BLOCK_PACKET => self.on_peer_new_block(io, peer, &rlp),
NEW_BLOCK_HASHES_PACKET => self.on_peer_new_hashes(io, peer, &rlp),
2015-12-25 14:55:55 +01:00
GET_NODE_DATA_PACKET => self.return_node_data(io, &rlp),
GET_RECEIPTS_PACKET => self.return_receipts(io, &rlp),
2016-01-08 17:52:25 +01:00
_ => {
debug!(target: "sync", "Unknown packet {}", packet_id);
Ok(())
}
};
result.unwrap_or_else(|e| {
debug!(target:"sync", "{} -> Malformed packet {} : {}", peer, packet_id, e);
})
2015-12-24 17:18:47 +01:00
}
2015-12-22 22:19:50 +01:00
2016-01-09 18:40:13 +01:00
/// Maintain other peers. Send out any new blocks and transactions
2016-01-22 04:54:38 +01:00
pub fn _maintain_sync(&mut self, _io: &mut SyncIo) {
2015-12-22 22:19:50 +01:00
}
}