forked from nervosnetwork/ckb
/
get_blocks_process.rs
58 lines (53 loc) · 1.83 KB
/
get_blocks_process.rs
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
use crate::synchronizer::Synchronizer;
use ckb_network::{CKBProtocolContext, PeerIndex};
use ckb_protocol::{cast, GetBlocks, SyncMessage};
use ckb_shared::index::ChainIndex;
use failure::Error as FailureError;
use flatbuffers::FlatBufferBuilder;
use log::{debug, warn};
use std::convert::TryInto;
pub struct GetBlocksProcess<'a, CI: ChainIndex + 'a> {
message: &'a GetBlocks<'a>,
synchronizer: &'a Synchronizer<CI>,
nc: &'a mut CKBProtocolContext,
peer: PeerIndex,
}
impl<'a, CI> GetBlocksProcess<'a, CI>
where
CI: ChainIndex + 'a,
{
pub fn new(
message: &'a GetBlocks,
synchronizer: &'a Synchronizer<CI>,
peer: PeerIndex,
nc: &'a mut CKBProtocolContext,
) -> Self {
GetBlocksProcess {
peer,
message,
nc,
synchronizer,
}
}
pub fn execute(self) -> Result<(), FailureError> {
let block_hashes = cast!(self.message.block_hashes())?;
for fbs_h256 in block_hashes {
let block_hash = fbs_h256.try_into()?;
debug!(target: "sync", "get_blocks {:x}", block_hash);
if let Some(block) = self.synchronizer.get_block(&block_hash) {
debug!(target: "sync", "respond_block {} {:x}", block.header().number(), block.header().hash());
let fbb = &mut FlatBufferBuilder::new();
let message = SyncMessage::build_block(fbb, &block);
fbb.finish(message, None);
let ret = self.nc.send(self.peer, fbb.finished_data().to_vec());
if ret.is_err() {
warn!(target: "relay", "response GetBlocks error {:?}", ret);
}
} else {
// TODO response not found
// TODO add timeout check in synchronizer
}
}
Ok(())
}
}