Post enactment block verification
This commit is contained in:
parent
8f631a7c60
commit
00868488cf
14
src/block.rs
14
src/block.rs
@ -229,6 +229,9 @@ impl<'x, 'y> ClosedBlock<'x, 'y> {
|
||||
|
||||
/// Turn this back into an `OpenBlock`.
|
||||
pub fn reopen(self) -> OpenBlock<'x, 'y> { self.open_block }
|
||||
|
||||
/// Drop this object and return the underlieing database.
|
||||
pub fn drain(self) -> OverlayDB { self.open_block.block.state.drop().1 }
|
||||
}
|
||||
|
||||
impl SealedBlock {
|
||||
@ -251,15 +254,20 @@ impl IsBlock for SealedBlock {
|
||||
}
|
||||
|
||||
/// Enact the block given by `block_bytes` using `engine` on the database `db` with given `parent` block header
|
||||
///
|
||||
pub fn enact(block_bytes: &[u8], engine: &Engine, db: OverlayDB, parent: &Header, last_hashes: &LastHashes) -> Result<SealedBlock, Error> {
|
||||
pub fn enact<'x, 'y>(block_bytes: &[u8], engine: &'x Engine, db: OverlayDB, parent: &Header, last_hashes: &'y LastHashes) -> Result<ClosedBlock<'x, 'y>, Error> {
|
||||
let block = BlockView::new(block_bytes);
|
||||
let header = block.header_view();
|
||||
let mut b = OpenBlock::new(engine, db, parent, last_hashes, header.author(), header.extra_data());
|
||||
b.set_timestamp(header.timestamp());
|
||||
for t in block.transactions().into_iter() { try!(b.push_transaction(t, None)); }
|
||||
for u in block.uncles().into_iter() { try!(b.push_uncle(u)); }
|
||||
Ok(try!(b.close().seal(header.seal())))
|
||||
Ok(b.close())
|
||||
}
|
||||
|
||||
/// Enact the block given by `block_bytes` using `engine` on the database `db` with given `parent` block header. Seal the block aferwards
|
||||
pub fn enact_and_seal(block_bytes: &[u8], engine: &Engine, db: OverlayDB, parent: &Header, last_hashes: &LastHashes) -> Result<SealedBlock, Error> {
|
||||
let header = BlockView::new(block_bytes).header_view();
|
||||
Ok(try!(try!(enact(block_bytes, engine, db, parent, last_hashes)).seal(header.seal())))
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
@ -46,7 +46,7 @@ pub struct BlockQueueStatus {
|
||||
pub type TreeRoute = ::blockchain::TreeRoute;
|
||||
|
||||
/// Blockchain database client. Owns and manages a blockchain and a block queue.
|
||||
pub trait BlockChainClient : Sync {
|
||||
pub trait BlockChainClient : Sync + Send {
|
||||
/// Get raw block header data by block header hash.
|
||||
fn block_header(&self, hash: &H256) -> Option<Bytes>;
|
||||
|
||||
@ -111,11 +111,13 @@ impl Client {
|
||||
let mut state_path = path.to_path_buf();
|
||||
state_path.push("state");
|
||||
let db = DB::open_default(state_path.to_str().unwrap()).unwrap();
|
||||
let mut state_db = OverlayDB::new(db);
|
||||
engine.spec().ensure_db_good(&mut state_db);
|
||||
|
||||
Ok(Client {
|
||||
chain: chain.clone(),
|
||||
engine: engine.clone(),
|
||||
state_db: OverlayDB::new(db),
|
||||
state_db: state_db,
|
||||
queue: BlockQueue::new(engine.clone(), message_channel),
|
||||
})
|
||||
}
|
||||
@ -123,16 +125,16 @@ impl Client {
|
||||
|
||||
pub fn import_verified_block(&mut self, bytes: Bytes) {
|
||||
let block = BlockView::new(&bytes);
|
||||
let header = block.header_view();
|
||||
if let Err(e) = verify_block_final(&bytes, self.engine.deref().deref(), self.chain.read().unwrap().deref()) {
|
||||
warn!(target: "client", "Stage 3 block verification failed for {}\nError: {:?}", header.sha3(), e);
|
||||
let header = block.header();
|
||||
if let Err(e) = verify_block_family(&bytes, self.engine.deref().deref(), self.chain.read().unwrap().deref()) {
|
||||
warn!(target: "client", "Stage 3 block verification failed for {}\nError: {:?}", header.hash(), e);
|
||||
// TODO: mark as bad
|
||||
return;
|
||||
};
|
||||
let parent = match self.chain.read().unwrap().block_header(&header.parent_hash()) {
|
||||
let parent = match self.chain.read().unwrap().block_header(&header.parent_hash) {
|
||||
Some(p) => p,
|
||||
None => {
|
||||
warn!(target: "client", "Stage 3 import failed for {}: Parent not found ({}) ", header.sha3(), header.parent_hash());
|
||||
warn!(target: "client", "Block import failed for {}: Parent not found ({}) ", header.hash(), header.parent_hash);
|
||||
return;
|
||||
},
|
||||
};
|
||||
@ -150,15 +152,26 @@ impl Client {
|
||||
}
|
||||
}
|
||||
|
||||
let mut b = OpenBlock::new(self.engine.deref().deref(), self.state_db.clone(), &parent, &last_hashes, header.author(), header.extra_data());
|
||||
|
||||
for t in block.transactions().into_iter() {
|
||||
if let Err(e) = b.push_transaction(t.clone(), None) {
|
||||
warn!(target: "client", "Stage 3 transaction import failed for block {}\nTransaction:{:?}\nError: {:?}", header.sha3(), t, e);
|
||||
let result = match enact(&bytes, self.engine.deref().deref(), self.state_db.clone(), &parent, &last_hashes) {
|
||||
Ok(b) => b,
|
||||
Err(e) => {
|
||||
warn!(target: "client", "Block import failed for {}\nError: {:?}", header.hash(), e);
|
||||
return;
|
||||
};
|
||||
}
|
||||
};
|
||||
if let Err(e) = verify_block_final(&header, result.block().header()) {
|
||||
warn!(target: "client", "Stage 4 block verification failed for {}\nError: {:?}", header.hash(), e);
|
||||
}
|
||||
self.chain.write().unwrap().insert_block(&bytes);
|
||||
|
||||
self.chain.write().unwrap().insert_block(&bytes); //TODO: err here?
|
||||
match result.drain().commit() {
|
||||
Ok(_) => (),
|
||||
Err(e) => {
|
||||
warn!(target: "client", "State DB commit failed: {:?}", e);
|
||||
return;
|
||||
}
|
||||
}
|
||||
info!(target: "client", "Imported {}", header.hash());
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -45,7 +45,7 @@ pub trait Engine : Sync + Send {
|
||||
|
||||
/// Phase 3 verification. Check block information against parent and uncles. `block` (the header's full block)
|
||||
/// may be provided for additional checks. Returns either a null `Ok` or a general error detailing the problem with import.
|
||||
fn verify_block_final(&self, _header: &Header, _parent: &Header, _block: Option<&[u8]>) -> Result<(), Error> { Ok(()) }
|
||||
fn verify_block_family(&self, _header: &Header, _parent: &Header, _block: Option<&[u8]>) -> Result<(), Error> { Ok(()) }
|
||||
|
||||
/// Additional verification for transactions in blocks.
|
||||
// TODO: Add flags for which bits of the transaction to check.
|
||||
|
11
src/error.rs
11
src/error.rs
@ -2,6 +2,7 @@
|
||||
|
||||
use util::*;
|
||||
use header::BlockNumber;
|
||||
use basic_types::LogBloom;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Mismatch<T: fmt::Debug> {
|
||||
@ -50,15 +51,15 @@ pub enum BlockError {
|
||||
UncleIsBrother(OutOfBounds<BlockNumber>),
|
||||
UncleInChain(H256),
|
||||
UncleParentNotInChain(H256),
|
||||
InvalidStateRoot,
|
||||
InvalidGasUsed,
|
||||
InvalidStateRoot(Mismatch<H256>),
|
||||
InvalidGasUsed(Mismatch<U256>),
|
||||
InvalidTransactionsRoot(Mismatch<H256>),
|
||||
InvalidDifficulty(Mismatch<U256>),
|
||||
InvalidGasLimit(OutOfBounds<U256>),
|
||||
InvalidReceiptsStateRoot,
|
||||
InvalidReceiptsStateRoot(Mismatch<H256>),
|
||||
InvalidTimestamp(OutOfBounds<u64>),
|
||||
InvalidLogBloom,
|
||||
InvalidBlockNonce,
|
||||
InvalidLogBloom(Mismatch<LogBloom>),
|
||||
InvalidBlockNonce(Mismatch<H256>),
|
||||
InvalidParentHash(Mismatch<H256>),
|
||||
InvalidNumber(OutOfBounds<BlockNumber>),
|
||||
UnknownParent(H256),
|
||||
|
@ -60,7 +60,7 @@ impl Engine for Ethash {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify_block_final(&self, header: &Header, parent: &Header, _block: Option<&[u8]>) -> result::Result<(), Error> {
|
||||
fn verify_block_family(&self, header: &Header, parent: &Header, _block: Option<&[u8]>) -> result::Result<(), Error> {
|
||||
// Check difficulty is correct given the two timestamps.
|
||||
let expected_difficulty = self.calculate_difficuty(header, parent);
|
||||
if header.difficulty != expected_difficulty {
|
||||
|
11
src/queue.rs
11
src/queue.rs
@ -3,6 +3,7 @@ use verification::*;
|
||||
use error::*;
|
||||
use engine::Engine;
|
||||
use sync::*;
|
||||
use views::*;
|
||||
|
||||
/// A queue of blocks. Sits between network or other I/O and the BlockChain.
|
||||
/// Sorts them ready for blockchain insertion.
|
||||
@ -26,8 +27,14 @@ impl BlockQueue {
|
||||
|
||||
/// Add a block to the queue.
|
||||
pub fn import_block(&mut self, bytes: &[u8]) -> ImportResult {
|
||||
try!(verify_block_basic(bytes, self.engine.deref().deref()));
|
||||
try!(verify_block_unordered(bytes, self.engine.deref().deref()));
|
||||
try!(verify_block_basic(bytes, self.engine.deref().deref()).map_err(|e| {
|
||||
warn!(target: "client", "Stage 1 block verification failed for {}\nError: {:?}", BlockView::new(&bytes).header_view().sha3(), e);
|
||||
e
|
||||
}));
|
||||
try!(verify_block_unordered(bytes, self.engine.deref().deref()).map_err(|e| {
|
||||
warn!(target: "client", "Stage 2 block verification failed for {}\nError: {:?}", BlockView::new(&bytes).header_view().sha3(), e);
|
||||
e
|
||||
}));
|
||||
try!(self.message_channel.send(UserMessage(SyncMessage::BlockVerified(bytes.to_vec()))).map_err(|e| Error::from(e)));
|
||||
Ok(())
|
||||
}
|
||||
|
@ -19,9 +19,11 @@ pub struct ClientService {
|
||||
impl ClientService {
|
||||
pub fn start(spec: Spec) -> Result<ClientService, Error> {
|
||||
let mut net_service = try!(NetworkService::start());
|
||||
let mut dir = env::temp_dir();
|
||||
dir.push(H32::random().hex());
|
||||
let client = Arc::new(Client::new(spec, &dir, net_service.io().channel()).unwrap());
|
||||
info!("Starting {}", net_service.host_info());
|
||||
let mut dir = env::home_dir().unwrap();
|
||||
dir.push(".parity");
|
||||
dir.push(H64::from(spec.genesis_header().hash()).hex());
|
||||
let client = Arc::new(RwLock::new(try!(Client::new(spec, &dir, net_service.io().channel()))));
|
||||
EthSync::register(&mut net_service, client.clone());
|
||||
let client_io = Box::new(ClientIoHandler {
|
||||
client: client
|
||||
@ -35,7 +37,7 @@ impl ClientService {
|
||||
}
|
||||
|
||||
struct ClientIoHandler {
|
||||
client: Arc<Client>
|
||||
client: Arc<RwLock<Client>>
|
||||
}
|
||||
|
||||
impl IoHandler<NetSyncMessage> for ClientIoHandler {
|
||||
@ -47,7 +49,7 @@ impl IoHandler<NetSyncMessage> for ClientIoHandler {
|
||||
&mut UserMessage(ref mut message) => {
|
||||
match message {
|
||||
&mut SyncMessage::BlockVerified(ref mut bytes) => {
|
||||
Arc::get_mut(&mut self.client).unwrap().import_verified_block(mem::replace(bytes, Bytes::new()));
|
||||
self.client.write().unwrap().import_verified_block(mem::replace(bytes, Bytes::new()));
|
||||
},
|
||||
_ => {},
|
||||
}
|
||||
|
@ -234,7 +234,7 @@ impl ChainSync {
|
||||
}
|
||||
|
||||
/// Called by peer to report status
|
||||
fn on_peer_status(&mut self, io: &mut SyncIo, peer_id: &PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
|
||||
fn on_peer_status(&mut self, io: &mut SyncIo, peer_id: PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
|
||||
let peer = PeerInfo {
|
||||
protocol_version: try!(r.val_at(0)),
|
||||
network_id: try!(r.val_at(1)),
|
||||
@ -263,12 +263,13 @@ impl ChainSync {
|
||||
if old.is_some() {
|
||||
panic!("ChainSync: new peer already exists");
|
||||
}
|
||||
info!(target: "sync", "Connected {}:{}", peer_id, io.peer_info(peer_id));
|
||||
self.sync_peer(io, peer_id, false);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Called by peer once it has new block headers during sync
|
||||
fn on_peer_block_headers(&mut self, io: &mut SyncIo, peer_id: &PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
|
||||
fn on_peer_block_headers(&mut self, io: &mut SyncIo, peer_id: PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
|
||||
self.reset_peer_asking(peer_id, PeerAsking::BlockHeaders);
|
||||
let item_count = r.item_count();
|
||||
trace!(target: "sync", "{} -> BlockHeaders ({} entries)", peer_id, item_count);
|
||||
@ -351,7 +352,7 @@ impl ChainSync {
|
||||
}
|
||||
|
||||
/// Called by peer once it has new block bodies
|
||||
fn on_peer_block_bodies(&mut self, io: &mut SyncIo, peer_id: &PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
|
||||
fn on_peer_block_bodies(&mut self, io: &mut SyncIo, peer_id: PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
|
||||
use util::triehash::ordered_trie_root;
|
||||
self.reset_peer_asking(peer_id, PeerAsking::BlockBodies);
|
||||
let item_count = r.item_count();
|
||||
@ -391,7 +392,7 @@ impl ChainSync {
|
||||
}
|
||||
|
||||
/// Called by peer once it has new block bodies
|
||||
fn on_peer_new_block(&mut self, io: &mut SyncIo, peer_id: &PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
|
||||
fn on_peer_new_block(&mut self, io: &mut SyncIo, peer_id: PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
|
||||
let block_rlp = try!(r.at(0));
|
||||
let header_rlp = try!(block_rlp.at(0));
|
||||
let h = header_rlp.as_raw().sha3();
|
||||
@ -430,7 +431,7 @@ impl ChainSync {
|
||||
}
|
||||
|
||||
/// Handles NewHashes packet. Initiates headers download for any unknown hashes.
|
||||
fn on_peer_new_hashes(&mut self, io: &mut SyncIo, peer_id: &PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
|
||||
fn on_peer_new_hashes(&mut self, io: &mut SyncIo, peer_id: PeerId, r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
|
||||
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.");
|
||||
return Ok(());
|
||||
@ -467,16 +468,17 @@ impl ChainSync {
|
||||
}
|
||||
|
||||
/// Called by peer when it is disconnecting
|
||||
pub fn on_peer_aborting(&mut self, io: &mut SyncIo, peer: &PeerId) {
|
||||
trace!(target: "sync", "== Disconnected {}", peer);
|
||||
pub fn on_peer_aborting(&mut self, io: &mut SyncIo, peer: PeerId) {
|
||||
trace!(target: "sync", "== Disconnecting {}", peer);
|
||||
if self.peers.contains_key(&peer) {
|
||||
info!(target: "sync", "Disconneced {}:{}", peer, io.peer_info(peer));
|
||||
self.clear_peer_download(peer);
|
||||
self.continue_sync(io);
|
||||
}
|
||||
}
|
||||
|
||||
/// Called when a new peer is connected
|
||||
pub fn on_peer_connected(&mut self, io: &mut SyncIo, peer: &PeerId) {
|
||||
pub fn on_peer_connected(&mut self, io: &mut SyncIo, peer: PeerId) {
|
||||
trace!(target: "sync", "== Connected {}", peer);
|
||||
self.send_status(io, peer);
|
||||
}
|
||||
@ -486,7 +488,7 @@ impl ChainSync {
|
||||
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 {
|
||||
self.sync_peer(io, &p, false);
|
||||
self.sync_peer(io, p, false);
|
||||
}
|
||||
}
|
||||
|
||||
@ -504,7 +506,7 @@ impl ChainSync {
|
||||
}
|
||||
|
||||
/// Find something to do for a peer. Called for a new peer or when a peer is done with it's task.
|
||||
fn sync_peer(&mut self, io: &mut SyncIo, peer_id: &PeerId, force: bool) {
|
||||
fn sync_peer(&mut self, io: &mut SyncIo, peer_id: PeerId, force: bool) {
|
||||
let (peer_latest, peer_difficulty) = {
|
||||
let peer = self.peers.get_mut(&peer_id).expect("ChainSync: unknown peer");
|
||||
if peer.asking != PeerAsking::Nothing {
|
||||
@ -534,7 +536,7 @@ impl ChainSync {
|
||||
}
|
||||
|
||||
/// Find some headers or blocks to download for a peer.
|
||||
fn request_blocks(&mut self, io: &mut SyncIo, peer_id: &PeerId) {
|
||||
fn request_blocks(&mut self, io: &mut SyncIo, peer_id: PeerId) {
|
||||
self.clear_peer_download(peer_id);
|
||||
|
||||
if io.chain().queue_status().full {
|
||||
@ -564,7 +566,7 @@ impl ChainSync {
|
||||
}
|
||||
}
|
||||
if !needed_bodies.is_empty() {
|
||||
replace(&mut self.peers.get_mut(peer_id).unwrap().asking_blocks, needed_numbers);
|
||||
replace(&mut self.peers.get_mut(&peer_id).unwrap().asking_blocks, needed_numbers);
|
||||
self.request_bodies(io, peer_id, needed_bodies);
|
||||
}
|
||||
else {
|
||||
@ -607,7 +609,7 @@ impl ChainSync {
|
||||
if !headers.is_empty() {
|
||||
start = headers[0] as usize;
|
||||
let count = headers.len();
|
||||
replace(&mut self.peers.get_mut(peer_id).unwrap().asking_blocks, headers);
|
||||
replace(&mut self.peers.get_mut(&peer_id).unwrap().asking_blocks, headers);
|
||||
assert!(!self.headers.have_item(&(start as BlockNumber)));
|
||||
self.request_headers_by_number(io, peer_id, start as BlockNumber, count, 0, false);
|
||||
}
|
||||
@ -619,7 +621,7 @@ impl ChainSync {
|
||||
}
|
||||
|
||||
/// Clear all blocks/headers marked as being downloaded by a peer.
|
||||
fn clear_peer_download(&mut self, peer_id: &PeerId) {
|
||||
fn clear_peer_download(&mut self, peer_id: PeerId) {
|
||||
let peer = self.peers.get_mut(&peer_id).expect("ChainSync: unknown peer");
|
||||
for b in &peer.asking_blocks {
|
||||
self.downloading_headers.remove(&b);
|
||||
@ -715,7 +717,7 @@ impl ChainSync {
|
||||
}
|
||||
|
||||
/// Request headers from a peer by block hash
|
||||
fn request_headers_by_hash(&mut self, sync: &mut SyncIo, peer_id: &PeerId, h: &H256, count: usize, skip: usize, reverse: bool) {
|
||||
fn request_headers_by_hash(&mut self, sync: &mut SyncIo, peer_id: PeerId, h: &H256, count: usize, skip: usize, reverse: bool) {
|
||||
trace!(target: "sync", "{} <- GetBlockHeaders: {} entries starting from {}", peer_id, count, h);
|
||||
let mut rlp = RlpStream::new_list(4);
|
||||
rlp.append(h);
|
||||
@ -726,7 +728,7 @@ impl ChainSync {
|
||||
}
|
||||
|
||||
/// Request headers from a peer by block number
|
||||
fn request_headers_by_number(&mut self, sync: &mut SyncIo, peer_id: &PeerId, n: BlockNumber, count: usize, skip: usize, reverse: bool) {
|
||||
fn request_headers_by_number(&mut self, sync: &mut SyncIo, peer_id: PeerId, n: BlockNumber, count: usize, skip: usize, reverse: bool) {
|
||||
let mut rlp = RlpStream::new_list(4);
|
||||
trace!(target: "sync", "{} <- GetBlockHeaders: {} entries starting from {}", peer_id, count, n);
|
||||
rlp.append(&n);
|
||||
@ -737,7 +739,7 @@ impl ChainSync {
|
||||
}
|
||||
|
||||
/// Request block bodies from a peer
|
||||
fn request_bodies(&mut self, sync: &mut SyncIo, peer_id: &PeerId, hashes: Vec<H256>) {
|
||||
fn request_bodies(&mut self, sync: &mut SyncIo, peer_id: PeerId, hashes: Vec<H256>) {
|
||||
let mut rlp = RlpStream::new_list(hashes.len());
|
||||
trace!(target: "sync", "{} <- GetBlockBodies: {} entries", peer_id, hashes.len());
|
||||
for h in hashes {
|
||||
@ -747,7 +749,7 @@ impl ChainSync {
|
||||
}
|
||||
|
||||
/// Reset peer status after request is complete.
|
||||
fn reset_peer_asking(&mut self, peer_id: &PeerId, asking: PeerAsking) {
|
||||
fn reset_peer_asking(&mut self, peer_id: PeerId, asking: PeerAsking) {
|
||||
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);
|
||||
@ -758,14 +760,14 @@ impl ChainSync {
|
||||
}
|
||||
|
||||
/// Generic request sender
|
||||
fn send_request(&mut self, sync: &mut SyncIo, peer_id: &PeerId, asking: PeerAsking, packet_id: PacketId, packet: Bytes) {
|
||||
fn send_request(&mut self, sync: &mut SyncIo, peer_id: PeerId, asking: PeerAsking, packet_id: PacketId, packet: Bytes) {
|
||||
{
|
||||
let peer = self.peers.get_mut(&peer_id).expect("ChainSync: unknown peer");
|
||||
if peer.asking != PeerAsking::Nothing {
|
||||
warn!(target:"sync", "Asking {:?} while requesting {:?}", asking, peer.asking);
|
||||
}
|
||||
}
|
||||
match sync.send(*peer_id, packet_id, packet) {
|
||||
match sync.send(peer_id, packet_id, packet) {
|
||||
Err(e) => {
|
||||
warn!(target:"sync", "Error sending request: {:?}", e);
|
||||
sync.disable_peer(peer_id);
|
||||
@ -779,12 +781,12 @@ impl ChainSync {
|
||||
}
|
||||
|
||||
/// Called when peer sends us new transactions
|
||||
fn on_peer_transactions(&mut self, _io: &mut SyncIo, _peer_id: &PeerId, _r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
|
||||
fn on_peer_transactions(&mut self, _io: &mut SyncIo, _peer_id: PeerId, _r: &UntrustedRlp) -> Result<(), PacketDecodeError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Send Status message
|
||||
fn send_status(&mut self, io: &mut SyncIo, peer_id: &PeerId) {
|
||||
fn send_status(&mut self, io: &mut SyncIo, peer_id: PeerId) {
|
||||
let mut packet = RlpStream::new_list(5);
|
||||
let chain = io.chain().chain_info();
|
||||
packet.append(&(PROTOCOL_VERSION as u32));
|
||||
@ -793,7 +795,7 @@ impl ChainSync {
|
||||
packet.append(&chain.best_block_hash);
|
||||
packet.append(&chain.genesis_hash);
|
||||
//TODO: handle timeout for status request
|
||||
match io.send(*peer_id, STATUS_PACKET, packet.out()) {
|
||||
match io.send(peer_id, STATUS_PACKET, packet.out()) {
|
||||
Err(e) => {
|
||||
warn!(target:"sync", "Error sending status request: {:?}", e);
|
||||
io.disable_peer(peer_id);
|
||||
@ -940,7 +942,7 @@ impl ChainSync {
|
||||
}
|
||||
|
||||
/// Dispatch incoming requests and responses
|
||||
pub fn on_packet(&mut self, io: &mut SyncIo, peer: &PeerId, packet_id: u8, data: &[u8]) {
|
||||
pub fn on_packet(&mut self, io: &mut SyncIo, peer: PeerId, packet_id: u8, data: &[u8]) {
|
||||
let rlp = UntrustedRlp::new(data);
|
||||
let result = match packet_id {
|
||||
STATUS_PACKET => self.on_peer_status(io, peer, &rlp),
|
||||
|
@ -8,13 +8,17 @@ use sync::SyncMessage;
|
||||
// TODO: ratings
|
||||
pub trait SyncIo {
|
||||
/// Disable a peer
|
||||
fn disable_peer(&mut self, peer_id: &PeerId);
|
||||
fn disable_peer(&mut self, peer_id: PeerId);
|
||||
/// Respond to current request with a packet. Can be called from an IO handler for incoming packet.
|
||||
fn respond(&mut self, packet_id: PacketId, data: Vec<u8>) -> Result<(), UtilError>;
|
||||
/// Send a packet to a peer.
|
||||
fn send(&mut self, peer_id: PeerId, packet_id: PacketId, data: Vec<u8>) -> Result<(), UtilError>;
|
||||
/// Get the blockchain
|
||||
fn chain<'s>(&'s mut self) -> &'s mut BlockChainClient;
|
||||
/// Returns peer client identifier string
|
||||
fn peer_info(&self, peer_id: PeerId) -> String {
|
||||
peer_id.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// Wraps `NetworkContext` and the blockchain client
|
||||
@ -34,8 +38,8 @@ impl<'s, 'h, 'io> NetSyncIo<'s, 'h, 'io> {
|
||||
}
|
||||
|
||||
impl<'s, 'h, 'op> SyncIo for NetSyncIo<'s, 'h, 'op> {
|
||||
fn disable_peer(&mut self, peer_id: &PeerId) {
|
||||
self.network.disable_peer(*peer_id);
|
||||
fn disable_peer(&mut self, peer_id: PeerId) {
|
||||
self.network.disable_peer(peer_id);
|
||||
}
|
||||
|
||||
fn respond(&mut self, packet_id: PacketId, data: Vec<u8>) -> Result<(), UtilError>{
|
||||
@ -49,6 +53,10 @@ impl<'s, 'h, 'op> SyncIo for NetSyncIo<'s, 'h, 'op> {
|
||||
fn chain<'a>(&'a mut self) -> &'a mut BlockChainClient {
|
||||
self.chain
|
||||
}
|
||||
|
||||
fn peer_info(&self, peer_id: PeerId) -> String {
|
||||
self.network.peer_info(peer_id)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
@ -22,8 +22,9 @@
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
use std::sync::Arc;
|
||||
use client::BlockChainClient;
|
||||
use std::ops::*;
|
||||
use std::sync::*;
|
||||
use client::Client;
|
||||
use util::network::{NetworkProtocolHandler, NetworkService, NetworkContext, PeerId, NetworkIoMessage};
|
||||
use util::TimerToken;
|
||||
use util::Bytes;
|
||||
@ -50,7 +51,7 @@ pub type NetSyncMessage = NetworkIoMessage<SyncMessage>;
|
||||
/// Ethereum network protocol handler
|
||||
pub struct EthSync {
|
||||
/// Shared blockchain client. TODO: this should evetually become an IPC endpoint
|
||||
chain: Arc<BlockChainClient + Send + Sized>,
|
||||
chain: Arc<RwLock<Client>>,
|
||||
/// Sync strategy
|
||||
sync: ChainSync
|
||||
}
|
||||
@ -59,7 +60,7 @@ pub use self::chain::SyncStatus;
|
||||
|
||||
impl EthSync {
|
||||
/// Creates and register protocol with the network service
|
||||
pub fn register(service: &mut NetworkService<SyncMessage>, chain: Arc<BlockChainClient + Send + Sized>) {
|
||||
pub fn register(service: &mut NetworkService<SyncMessage>, chain: Arc<RwLock<Client>>) {
|
||||
let sync = Box::new(EthSync {
|
||||
chain: chain,
|
||||
sync: ChainSync::new(),
|
||||
@ -74,35 +75,35 @@ impl EthSync {
|
||||
|
||||
/// Stop sync
|
||||
pub fn stop(&mut self, io: &mut NetworkContext<SyncMessage>) {
|
||||
self.sync.abort(&mut NetSyncIo::new(io, Arc::get_mut(&mut self.chain).unwrap()));
|
||||
self.sync.abort(&mut NetSyncIo::new(io, self.chain.write().unwrap().deref_mut()));
|
||||
}
|
||||
|
||||
/// Restart sync
|
||||
pub fn restart(&mut self, io: &mut NetworkContext<SyncMessage>) {
|
||||
self.sync.restart(&mut NetSyncIo::new(io, Arc::get_mut(&mut self.chain).unwrap()));
|
||||
self.sync.restart(&mut NetSyncIo::new(io, self.chain.write().unwrap().deref_mut()));
|
||||
}
|
||||
}
|
||||
|
||||
impl NetworkProtocolHandler<SyncMessage> for EthSync {
|
||||
fn initialize(&mut self, io: &mut NetworkContext<SyncMessage>) {
|
||||
self.sync.restart(&mut NetSyncIo::new(io, Arc::get_mut(&mut self.chain).unwrap()));
|
||||
self.sync.restart(&mut NetSyncIo::new(io, self.chain.write().unwrap().deref_mut()));
|
||||
io.register_timer(1000).unwrap();
|
||||
}
|
||||
|
||||
fn read(&mut self, io: &mut NetworkContext<SyncMessage>, peer: &PeerId, packet_id: u8, data: &[u8]) {
|
||||
self.sync.on_packet(&mut NetSyncIo::new(io, Arc::get_mut(&mut self.chain).unwrap()), peer, packet_id, data);
|
||||
self.sync.on_packet(&mut NetSyncIo::new(io, self.chain.write().unwrap().deref_mut()) , *peer, packet_id, data);
|
||||
}
|
||||
|
||||
fn connected(&mut self, io: &mut NetworkContext<SyncMessage>, peer: &PeerId) {
|
||||
self.sync.on_peer_connected(&mut NetSyncIo::new(io, Arc::get_mut(&mut self.chain).unwrap()), peer);
|
||||
self.sync.on_peer_connected(&mut NetSyncIo::new(io, self.chain.write().unwrap().deref_mut()), *peer);
|
||||
}
|
||||
|
||||
fn disconnected(&mut self, io: &mut NetworkContext<SyncMessage>, peer: &PeerId) {
|
||||
self.sync.on_peer_aborting(&mut NetSyncIo::new(io, Arc::get_mut(&mut self.chain).unwrap()), peer);
|
||||
self.sync.on_peer_aborting(&mut NetSyncIo::new(io, self.chain.write().unwrap().deref_mut()), *peer);
|
||||
}
|
||||
|
||||
fn timeout(&mut self, io: &mut NetworkContext<SyncMessage>, _timer: TimerToken) {
|
||||
self.sync.maintain_sync(&mut NetSyncIo::new(io, Arc::get_mut(&mut self.chain).unwrap()));
|
||||
self.sync.maintain_sync(&mut NetSyncIo::new(io, self.chain.write().unwrap().deref_mut()));
|
||||
}
|
||||
|
||||
fn message(&mut self, _io: &mut NetworkContext<SyncMessage>, _message: &SyncMessage) {
|
||||
|
@ -37,13 +37,13 @@ pub fn verify_block_unordered(bytes: &[u8], engine: &Engine) -> Result<(), Error
|
||||
}
|
||||
|
||||
/// Phase 3 verification. Check block information against parent and uncles.
|
||||
pub fn verify_block_final<BC>(bytes: &[u8], engine: &Engine, bc: &BC) -> Result<(), Error> where BC: BlockProvider {
|
||||
pub fn verify_block_family<BC>(bytes: &[u8], engine: &Engine, bc: &BC) -> Result<(), Error> where BC: BlockProvider {
|
||||
// TODO: verify timestamp
|
||||
let block = BlockView::new(bytes);
|
||||
let header = block.header();
|
||||
let parent = try!(bc.block_header(&header.parent_hash).ok_or::<Error>(From::from(BlockError::UnknownParent(header.parent_hash.clone()))));
|
||||
try!(verify_parent(&header, &parent));
|
||||
try!(engine.verify_block_final(&header, &parent, Some(bytes)));
|
||||
try!(engine.verify_block_family(&header, &parent, Some(bytes)));
|
||||
|
||||
let num_uncles = Rlp::new(bytes).at(2).item_count();
|
||||
if num_uncles != 0 {
|
||||
@ -113,12 +113,29 @@ pub fn verify_block_final<BC>(bytes: &[u8], engine: &Engine, bc: &BC) -> Result<
|
||||
}
|
||||
|
||||
try!(verify_parent(&uncle, &uncle_parent));
|
||||
try!(engine.verify_block_final(&uncle, &uncle_parent, Some(bytes)));
|
||||
try!(engine.verify_block_family(&uncle, &uncle_parent, Some(bytes)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Phase 4 verification. Check block information against transaction enactment results,
|
||||
pub fn verify_block_final(expected: &Header, got: &Header) -> Result<(), Error> {
|
||||
if expected.state_root != got.state_root {
|
||||
return Err(From::from(BlockError::InvalidStateRoot(Mismatch { expected: expected.state_root.clone(), found: got.state_root.clone() })))
|
||||
}
|
||||
if expected.receipts_root != got.receipts_root {
|
||||
return Err(From::from(BlockError::InvalidReceiptsStateRoot(Mismatch { expected: expected.receipts_root.clone(), found: got.receipts_root.clone() })))
|
||||
}
|
||||
if expected.log_bloom != got.log_bloom {
|
||||
return Err(From::from(BlockError::InvalidLogBloom(Mismatch { expected: expected.log_bloom.clone(), found: got.log_bloom.clone() })))
|
||||
}
|
||||
if expected.gas_used != got.gas_used {
|
||||
return Err(From::from(BlockError::InvalidGasUsed(Mismatch { expected: expected.gas_used, found: got.gas_used })))
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check basic header parameters.
|
||||
fn verify_header(header: &Header, engine: &Engine) -> Result<(), Error> {
|
||||
if header.number >= From::from(BlockNumber::max_value()) {
|
||||
@ -372,28 +389,28 @@ mod tests {
|
||||
check_fail(verify_block_basic(&create_test_block_with_data(&header, &good_transactions, &good_uncles), engine.deref()),
|
||||
InvalidUnclesHash(Mismatch { expected: good_uncles_hash.clone(), found: header.uncles_hash }));
|
||||
|
||||
check_ok(verify_block_final(&create_test_block(&good), engine.deref(), &bc));
|
||||
check_ok(verify_block_final(&create_test_block_with_data(&good, &good_transactions, &good_uncles), engine.deref(), &bc));
|
||||
check_ok(verify_block_family(&create_test_block(&good), engine.deref(), &bc));
|
||||
check_ok(verify_block_family(&create_test_block_with_data(&good, &good_transactions, &good_uncles), engine.deref(), &bc));
|
||||
|
||||
header = good.clone();
|
||||
header.parent_hash = H256::random();
|
||||
check_fail(verify_block_final(&create_test_block_with_data(&header, &good_transactions, &good_uncles), engine.deref(), &bc),
|
||||
check_fail(verify_block_family(&create_test_block_with_data(&header, &good_transactions, &good_uncles), engine.deref(), &bc),
|
||||
UnknownParent(header.parent_hash));
|
||||
|
||||
header = good.clone();
|
||||
header.timestamp = 10;
|
||||
check_fail(verify_block_final(&create_test_block_with_data(&header, &good_transactions, &good_uncles), engine.deref(), &bc),
|
||||
check_fail(verify_block_family(&create_test_block_with_data(&header, &good_transactions, &good_uncles), engine.deref(), &bc),
|
||||
InvalidTimestamp(OutOfBounds { max: None, min: Some(parent.timestamp + 1), found: header.timestamp }));
|
||||
|
||||
header = good.clone();
|
||||
header.number = 9;
|
||||
check_fail(verify_block_final(&create_test_block_with_data(&header, &good_transactions, &good_uncles), engine.deref(), &bc),
|
||||
check_fail(verify_block_family(&create_test_block_with_data(&header, &good_transactions, &good_uncles), engine.deref(), &bc),
|
||||
InvalidNumber(OutOfBounds { max: None, min: Some(parent.number + 1), found: header.number }));
|
||||
|
||||
header = good.clone();
|
||||
let mut bad_uncles = good_uncles.clone();
|
||||
bad_uncles.push(good_uncle1.clone());
|
||||
check_fail(verify_block_final(&create_test_block_with_data(&header, &good_transactions, &bad_uncles), engine.deref(), &bc),
|
||||
check_fail(verify_block_family(&create_test_block_with_data(&header, &good_transactions, &bad_uncles), engine.deref(), &bc),
|
||||
TooManyUncles(OutOfBounds { max: Some(engine.maximum_uncle_count()), min: None, found: bad_uncles.len() }));
|
||||
|
||||
// TODO: some additional uncle checks
|
||||
|
Loading…
Reference in New Issue
Block a user