mirror of
https://github.com/sigp/lighthouse.git
synced 2026-03-09 03:31:45 +00:00
Ethereum 2.0 Network Specification Upgrade (#510)
Updates lighthouse to the latest networking spec - Sync re-write (#496) - Updates to the latest eth2 networking spec (#495) - Libp2p updates and improvements
This commit is contained in:
@@ -1,8 +1,7 @@
|
||||
use crate::error;
|
||||
use crate::service::{NetworkMessage, OutgoingMessage};
|
||||
use crate::service::NetworkMessage;
|
||||
use crate::sync::SimpleSync;
|
||||
use beacon_chain::{BeaconChain, BeaconChainTypes};
|
||||
use eth2_libp2p::rpc::methods::*;
|
||||
use eth2_libp2p::{
|
||||
behaviour::PubsubMessage,
|
||||
rpc::{RPCError, RPCErrorResponse, RPCRequest, RPCResponse, RequestId},
|
||||
@@ -10,11 +9,11 @@ use eth2_libp2p::{
|
||||
};
|
||||
use futures::future::Future;
|
||||
use futures::stream::Stream;
|
||||
use slog::{debug, warn};
|
||||
use slog::{debug, trace, warn};
|
||||
use ssz::{Decode, DecodeError};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::mpsc;
|
||||
use types::{Attestation, BeaconBlock, BeaconBlockHeader};
|
||||
use types::{Attestation, AttesterSlashing, BeaconBlock, ProposerSlashing, VoluntaryExit};
|
||||
|
||||
/// Handles messages received from the network and client and organises syncing.
|
||||
pub struct MessageHandler<T: BeaconChainTypes> {
|
||||
@@ -22,8 +21,6 @@ pub struct MessageHandler<T: BeaconChainTypes> {
|
||||
_chain: Arc<BeaconChain<T>>,
|
||||
/// The syncing framework.
|
||||
sync: SimpleSync<T>,
|
||||
/// The context required to send messages to, and process messages from peers.
|
||||
network_context: NetworkContext,
|
||||
/// The `MessageHandler` logger.
|
||||
log: slog::Logger,
|
||||
}
|
||||
@@ -49,23 +46,20 @@ impl<T: BeaconChainTypes + 'static> MessageHandler<T> {
|
||||
executor: &tokio::runtime::TaskExecutor,
|
||||
log: slog::Logger,
|
||||
) -> error::Result<mpsc::UnboundedSender<HandlerMessage>> {
|
||||
debug!(log, "Service starting");
|
||||
trace!(log, "Service starting");
|
||||
|
||||
let (handler_send, handler_recv) = mpsc::unbounded_channel();
|
||||
|
||||
// Initialise sync and begin processing in thread
|
||||
// generate the Message handler
|
||||
let sync = SimpleSync::new(beacon_chain.clone(), &log);
|
||||
let sync = SimpleSync::new(beacon_chain.clone(), network_send, &log);
|
||||
|
||||
// generate the Message handler
|
||||
let mut handler = MessageHandler {
|
||||
_chain: beacon_chain.clone(),
|
||||
sync,
|
||||
network_context: NetworkContext::new(network_send, log.clone()),
|
||||
log: log.clone(),
|
||||
};
|
||||
|
||||
// spawn handler task
|
||||
// TODO: Handle manual termination of thread
|
||||
// spawn handler task and move the message handler instance into the spawned thread
|
||||
executor.spawn(
|
||||
handler_recv
|
||||
.for_each(move |msg| Ok(handler.handle_message(msg)))
|
||||
@@ -82,17 +76,17 @@ impl<T: BeaconChainTypes + 'static> MessageHandler<T> {
|
||||
match message {
|
||||
// we have initiated a connection to a peer
|
||||
HandlerMessage::PeerDialed(peer_id) => {
|
||||
self.sync.on_connect(peer_id, &mut self.network_context);
|
||||
self.sync.on_connect(peer_id);
|
||||
}
|
||||
// A peer has disconnected
|
||||
HandlerMessage::PeerDisconnected(peer_id) => {
|
||||
self.sync.on_disconnect(peer_id);
|
||||
}
|
||||
// we have received an RPC message request/response
|
||||
// An RPC message request/response has been received
|
||||
HandlerMessage::RPC(peer_id, rpc_event) => {
|
||||
self.handle_rpc_message(peer_id, rpc_event);
|
||||
}
|
||||
// we have received an RPC message request/response
|
||||
// An RPC message request/response has been received
|
||||
HandlerMessage::PubsubMessage(peer_id, gossip) => {
|
||||
self.handle_gossip(peer_id, gossip);
|
||||
}
|
||||
@@ -105,7 +99,7 @@ impl<T: BeaconChainTypes + 'static> MessageHandler<T> {
|
||||
fn handle_rpc_message(&mut self, peer_id: PeerId, rpc_message: RPCEvent) {
|
||||
match rpc_message {
|
||||
RPCEvent::Request(id, req) => self.handle_rpc_request(peer_id, id, req),
|
||||
RPCEvent::Response(_id, resp) => self.handle_rpc_response(peer_id, resp),
|
||||
RPCEvent::Response(id, resp) => self.handle_rpc_response(peer_id, id, resp),
|
||||
RPCEvent::Error(id, error) => self.handle_rpc_error(peer_id, id, error),
|
||||
}
|
||||
}
|
||||
@@ -113,106 +107,81 @@ impl<T: BeaconChainTypes + 'static> MessageHandler<T> {
|
||||
/// A new RPC request has been received from the network.
|
||||
fn handle_rpc_request(&mut self, peer_id: PeerId, request_id: RequestId, request: RPCRequest) {
|
||||
match request {
|
||||
RPCRequest::Hello(hello_message) => self.sync.on_hello_request(
|
||||
peer_id,
|
||||
request_id,
|
||||
hello_message,
|
||||
&mut self.network_context,
|
||||
),
|
||||
RPCRequest::Goodbye(goodbye_reason) => self.sync.on_goodbye(peer_id, goodbye_reason),
|
||||
RPCRequest::BeaconBlockRoots(request) => self.sync.on_beacon_block_roots_request(
|
||||
peer_id,
|
||||
request_id,
|
||||
request,
|
||||
&mut self.network_context,
|
||||
),
|
||||
RPCRequest::BeaconBlockHeaders(request) => self.sync.on_beacon_block_headers_request(
|
||||
peer_id,
|
||||
request_id,
|
||||
request,
|
||||
&mut self.network_context,
|
||||
),
|
||||
RPCRequest::BeaconBlockBodies(request) => self.sync.on_beacon_block_bodies_request(
|
||||
peer_id,
|
||||
request_id,
|
||||
request,
|
||||
&mut self.network_context,
|
||||
),
|
||||
RPCRequest::BeaconChainState(_) => {
|
||||
// We do not implement this endpoint, it is not required and will only likely be
|
||||
// useful for light-client support in later phases.
|
||||
warn!(self.log, "BeaconChainState RPC call is not supported.");
|
||||
RPCRequest::Hello(hello_message) => {
|
||||
self.sync
|
||||
.on_hello_request(peer_id, request_id, hello_message)
|
||||
}
|
||||
RPCRequest::Goodbye(goodbye_reason) => {
|
||||
debug!(
|
||||
self.log, "PeerGoodbye";
|
||||
"peer" => format!("{:?}", peer_id),
|
||||
"reason" => format!("{:?}", goodbye_reason),
|
||||
);
|
||||
self.sync.on_disconnect(peer_id);
|
||||
}
|
||||
RPCRequest::BeaconBlocks(request) => self
|
||||
.sync
|
||||
.on_beacon_blocks_request(peer_id, request_id, request),
|
||||
RPCRequest::RecentBeaconBlocks(request) => self
|
||||
.sync
|
||||
.on_recent_beacon_blocks_request(peer_id, request_id, request),
|
||||
}
|
||||
}
|
||||
|
||||
/// An RPC response has been received from the network.
|
||||
// we match on id and ignore responses past the timeout.
|
||||
fn handle_rpc_response(&mut self, peer_id: PeerId, error_response: RPCErrorResponse) {
|
||||
fn handle_rpc_response(
|
||||
&mut self,
|
||||
peer_id: PeerId,
|
||||
request_id: RequestId,
|
||||
error_response: RPCErrorResponse,
|
||||
) {
|
||||
// an error could have occurred.
|
||||
// TODO: Handle Error gracefully
|
||||
match error_response {
|
||||
RPCErrorResponse::InvalidRequest(error) => {
|
||||
warn!(self.log, "";"peer" => format!("{:?}", peer_id), "Invalid Request" => error.as_string())
|
||||
warn!(self.log, "Peer indicated invalid request";"peer_id" => format!("{:?}", peer_id), "error" => error.as_string())
|
||||
}
|
||||
RPCErrorResponse::ServerError(error) => {
|
||||
warn!(self.log, "";"peer" => format!("{:?}", peer_id), "Server Error" => error.as_string())
|
||||
warn!(self.log, "Peer internal server error";"peer_id" => format!("{:?}", peer_id), "error" => error.as_string())
|
||||
}
|
||||
RPCErrorResponse::Unknown(error) => {
|
||||
warn!(self.log, "";"peer" => format!("{:?}", peer_id), "Unknown Error" => error.as_string())
|
||||
warn!(self.log, "Unknown peer error";"peer" => format!("{:?}", peer_id), "error" => error.as_string())
|
||||
}
|
||||
RPCErrorResponse::Success(response) => {
|
||||
match response {
|
||||
RPCResponse::Hello(hello_message) => {
|
||||
self.sync.on_hello_response(
|
||||
peer_id,
|
||||
hello_message,
|
||||
&mut self.network_context,
|
||||
);
|
||||
self.sync.on_hello_response(peer_id, hello_message);
|
||||
}
|
||||
RPCResponse::BeaconBlockRoots(response) => {
|
||||
self.sync.on_beacon_block_roots_response(
|
||||
peer_id,
|
||||
response,
|
||||
&mut self.network_context,
|
||||
);
|
||||
}
|
||||
RPCResponse::BeaconBlockHeaders(response) => {
|
||||
match self.decode_block_headers(response) {
|
||||
Ok(decoded_block_headers) => {
|
||||
self.sync.on_beacon_block_headers_response(
|
||||
RPCResponse::BeaconBlocks(response) => {
|
||||
match self.decode_beacon_blocks(&response) {
|
||||
Ok(beacon_blocks) => {
|
||||
self.sync.on_beacon_blocks_response(
|
||||
peer_id,
|
||||
decoded_block_headers,
|
||||
&mut self.network_context,
|
||||
request_id,
|
||||
beacon_blocks,
|
||||
);
|
||||
}
|
||||
Err(_e) => {
|
||||
warn!(self.log, "Peer sent invalid block headers";"peer" => format!("{:?}", peer_id))
|
||||
Err(e) => {
|
||||
// TODO: Down-vote Peer
|
||||
warn!(self.log, "Peer sent invalid BEACON_BLOCKS response";"peer" => format!("{:?}", peer_id), "error" => format!("{:?}", e));
|
||||
}
|
||||
}
|
||||
}
|
||||
RPCResponse::BeaconBlockBodies(response) => {
|
||||
match self.decode_block_bodies(response) {
|
||||
Ok(decoded_block_bodies) => {
|
||||
self.sync.on_beacon_block_bodies_response(
|
||||
RPCResponse::RecentBeaconBlocks(response) => {
|
||||
match self.decode_beacon_blocks(&response) {
|
||||
Ok(beacon_blocks) => {
|
||||
self.sync.on_recent_beacon_blocks_response(
|
||||
peer_id,
|
||||
decoded_block_bodies,
|
||||
&mut self.network_context,
|
||||
request_id,
|
||||
beacon_blocks,
|
||||
);
|
||||
}
|
||||
Err(_e) => {
|
||||
warn!(self.log, "Peer sent invalid block bodies";"peer" => format!("{:?}", peer_id))
|
||||
Err(e) => {
|
||||
// TODO: Down-vote Peer
|
||||
warn!(self.log, "Peer sent invalid BEACON_BLOCKS response";"peer" => format!("{:?}", peer_id), "error" => format!("{:?}", e));
|
||||
}
|
||||
}
|
||||
}
|
||||
RPCResponse::BeaconChainState(_) => {
|
||||
// We do not implement this endpoint, it is not required and will only likely be
|
||||
// useful for light-client support in later phases.
|
||||
//
|
||||
// Theoretically, we shouldn't reach this code because we should never send a
|
||||
// beacon state RPC request.
|
||||
warn!(self.log, "BeaconChainState RPC call is not supported.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -221,43 +190,74 @@ impl<T: BeaconChainTypes + 'static> MessageHandler<T> {
|
||||
/// Handle various RPC errors
|
||||
fn handle_rpc_error(&mut self, peer_id: PeerId, request_id: RequestId, error: RPCError) {
|
||||
//TODO: Handle error correctly
|
||||
warn!(self.log, "RPC Error"; "Peer" => format!("{:?}", peer_id), "Request Id" => format!("{}", request_id), "Error" => format!("{:?}", error));
|
||||
warn!(self.log, "RPC Error"; "Peer" => format!("{:?}", peer_id), "request_id" => format!("{}", request_id), "Error" => format!("{:?}", error));
|
||||
}
|
||||
|
||||
/// Handle RPC messages
|
||||
fn handle_gossip(&mut self, peer_id: PeerId, gossip_message: PubsubMessage) {
|
||||
match gossip_message {
|
||||
PubsubMessage::Block(message) => match self.decode_gossip_block(message) {
|
||||
Err(e) => {
|
||||
debug!(self.log, "Invalid Gossiped Beacon Block"; "Peer" => format!("{}", peer_id), "Error" => format!("{:?}", e));
|
||||
}
|
||||
Ok(block) => {
|
||||
let _should_forward_on =
|
||||
self.sync
|
||||
.on_block_gossip(peer_id, block, &mut self.network_context);
|
||||
let _should_forward_on = self.sync.on_block_gossip(peer_id, block);
|
||||
}
|
||||
Err(e) => {
|
||||
debug!(self.log, "Invalid gossiped beacon block"; "peer_id" => format!("{}", peer_id), "Error" => format!("{:?}", e));
|
||||
}
|
||||
},
|
||||
PubsubMessage::Attestation(message) => match self.decode_gossip_attestation(message) {
|
||||
Ok(attestation) => self.sync.on_attestation_gossip(peer_id, attestation),
|
||||
Err(e) => {
|
||||
debug!(self.log, "Invalid Gossiped Attestation"; "Peer" => format!("{}", peer_id), "Error" => format!("{:?}", e));
|
||||
}
|
||||
Ok(attestation) => {
|
||||
self.sync
|
||||
.on_attestation_gossip(peer_id, attestation, &mut self.network_context)
|
||||
debug!(self.log, "Invalid gossiped attestation"; "peer_id" => format!("{}", peer_id), "Error" => format!("{:?}", e));
|
||||
}
|
||||
},
|
||||
PubsubMessage::VoluntaryExit(message) => match self.decode_gossip_exit(message) {
|
||||
Ok(_exit) => {
|
||||
// TODO: Handle exits
|
||||
debug!(self.log, "Received a voluntary exit"; "peer_id" => format!("{}", peer_id) );
|
||||
}
|
||||
Err(e) => {
|
||||
debug!(self.log, "Invalid gossiped exit"; "peer_id" => format!("{}", peer_id), "Error" => format!("{:?}", e));
|
||||
}
|
||||
},
|
||||
PubsubMessage::ProposerSlashing(message) => {
|
||||
match self.decode_gossip_proposer_slashing(message) {
|
||||
Ok(_slashing) => {
|
||||
// TODO: Handle proposer slashings
|
||||
debug!(self.log, "Received a proposer slashing"; "peer_id" => format!("{}", peer_id) );
|
||||
}
|
||||
Err(e) => {
|
||||
debug!(self.log, "Invalid gossiped proposer slashing"; "peer_id" => format!("{}", peer_id), "Error" => format!("{:?}", e));
|
||||
}
|
||||
}
|
||||
}
|
||||
PubsubMessage::AttesterSlashing(message) => {
|
||||
match self.decode_gossip_attestation_slashing(message) {
|
||||
Ok(_slashing) => {
|
||||
// TODO: Handle attester slashings
|
||||
debug!(self.log, "Received an attester slashing"; "peer_id" => format!("{}", peer_id) );
|
||||
}
|
||||
Err(e) => {
|
||||
debug!(self.log, "Invalid gossiped attester slashing"; "peer_id" => format!("{}", peer_id), "Error" => format!("{:?}", e));
|
||||
}
|
||||
}
|
||||
}
|
||||
PubsubMessage::Unknown(message) => {
|
||||
// Received a message from an unknown topic. Ignore for now
|
||||
debug!(self.log, "Unknown Gossip Message"; "Peer" => format!("{}", peer_id), "Message" => format!("{:?}", message));
|
||||
debug!(self.log, "Unknown Gossip Message"; "peer_id" => format!("{}", peer_id), "Message" => format!("{:?}", message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Decoding of blocks and attestations from the network.
|
||||
/* Decoding of gossipsub objects from the network.
|
||||
*
|
||||
* The decoding is done in the message handler as it has access to to a `BeaconChain` and can
|
||||
* therefore apply more efficient logic in decoding and verification.
|
||||
*
|
||||
* TODO: Apply efficient decoding/verification of these objects
|
||||
*/
|
||||
|
||||
/* Gossipsub Domain Decoding */
|
||||
// Note: These are not generics as type-specific verification will need to be applied.
|
||||
fn decode_gossip_block(
|
||||
&self,
|
||||
beacon_block: Vec<u8>,
|
||||
@@ -274,80 +274,39 @@ impl<T: BeaconChainTypes + 'static> MessageHandler<T> {
|
||||
Attestation::from_ssz_bytes(&beacon_block)
|
||||
}
|
||||
|
||||
/// Verifies and decodes the ssz-encoded block bodies received from peers.
|
||||
fn decode_block_bodies(
|
||||
fn decode_gossip_exit(&self, voluntary_exit: Vec<u8>) -> Result<VoluntaryExit, DecodeError> {
|
||||
//TODO: Apply verification before decoding.
|
||||
VoluntaryExit::from_ssz_bytes(&voluntary_exit)
|
||||
}
|
||||
|
||||
fn decode_gossip_proposer_slashing(
|
||||
&self,
|
||||
bodies_response: BeaconBlockBodiesResponse,
|
||||
) -> Result<DecodedBeaconBlockBodiesResponse<T::EthSpec>, DecodeError> {
|
||||
proposer_slashing: Vec<u8>,
|
||||
) -> Result<ProposerSlashing, DecodeError> {
|
||||
//TODO: Apply verification before decoding.
|
||||
ProposerSlashing::from_ssz_bytes(&proposer_slashing)
|
||||
}
|
||||
|
||||
fn decode_gossip_attestation_slashing(
|
||||
&self,
|
||||
attester_slashing: Vec<u8>,
|
||||
) -> Result<AttesterSlashing<T::EthSpec>, DecodeError> {
|
||||
//TODO: Apply verification before decoding.
|
||||
AttesterSlashing::from_ssz_bytes(&attester_slashing)
|
||||
}
|
||||
|
||||
/* Req/Resp Domain Decoding */
|
||||
|
||||
/// Verifies and decodes an ssz-encoded list of `BeaconBlock`s. This list may contain empty
|
||||
/// entries encoded with an SSZ NULL.
|
||||
fn decode_beacon_blocks(
|
||||
&self,
|
||||
beacon_blocks: &[u8],
|
||||
) -> Result<Vec<BeaconBlock<T::EthSpec>>, DecodeError> {
|
||||
if beacon_blocks.is_empty() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
//TODO: Implement faster block verification before decoding entirely
|
||||
let block_bodies = Vec::from_ssz_bytes(&bodies_response.block_bodies)?;
|
||||
Ok(DecodedBeaconBlockBodiesResponse {
|
||||
block_roots: bodies_response
|
||||
.block_roots
|
||||
.expect("Responses must have associated roots"),
|
||||
block_bodies,
|
||||
})
|
||||
}
|
||||
|
||||
/// Verifies and decodes the ssz-encoded block headers received from peers.
|
||||
fn decode_block_headers(
|
||||
&self,
|
||||
headers_response: BeaconBlockHeadersResponse,
|
||||
) -> Result<Vec<BeaconBlockHeader>, DecodeError> {
|
||||
//TODO: Implement faster header verification before decoding entirely
|
||||
Vec::from_ssz_bytes(&headers_response.headers)
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: RPC Rewrite makes this struct fairly pointless
|
||||
pub struct NetworkContext {
|
||||
/// The network channel to relay messages to the Network service.
|
||||
network_send: mpsc::UnboundedSender<NetworkMessage>,
|
||||
/// The `MessageHandler` logger.
|
||||
log: slog::Logger,
|
||||
}
|
||||
|
||||
impl NetworkContext {
|
||||
pub fn new(network_send: mpsc::UnboundedSender<NetworkMessage>, log: slog::Logger) -> Self {
|
||||
Self { network_send, log }
|
||||
}
|
||||
|
||||
pub fn disconnect(&mut self, peer_id: PeerId, reason: GoodbyeReason) {
|
||||
self.send_rpc_request(peer_id, RPCRequest::Goodbye(reason))
|
||||
// TODO: disconnect peers.
|
||||
}
|
||||
|
||||
pub fn send_rpc_request(&mut self, peer_id: PeerId, rpc_request: RPCRequest) {
|
||||
// Note: There is currently no use of keeping track of requests. However the functionality
|
||||
// is left here for future revisions.
|
||||
self.send_rpc_event(peer_id, RPCEvent::Request(0, rpc_request));
|
||||
}
|
||||
|
||||
//TODO: Handle Error responses
|
||||
pub fn send_rpc_response(
|
||||
&mut self,
|
||||
peer_id: PeerId,
|
||||
request_id: RequestId,
|
||||
rpc_response: RPCResponse,
|
||||
) {
|
||||
self.send_rpc_event(
|
||||
peer_id,
|
||||
RPCEvent::Response(request_id, RPCErrorResponse::Success(rpc_response)),
|
||||
);
|
||||
}
|
||||
|
||||
fn send_rpc_event(&mut self, peer_id: PeerId, rpc_event: RPCEvent) {
|
||||
self.send(peer_id, OutgoingMessage::RPC(rpc_event))
|
||||
}
|
||||
|
||||
fn send(&mut self, peer_id: PeerId, outgoing_message: OutgoingMessage) {
|
||||
self.network_send
|
||||
.try_send(NetworkMessage::Send(peer_id, outgoing_message))
|
||||
.unwrap_or_else(|_| {
|
||||
warn!(
|
||||
self.log,
|
||||
"Could not send RPC message to the network service"
|
||||
)
|
||||
});
|
||||
Vec::from_ssz_bytes(&beacon_blocks)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,8 +21,7 @@ pub struct Service<T: BeaconChainTypes> {
|
||||
libp2p_port: u16,
|
||||
_libp2p_exit: oneshot::Sender<()>,
|
||||
_network_send: mpsc::UnboundedSender<NetworkMessage>,
|
||||
_phantom: PhantomData<T>, //message_handler: MessageHandler,
|
||||
//message_handler_send: Sender<HandlerMessage>
|
||||
_phantom: PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T: BeaconChainTypes + 'static> Service<T> {
|
||||
@@ -43,17 +42,19 @@ impl<T: BeaconChainTypes + 'static> Service<T> {
|
||||
message_handler_log,
|
||||
)?;
|
||||
|
||||
let network_log = log.new(o!("Service" => "Network"));
|
||||
// launch libp2p service
|
||||
let libp2p_log = log.new(o!("Service" => "Libp2p"));
|
||||
let libp2p_service = Arc::new(Mutex::new(LibP2PService::new(config.clone(), libp2p_log)?));
|
||||
let libp2p_service = Arc::new(Mutex::new(LibP2PService::new(
|
||||
config.clone(),
|
||||
network_log.clone(),
|
||||
)?));
|
||||
|
||||
// TODO: Spawn thread to handle libp2p messages and pass to message handler thread.
|
||||
let libp2p_exit = spawn_service(
|
||||
libp2p_service.clone(),
|
||||
network_recv,
|
||||
message_handler_send,
|
||||
executor,
|
||||
log,
|
||||
network_log,
|
||||
)?;
|
||||
let network_service = Service {
|
||||
libp2p_service,
|
||||
@@ -166,7 +167,7 @@ fn network_service(
|
||||
},
|
||||
NetworkMessage::Publish { topics, message } => {
|
||||
debug!(log, "Sending pubsub message"; "topics" => format!("{:?}",topics));
|
||||
libp2p_service.lock().swarm.publish(topics, message);
|
||||
libp2p_service.lock().swarm.publish(&topics, message);
|
||||
}
|
||||
},
|
||||
Ok(Async::NotReady) => break,
|
||||
@@ -190,13 +191,13 @@ fn network_service(
|
||||
.map_err(|_| "Failed to send RPC to handler")?;
|
||||
}
|
||||
Libp2pEvent::PeerDialed(peer_id) => {
|
||||
debug!(log, "Peer Dialed: {:?}", peer_id);
|
||||
debug!(log, "Peer Dialed"; "PeerID" => format!("{:?}", peer_id));
|
||||
message_handler_send
|
||||
.try_send(HandlerMessage::PeerDialed(peer_id))
|
||||
.map_err(|_| "Failed to send PeerDialed to handler")?;
|
||||
}
|
||||
Libp2pEvent::PeerDisconnected(peer_id) => {
|
||||
debug!(log, "Peer Disconnected: {:?}", peer_id);
|
||||
debug!(log, "Peer Disconnected"; "PeerID" => format!("{:?}", peer_id));
|
||||
message_handler_send
|
||||
.try_send(HandlerMessage::PeerDisconnected(peer_id))
|
||||
.map_err(|_| "Failed to send PeerDisconnected to handler")?;
|
||||
|
||||
@@ -1,307 +0,0 @@
|
||||
use beacon_chain::{BeaconChain, BeaconChainTypes};
|
||||
use eth2_libp2p::rpc::methods::*;
|
||||
use eth2_libp2p::PeerId;
|
||||
use slog::error;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
use tree_hash::TreeHash;
|
||||
use types::{BeaconBlock, BeaconBlockBody, BeaconBlockHeader, EthSpec, Hash256, Slot};
|
||||
|
||||
/// Provides a queue for fully and partially built `BeaconBlock`s.
|
||||
///
|
||||
/// The queue is fundamentally a `Vec<PartialBeaconBlock>` where no two items have the same
|
||||
/// `item.block_root`. This struct it backed by a `Vec` not a `HashMap` for the following two
|
||||
/// reasons:
|
||||
///
|
||||
/// - When we receive a `BeaconBlockBody`, the only way we can find it's matching
|
||||
/// `BeaconBlockHeader` is to find a header such that `header.beacon_block_body ==
|
||||
/// tree_hash_root(body)`. Therefore, if we used a `HashMap` we would need to use the root of
|
||||
/// `BeaconBlockBody` as the key.
|
||||
/// - It is possible for multiple distinct blocks to have identical `BeaconBlockBodies`. Therefore
|
||||
/// we cannot use a `HashMap` keyed by the root of `BeaconBlockBody`.
|
||||
pub struct ImportQueue<T: BeaconChainTypes> {
|
||||
pub chain: Arc<BeaconChain<T>>,
|
||||
/// Partially imported blocks, keyed by the root of `BeaconBlockBody`.
|
||||
partials: HashMap<Hash256, PartialBeaconBlock<T::EthSpec>>,
|
||||
/// Time before a queue entry is considered state.
|
||||
pub stale_time: Duration,
|
||||
/// Logging
|
||||
log: slog::Logger,
|
||||
}
|
||||
|
||||
impl<T: BeaconChainTypes> ImportQueue<T> {
|
||||
/// Return a new, empty queue.
|
||||
pub fn new(chain: Arc<BeaconChain<T>>, stale_time: Duration, log: slog::Logger) -> Self {
|
||||
Self {
|
||||
chain,
|
||||
partials: HashMap::new(),
|
||||
stale_time,
|
||||
log,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true of the if the `BlockRoot` is found in the `import_queue`.
|
||||
pub fn contains_block_root(&self, block_root: Hash256) -> bool {
|
||||
self.partials.contains_key(&block_root)
|
||||
}
|
||||
|
||||
/// Attempts to complete the `BlockRoot` if it is found in the `import_queue`.
|
||||
///
|
||||
/// Returns an Enum with a `PartialBeaconBlockCompletion`.
|
||||
/// Does not remove the `block_root` from the `import_queue`.
|
||||
pub fn attempt_complete_block(
|
||||
&self,
|
||||
block_root: Hash256,
|
||||
) -> PartialBeaconBlockCompletion<T::EthSpec> {
|
||||
if let Some(partial) = self.partials.get(&block_root) {
|
||||
partial.attempt_complete()
|
||||
} else {
|
||||
PartialBeaconBlockCompletion::MissingRoot
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes the first `PartialBeaconBlock` with a matching `block_root`, returning the partial
|
||||
/// if it exists.
|
||||
pub fn remove(&mut self, block_root: Hash256) -> Option<PartialBeaconBlock<T::EthSpec>> {
|
||||
self.partials.remove(&block_root)
|
||||
}
|
||||
|
||||
/// Flushes all stale entries from the queue.
|
||||
///
|
||||
/// An entry is stale if it has as a `inserted` time that is more than `self.stale_time` in the
|
||||
/// past.
|
||||
pub fn remove_stale(&mut self) {
|
||||
let stale_time = self.stale_time;
|
||||
|
||||
self.partials
|
||||
.retain(|_, partial| partial.inserted + stale_time > Instant::now())
|
||||
}
|
||||
|
||||
/// Returns `true` if `self.chain` has not yet processed this block.
|
||||
pub fn chain_has_not_seen_block(&self, block_root: &Hash256) -> bool {
|
||||
self.chain
|
||||
.is_new_block_root(&block_root)
|
||||
.unwrap_or_else(|_| {
|
||||
error!(self.log, "Unable to determine if block is new.");
|
||||
true
|
||||
})
|
||||
}
|
||||
|
||||
/// Adds the `block_roots` to the partials queue.
|
||||
///
|
||||
/// If a `block_root` is not in the queue and has not been processed by the chain it is added
|
||||
/// to the queue and it's block root is included in the output.
|
||||
pub fn enqueue_block_roots(
|
||||
&mut self,
|
||||
block_roots: &[BlockRootSlot],
|
||||
sender: PeerId,
|
||||
) -> Vec<BlockRootSlot> {
|
||||
// TODO: This will currently not return a `BlockRootSlot` if this root exists but there is no header.
|
||||
// It would be more robust if it did.
|
||||
let new_block_root_slots: Vec<BlockRootSlot> = block_roots
|
||||
.iter()
|
||||
// Ignore any roots already stored in the queue.
|
||||
.filter(|brs| !self.contains_block_root(brs.block_root))
|
||||
// Ignore any roots already processed by the chain.
|
||||
.filter(|brs| self.chain_has_not_seen_block(&brs.block_root))
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
self.partials.extend(
|
||||
new_block_root_slots
|
||||
.iter()
|
||||
.map(|brs| PartialBeaconBlock {
|
||||
slot: brs.slot,
|
||||
block_root: brs.block_root,
|
||||
sender: sender.clone(),
|
||||
header: None,
|
||||
body: None,
|
||||
inserted: Instant::now(),
|
||||
})
|
||||
.map(|partial| (partial.block_root, partial)),
|
||||
);
|
||||
|
||||
new_block_root_slots
|
||||
}
|
||||
|
||||
/// Adds the `headers` to the `partials` queue. Returns a list of `Hash256` block roots for
|
||||
/// which we should use to request `BeaconBlockBodies`.
|
||||
///
|
||||
/// If a `header` is not in the queue and has not been processed by the chain it is added to
|
||||
/// the queue and it's block root is included in the output.
|
||||
///
|
||||
/// If a `header` is already in the queue, but not yet processed by the chain the block root is
|
||||
/// not included in the output and the `inserted` time for the partial record is set to
|
||||
/// `Instant::now()`. Updating the `inserted` time stops the partial from becoming stale.
|
||||
pub fn enqueue_headers(
|
||||
&mut self,
|
||||
headers: Vec<BeaconBlockHeader>,
|
||||
sender: PeerId,
|
||||
) -> Vec<Hash256> {
|
||||
let mut required_bodies: Vec<Hash256> = vec![];
|
||||
|
||||
for header in headers {
|
||||
let block_root = Hash256::from_slice(&header.canonical_root()[..]);
|
||||
|
||||
if self.chain_has_not_seen_block(&block_root)
|
||||
&& !self.insert_header(block_root, header, sender.clone())
|
||||
{
|
||||
// If a body is empty
|
||||
required_bodies.push(block_root);
|
||||
}
|
||||
}
|
||||
|
||||
required_bodies
|
||||
}
|
||||
|
||||
/// If there is a matching `header` for this `body`, adds it to the queue.
|
||||
///
|
||||
/// If there is no `header` for the `body`, the body is simply discarded.
|
||||
pub fn enqueue_bodies(
|
||||
&mut self,
|
||||
bodies: Vec<BeaconBlockBody<T::EthSpec>>,
|
||||
sender: PeerId,
|
||||
) -> Option<Hash256> {
|
||||
let mut last_block_hash = None;
|
||||
for body in bodies {
|
||||
last_block_hash = self.insert_body(body, sender.clone());
|
||||
}
|
||||
|
||||
last_block_hash
|
||||
}
|
||||
|
||||
pub fn enqueue_full_blocks(&mut self, blocks: Vec<BeaconBlock<T::EthSpec>>, sender: PeerId) {
|
||||
for block in blocks {
|
||||
self.insert_full_block(block, sender.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Inserts a header to the queue.
|
||||
///
|
||||
/// If the header already exists, the `inserted` time is set to `now` and not other
|
||||
/// modifications are made.
|
||||
/// Returns true is `body` exists.
|
||||
fn insert_header(
|
||||
&mut self,
|
||||
block_root: Hash256,
|
||||
header: BeaconBlockHeader,
|
||||
sender: PeerId,
|
||||
) -> bool {
|
||||
let mut exists = false;
|
||||
self.partials
|
||||
.entry(block_root)
|
||||
.and_modify(|partial| {
|
||||
partial.header = Some(header.clone());
|
||||
partial.inserted = Instant::now();
|
||||
if partial.body.is_some() {
|
||||
exists = true;
|
||||
}
|
||||
})
|
||||
.or_insert_with(|| PartialBeaconBlock {
|
||||
slot: header.slot,
|
||||
block_root,
|
||||
header: Some(header),
|
||||
body: None,
|
||||
inserted: Instant::now(),
|
||||
sender,
|
||||
});
|
||||
exists
|
||||
}
|
||||
|
||||
/// Updates an existing partial with the `body`.
|
||||
///
|
||||
/// If the body already existed, the `inserted` time is set to `now`.
|
||||
///
|
||||
/// Returns the block hash of the inserted body
|
||||
fn insert_body(
|
||||
&mut self,
|
||||
body: BeaconBlockBody<T::EthSpec>,
|
||||
sender: PeerId,
|
||||
) -> Option<Hash256> {
|
||||
let body_root = Hash256::from_slice(&body.tree_hash_root()[..]);
|
||||
let mut last_root = None;
|
||||
|
||||
self.partials.iter_mut().for_each(|(root, mut p)| {
|
||||
if let Some(header) = &mut p.header {
|
||||
if body_root == header.body_root {
|
||||
p.inserted = Instant::now();
|
||||
p.body = Some(body.clone());
|
||||
p.sender = sender.clone();
|
||||
last_root = Some(*root);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
last_root
|
||||
}
|
||||
|
||||
/// Updates an existing `partial` with the completed block, or adds a new (complete) partial.
|
||||
///
|
||||
/// If the partial already existed, the `inserted` time is set to `now`.
|
||||
fn insert_full_block(&mut self, block: BeaconBlock<T::EthSpec>, sender: PeerId) {
|
||||
let block_root = Hash256::from_slice(&block.canonical_root()[..]);
|
||||
|
||||
let partial = PartialBeaconBlock {
|
||||
slot: block.slot,
|
||||
block_root,
|
||||
header: Some(block.block_header()),
|
||||
body: Some(block.body),
|
||||
inserted: Instant::now(),
|
||||
sender,
|
||||
};
|
||||
|
||||
self.partials
|
||||
.entry(block_root)
|
||||
.and_modify(|existing_partial| *existing_partial = partial.clone())
|
||||
.or_insert(partial);
|
||||
}
|
||||
}
|
||||
|
||||
/// Individual components of a `BeaconBlock`, potentially all that are required to form a full
|
||||
/// `BeaconBlock`.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PartialBeaconBlock<E: EthSpec> {
|
||||
pub slot: Slot,
|
||||
/// `BeaconBlock` root.
|
||||
pub block_root: Hash256,
|
||||
pub header: Option<BeaconBlockHeader>,
|
||||
pub body: Option<BeaconBlockBody<E>>,
|
||||
/// The instant at which this record was created or last meaningfully modified. Used to
|
||||
/// determine if an entry is stale and should be removed.
|
||||
pub inserted: Instant,
|
||||
/// The `PeerId` that last meaningfully contributed to this item.
|
||||
pub sender: PeerId,
|
||||
}
|
||||
|
||||
impl<E: EthSpec> PartialBeaconBlock<E> {
|
||||
/// Attempts to build a block.
|
||||
///
|
||||
/// Does not comsume the `PartialBeaconBlock`.
|
||||
pub fn attempt_complete(&self) -> PartialBeaconBlockCompletion<E> {
|
||||
if self.header.is_none() {
|
||||
PartialBeaconBlockCompletion::MissingHeader(self.slot)
|
||||
} else if self.body.is_none() {
|
||||
PartialBeaconBlockCompletion::MissingBody
|
||||
} else {
|
||||
PartialBeaconBlockCompletion::Complete(
|
||||
self.header
|
||||
.clone()
|
||||
.unwrap()
|
||||
.into_block(self.body.clone().unwrap()),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The result of trying to convert a `BeaconBlock` into a `PartialBeaconBlock`.
|
||||
pub enum PartialBeaconBlockCompletion<E: EthSpec> {
|
||||
/// The partial contains a valid BeaconBlock.
|
||||
Complete(BeaconBlock<E>),
|
||||
/// The partial does not exist.
|
||||
MissingRoot,
|
||||
/// The partial contains a `BeaconBlockRoot` but no `BeaconBlockHeader`.
|
||||
MissingHeader(Slot),
|
||||
/// The partial contains a `BeaconBlockRoot` and `BeaconBlockHeader` but no `BeaconBlockBody`.
|
||||
MissingBody,
|
||||
}
|
||||
725
beacon_node/network/src/sync/manager.rs
Normal file
725
beacon_node/network/src/sync/manager.rs
Normal file
@@ -0,0 +1,725 @@
|
||||
use super::simple_sync::{PeerSyncInfo, FUTURE_SLOT_TOLERANCE};
|
||||
use beacon_chain::{BeaconChain, BeaconChainTypes, BlockProcessingOutcome};
|
||||
use eth2_libp2p::rpc::methods::*;
|
||||
use eth2_libp2p::rpc::RequestId;
|
||||
use eth2_libp2p::PeerId;
|
||||
use slog::{debug, info, trace, warn, Logger};
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ops::{Add, Sub};
|
||||
use std::sync::Arc;
|
||||
use types::{BeaconBlock, EthSpec, Hash256, Slot};
|
||||
|
||||
const MAX_BLOCKS_PER_REQUEST: u64 = 10;
|
||||
|
||||
/// The number of slots that we can import blocks ahead of us, before going into full Sync mode.
|
||||
const SLOT_IMPORT_TOLERANCE: usize = 10;
|
||||
const PARENT_FAIL_TOLERANCE: usize = 3;
|
||||
const PARENT_DEPTH_TOLERANCE: usize = SLOT_IMPORT_TOLERANCE * 2;
|
||||
|
||||
#[derive(PartialEq)]
|
||||
enum BlockRequestsState {
|
||||
Queued,
|
||||
Pending(RequestId),
|
||||
Complete,
|
||||
Failed,
|
||||
}
|
||||
|
||||
struct BlockRequests<T: EthSpec> {
|
||||
target_head_slot: Slot,
|
||||
target_head_root: Hash256,
|
||||
downloaded_blocks: Vec<BeaconBlock<T>>,
|
||||
state: BlockRequestsState,
|
||||
/// Specifies whether the current state is syncing forwards or backwards.
|
||||
forward_sync: bool,
|
||||
/// The current `start_slot` of the batched block request.
|
||||
current_start_slot: Slot,
|
||||
}
|
||||
|
||||
struct ParentRequests<T: EthSpec> {
|
||||
downloaded_blocks: Vec<BeaconBlock<T>>,
|
||||
failed_attempts: usize,
|
||||
last_submitted_peer: PeerId, // to downvote the submitting peer.
|
||||
state: BlockRequestsState,
|
||||
}
|
||||
|
||||
impl<T: EthSpec> BlockRequests<T> {
|
||||
// gets the start slot for next batch
|
||||
// last block slot downloaded plus 1
|
||||
fn update_start_slot(&mut self) {
|
||||
if self.forward_sync {
|
||||
self.current_start_slot += Slot::from(MAX_BLOCKS_PER_REQUEST);
|
||||
} else {
|
||||
self.current_start_slot -= Slot::from(MAX_BLOCKS_PER_REQUEST);
|
||||
}
|
||||
self.state = BlockRequestsState::Queued;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Debug, Clone)]
|
||||
enum ManagerState {
|
||||
Syncing,
|
||||
Regular,
|
||||
Stalled,
|
||||
}
|
||||
|
||||
pub(crate) enum ImportManagerOutcome {
|
||||
Idle,
|
||||
RequestBlocks {
|
||||
peer_id: PeerId,
|
||||
request_id: RequestId,
|
||||
request: BeaconBlocksRequest,
|
||||
},
|
||||
/// Updates information with peer via requesting another HELLO handshake.
|
||||
Hello(PeerId),
|
||||
RecentRequest(PeerId, RecentBeaconBlocksRequest),
|
||||
DownvotePeer(PeerId),
|
||||
}
|
||||
|
||||
pub struct ImportManager<T: BeaconChainTypes> {
|
||||
/// A reference to the underlying beacon chain.
|
||||
chain: Arc<BeaconChain<T>>,
|
||||
state: ManagerState,
|
||||
import_queue: HashMap<PeerId, BlockRequests<T::EthSpec>>,
|
||||
parent_queue: Vec<ParentRequests<T::EthSpec>>,
|
||||
full_peers: HashSet<PeerId>,
|
||||
current_req_id: usize,
|
||||
log: Logger,
|
||||
}
|
||||
|
||||
impl<T: BeaconChainTypes> ImportManager<T> {
|
||||
pub fn new(beacon_chain: Arc<BeaconChain<T>>, log: &slog::Logger) -> Self {
|
||||
ImportManager {
|
||||
chain: beacon_chain.clone(),
|
||||
state: ManagerState::Regular,
|
||||
import_queue: HashMap::new(),
|
||||
parent_queue: Vec::new(),
|
||||
full_peers: HashSet::new(),
|
||||
current_req_id: 0,
|
||||
log: log.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn add_peer(&mut self, peer_id: PeerId, remote: PeerSyncInfo) {
|
||||
// TODO: Improve comments.
|
||||
// initially try to download blocks from our current head
|
||||
// then backwards search all the way back to our finalized epoch until we match on a chain
|
||||
// has to be done sequentially to find next slot to start the batch from
|
||||
|
||||
let local = PeerSyncInfo::from(&self.chain);
|
||||
|
||||
// If a peer is within SLOT_IMPORT_TOLERANCE from our head slot, ignore a batch sync
|
||||
if remote.head_slot.sub(local.head_slot).as_usize() < SLOT_IMPORT_TOLERANCE {
|
||||
trace!(self.log, "Ignoring full sync with peer";
|
||||
"peer" => format!("{:?}", peer_id),
|
||||
"peer_head_slot" => remote.head_slot,
|
||||
"local_head_slot" => local.head_slot,
|
||||
);
|
||||
// remove the peer from the queue if it exists
|
||||
self.import_queue.remove(&peer_id);
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(block_requests) = self.import_queue.get_mut(&peer_id) {
|
||||
// update the target head slot
|
||||
if remote.head_slot > block_requests.target_head_slot {
|
||||
block_requests.target_head_slot = remote.head_slot;
|
||||
}
|
||||
} else {
|
||||
let block_requests = BlockRequests {
|
||||
target_head_slot: remote.head_slot, // this should be larger than the current head. It is checked in the SyncManager before add_peer is called
|
||||
target_head_root: remote.head_root,
|
||||
downloaded_blocks: Vec::new(),
|
||||
state: BlockRequestsState::Queued,
|
||||
forward_sync: true,
|
||||
current_start_slot: self.chain.best_slot(),
|
||||
};
|
||||
self.import_queue.insert(peer_id, block_requests);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn beacon_blocks_response(
|
||||
&mut self,
|
||||
peer_id: PeerId,
|
||||
request_id: RequestId,
|
||||
mut blocks: Vec<BeaconBlock<T::EthSpec>>,
|
||||
) {
|
||||
// find the request
|
||||
let block_requests = match self
|
||||
.import_queue
|
||||
.get_mut(&peer_id)
|
||||
.filter(|r| r.state == BlockRequestsState::Pending(request_id))
|
||||
{
|
||||
Some(req) => req,
|
||||
_ => {
|
||||
// No pending request, invalid request_id or coding error
|
||||
warn!(self.log, "BeaconBlocks response unknown"; "request_id" => request_id);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// If we are syncing up to a target head block, at least the target head block should be
|
||||
// returned. If we are syncing back to our last finalized block the request should return
|
||||
// at least the last block we received (last known block). In diagram form:
|
||||
//
|
||||
// unknown blocks requested blocks downloaded blocks
|
||||
// |-------------------|------------------------|------------------------|
|
||||
// ^finalized slot ^ requested start slot ^ last known block ^ remote head
|
||||
|
||||
if blocks.is_empty() {
|
||||
debug!(self.log, "BeaconBlocks response was empty"; "request_id" => request_id);
|
||||
block_requests.update_start_slot();
|
||||
return;
|
||||
}
|
||||
|
||||
// verify the range of received blocks
|
||||
// Note that the order of blocks is verified in block processing
|
||||
let last_sent_slot = blocks[blocks.len() - 1].slot;
|
||||
if block_requests.current_start_slot > blocks[0].slot
|
||||
|| block_requests
|
||||
.current_start_slot
|
||||
.add(MAX_BLOCKS_PER_REQUEST)
|
||||
< last_sent_slot
|
||||
{
|
||||
//TODO: Downvote peer - add a reason to failed
|
||||
dbg!(&blocks);
|
||||
warn!(self.log, "BeaconBlocks response returned out of range blocks";
|
||||
"request_id" => request_id,
|
||||
"response_initial_slot" => blocks[0].slot,
|
||||
"requested_initial_slot" => block_requests.current_start_slot);
|
||||
// consider this sync failed
|
||||
block_requests.state = BlockRequestsState::Failed;
|
||||
return;
|
||||
}
|
||||
|
||||
// Determine if more blocks need to be downloaded. There are a few cases:
|
||||
// - We have downloaded a batch from our head_slot, which has not reached the remotes head
|
||||
// (target head). Therefore we need to download another sequential batch.
|
||||
// - The latest batch includes blocks that greater than or equal to the target_head slot,
|
||||
// which means we have caught up to their head. We then check to see if the first
|
||||
// block downloaded matches our head. If so, we are on the same chain and can process
|
||||
// the blocks. If not we need to sync back further until we are on the same chain. So
|
||||
// request more blocks.
|
||||
// - We are syncing backwards (from our head slot) and need to check if we are on the same
|
||||
// chain. If so, process the blocks, if not, request more blocks all the way up to
|
||||
// our last finalized slot.
|
||||
|
||||
if block_requests.forward_sync {
|
||||
// append blocks if syncing forward
|
||||
block_requests.downloaded_blocks.append(&mut blocks);
|
||||
} else {
|
||||
// prepend blocks if syncing backwards
|
||||
block_requests.downloaded_blocks.splice(..0, blocks);
|
||||
}
|
||||
|
||||
// does the batch contain the target_head_slot
|
||||
let last_element_index = block_requests.downloaded_blocks.len() - 1;
|
||||
if block_requests.downloaded_blocks[last_element_index].slot
|
||||
>= block_requests.target_head_slot
|
||||
|| !block_requests.forward_sync
|
||||
{
|
||||
// if the batch is on our chain, this is complete and we can then process.
|
||||
// Otherwise start backwards syncing until we reach a common chain.
|
||||
let earliest_slot = block_requests.downloaded_blocks[0].slot;
|
||||
//TODO: Decide which is faster. Reading block from db and comparing or calculating
|
||||
//the hash tree root and comparing.
|
||||
if Some(block_requests.downloaded_blocks[0].canonical_root())
|
||||
== root_at_slot(&self.chain, earliest_slot)
|
||||
{
|
||||
block_requests.state = BlockRequestsState::Complete;
|
||||
return;
|
||||
}
|
||||
|
||||
// not on the same chain, request blocks backwards
|
||||
let state = &self.chain.head().beacon_state;
|
||||
let local_finalized_slot = state
|
||||
.finalized_checkpoint
|
||||
.epoch
|
||||
.start_slot(T::EthSpec::slots_per_epoch());
|
||||
|
||||
// check that the request hasn't failed by having no common chain
|
||||
if local_finalized_slot >= block_requests.current_start_slot {
|
||||
warn!(self.log, "Peer returned an unknown chain."; "request_id" => request_id);
|
||||
block_requests.state = BlockRequestsState::Failed;
|
||||
return;
|
||||
}
|
||||
|
||||
// if this is a forward sync, then we have reached the head without a common chain
|
||||
// and we need to start syncing backwards.
|
||||
if block_requests.forward_sync {
|
||||
// Start a backwards sync by requesting earlier blocks
|
||||
block_requests.forward_sync = false;
|
||||
block_requests.current_start_slot = std::cmp::min(
|
||||
self.chain.best_slot(),
|
||||
block_requests.downloaded_blocks[0].slot,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// update the start slot and re-queue the batch
|
||||
block_requests.update_start_slot();
|
||||
}
|
||||
|
||||
pub fn recent_blocks_response(
|
||||
&mut self,
|
||||
peer_id: PeerId,
|
||||
request_id: RequestId,
|
||||
blocks: Vec<BeaconBlock<T::EthSpec>>,
|
||||
) {
|
||||
// find the request
|
||||
let parent_request = match self
|
||||
.parent_queue
|
||||
.iter_mut()
|
||||
.find(|request| request.state == BlockRequestsState::Pending(request_id))
|
||||
{
|
||||
Some(req) => req,
|
||||
None => {
|
||||
// No pending request, invalid request_id or coding error
|
||||
warn!(self.log, "RecentBeaconBlocks response unknown"; "request_id" => request_id);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// if an empty response is given, the peer didn't have the requested block, try again
|
||||
if blocks.is_empty() {
|
||||
parent_request.failed_attempts += 1;
|
||||
parent_request.state = BlockRequestsState::Queued;
|
||||
parent_request.last_submitted_peer = peer_id;
|
||||
return;
|
||||
}
|
||||
|
||||
// currently only support a single block lookup. Reject any response that has more than 1
|
||||
// block
|
||||
if blocks.len() != 1 {
|
||||
//TODO: Potentially downvote the peer
|
||||
debug!(self.log, "Peer sent more than 1 parent. Ignoring";
|
||||
"peer_id" => format!("{:?}", peer_id),
|
||||
"no_parents" => blocks.len()
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// queue for processing
|
||||
parent_request.state = BlockRequestsState::Complete;
|
||||
}
|
||||
|
||||
pub fn _inject_error(_peer_id: PeerId, _id: RequestId) {
|
||||
//TODO: Remove block state from pending
|
||||
}
|
||||
|
||||
pub fn peer_disconnect(&mut self, peer_id: &PeerId) {
|
||||
self.import_queue.remove(peer_id);
|
||||
self.full_peers.remove(peer_id);
|
||||
self.update_state();
|
||||
}
|
||||
|
||||
pub fn add_full_peer(&mut self, peer_id: PeerId) {
|
||||
debug!(
|
||||
self.log, "Fully synced peer added";
|
||||
"peer" => format!("{:?}", peer_id),
|
||||
);
|
||||
self.full_peers.insert(peer_id);
|
||||
self.update_state();
|
||||
}
|
||||
|
||||
pub fn add_unknown_block(&mut self, block: BeaconBlock<T::EthSpec>, peer_id: PeerId) {
|
||||
// if we are not in regular sync mode, ignore this block
|
||||
if let ManagerState::Regular = self.state {
|
||||
return;
|
||||
}
|
||||
|
||||
// make sure this block is not already being searched for
|
||||
// TODO: Potentially store a hashset of blocks for O(1) lookups
|
||||
for parent_req in self.parent_queue.iter() {
|
||||
if let Some(_) = parent_req
|
||||
.downloaded_blocks
|
||||
.iter()
|
||||
.find(|d_block| d_block == &&block)
|
||||
{
|
||||
// we are already searching for this block, ignore it
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let req = ParentRequests {
|
||||
downloaded_blocks: vec![block],
|
||||
failed_attempts: 0,
|
||||
last_submitted_peer: peer_id,
|
||||
state: BlockRequestsState::Queued,
|
||||
};
|
||||
|
||||
self.parent_queue.push(req);
|
||||
}
|
||||
|
||||
pub(crate) fn poll(&mut self) -> ImportManagerOutcome {
|
||||
loop {
|
||||
// update the state of the manager
|
||||
self.update_state();
|
||||
|
||||
// process potential block requests
|
||||
if let Some(outcome) = self.process_potential_block_requests() {
|
||||
return outcome;
|
||||
}
|
||||
|
||||
// process any complete long-range batches
|
||||
if let Some(outcome) = self.process_complete_batches() {
|
||||
return outcome;
|
||||
}
|
||||
|
||||
// process any parent block lookup-requests
|
||||
if let Some(outcome) = self.process_parent_requests() {
|
||||
return outcome;
|
||||
}
|
||||
|
||||
// process any complete parent lookups
|
||||
let (re_run, outcome) = self.process_complete_parent_requests();
|
||||
if let Some(outcome) = outcome {
|
||||
return outcome;
|
||||
} else if !re_run {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return ImportManagerOutcome::Idle;
|
||||
}
|
||||
|
||||
fn update_state(&mut self) {
|
||||
let previous_state = self.state.clone();
|
||||
self.state = {
|
||||
if !self.import_queue.is_empty() {
|
||||
ManagerState::Syncing
|
||||
} else if !self.full_peers.is_empty() {
|
||||
ManagerState::Regular
|
||||
} else {
|
||||
ManagerState::Stalled
|
||||
}
|
||||
};
|
||||
if self.state != previous_state {
|
||||
info!(self.log, "Syncing state updated";
|
||||
"old_state" => format!("{:?}", previous_state),
|
||||
"new_state" => format!("{:?}", self.state),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn process_potential_block_requests(&mut self) -> Option<ImportManagerOutcome> {
|
||||
// check if an outbound request is required
|
||||
// Managing a fixed number of outbound requests is maintained at the RPC protocol libp2p
|
||||
// layer and not needed here.
|
||||
// If any in queued state we submit a request.
|
||||
|
||||
// remove any failed batches
|
||||
let debug_log = &self.log;
|
||||
self.import_queue.retain(|peer_id, block_request| {
|
||||
if let BlockRequestsState::Failed = block_request.state {
|
||||
debug!(debug_log, "Block import from peer failed";
|
||||
"peer_id" => format!("{:?}", peer_id),
|
||||
"downloaded_blocks" => block_request.downloaded_blocks.len()
|
||||
);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
|
||||
// process queued block requests
|
||||
for (peer_id, block_requests) in self
|
||||
.import_queue
|
||||
.iter_mut()
|
||||
.find(|(_peer_id, req)| req.state == BlockRequestsState::Queued)
|
||||
{
|
||||
let request_id = self.current_req_id;
|
||||
block_requests.state = BlockRequestsState::Pending(request_id);
|
||||
self.current_req_id += 1;
|
||||
|
||||
let request = BeaconBlocksRequest {
|
||||
head_block_root: block_requests.target_head_root,
|
||||
start_slot: block_requests.current_start_slot.as_u64(),
|
||||
count: MAX_BLOCKS_PER_REQUEST,
|
||||
step: 0,
|
||||
};
|
||||
return Some(ImportManagerOutcome::RequestBlocks {
|
||||
peer_id: peer_id.clone(),
|
||||
request,
|
||||
request_id,
|
||||
});
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn process_complete_batches(&mut self) -> Option<ImportManagerOutcome> {
|
||||
let completed_batches = self
|
||||
.import_queue
|
||||
.iter()
|
||||
.filter(|(_peer, block_requests)| block_requests.state == BlockRequestsState::Complete)
|
||||
.map(|(peer, _)| peer)
|
||||
.cloned()
|
||||
.collect::<Vec<PeerId>>();
|
||||
for peer_id in completed_batches {
|
||||
let block_requests = self.import_queue.remove(&peer_id).expect("key exists");
|
||||
match self.process_blocks(block_requests.downloaded_blocks.clone()) {
|
||||
Ok(()) => {
|
||||
//TODO: Verify it's impossible to have empty downloaded_blocks
|
||||
let last_element = block_requests.downloaded_blocks.len() - 1;
|
||||
debug!(self.log, "Blocks processed successfully";
|
||||
"peer" => format!("{:?}", peer_id),
|
||||
"start_slot" => block_requests.downloaded_blocks[0].slot,
|
||||
"end_slot" => block_requests.downloaded_blocks[last_element].slot,
|
||||
"no_blocks" => last_element + 1,
|
||||
);
|
||||
// Re-HELLO to ensure we are up to the latest head
|
||||
return Some(ImportManagerOutcome::Hello(peer_id));
|
||||
}
|
||||
Err(e) => {
|
||||
let last_element = block_requests.downloaded_blocks.len() - 1;
|
||||
warn!(self.log, "Block processing failed";
|
||||
"peer" => format!("{:?}", peer_id),
|
||||
"start_slot" => block_requests.downloaded_blocks[0].slot,
|
||||
"end_slot" => block_requests.downloaded_blocks[last_element].slot,
|
||||
"no_blocks" => last_element + 1,
|
||||
"error" => format!("{:?}", e),
|
||||
);
|
||||
return Some(ImportManagerOutcome::DownvotePeer(peer_id));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn process_parent_requests(&mut self) -> Option<ImportManagerOutcome> {
|
||||
// remove any failed requests
|
||||
let debug_log = &self.log;
|
||||
self.parent_queue.retain(|parent_request| {
|
||||
if parent_request.state == BlockRequestsState::Failed {
|
||||
debug!(debug_log, "Parent import failed";
|
||||
"block" => format!("{:?}",parent_request.downloaded_blocks[0].canonical_root()),
|
||||
"ancestors_found" => parent_request.downloaded_blocks.len()
|
||||
);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
|
||||
// check to make sure there are peers to search for the parent from
|
||||
if self.full_peers.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// check if parents need to be searched for
|
||||
for parent_request in self.parent_queue.iter_mut() {
|
||||
if parent_request.failed_attempts >= PARENT_FAIL_TOLERANCE {
|
||||
parent_request.state = BlockRequestsState::Failed;
|
||||
continue;
|
||||
} else if parent_request.state == BlockRequestsState::Queued {
|
||||
// check the depth isn't too large
|
||||
if parent_request.downloaded_blocks.len() >= PARENT_DEPTH_TOLERANCE {
|
||||
parent_request.state = BlockRequestsState::Failed;
|
||||
continue;
|
||||
}
|
||||
|
||||
parent_request.state = BlockRequestsState::Pending(self.current_req_id);
|
||||
self.current_req_id += 1;
|
||||
let last_element_index = parent_request.downloaded_blocks.len() - 1;
|
||||
let parent_hash = parent_request.downloaded_blocks[last_element_index].parent_root;
|
||||
let req = RecentBeaconBlocksRequest {
|
||||
block_roots: vec![parent_hash],
|
||||
};
|
||||
|
||||
// select a random fully synced peer to attempt to download the parent block
|
||||
let peer_id = self.full_peers.iter().next().expect("List is not empty");
|
||||
|
||||
return Some(ImportManagerOutcome::RecentRequest(peer_id.clone(), req));
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
fn process_complete_parent_requests(&mut self) -> (bool, Option<ImportManagerOutcome>) {
|
||||
// flag to determine if there is more process to drive or if the manager can be switched to
|
||||
// an idle state
|
||||
let mut re_run = false;
|
||||
|
||||
// Find any parent_requests ready to be processed
|
||||
for completed_request in self
|
||||
.parent_queue
|
||||
.iter_mut()
|
||||
.filter(|req| req.state == BlockRequestsState::Complete)
|
||||
{
|
||||
// verify the last added block is the parent of the last requested block
|
||||
let last_index = completed_request.downloaded_blocks.len() - 1;
|
||||
let expected_hash = completed_request.downloaded_blocks[last_index].parent_root;
|
||||
// Note: the length must be greater than 1 so this cannot panic.
|
||||
let block_hash = completed_request.downloaded_blocks[last_index - 1].canonical_root();
|
||||
if block_hash != expected_hash {
|
||||
// remove the head block
|
||||
let _ = completed_request.downloaded_blocks.pop();
|
||||
completed_request.state = BlockRequestsState::Queued;
|
||||
//TODO: Potentially downvote the peer
|
||||
let peer = completed_request.last_submitted_peer.clone();
|
||||
debug!(self.log, "Peer sent invalid parent. Ignoring";
|
||||
"peer_id" => format!("{:?}",peer),
|
||||
"received_block" => format!("{}", block_hash),
|
||||
"expected_parent" => format!("{}", expected_hash),
|
||||
);
|
||||
return (true, Some(ImportManagerOutcome::DownvotePeer(peer)));
|
||||
}
|
||||
|
||||
// try and process the list of blocks up to the requested block
|
||||
while !completed_request.downloaded_blocks.is_empty() {
|
||||
let block = completed_request
|
||||
.downloaded_blocks
|
||||
.pop()
|
||||
.expect("Block must exist exist");
|
||||
match self.chain.process_block(block.clone()) {
|
||||
Ok(BlockProcessingOutcome::ParentUnknown { parent: _ }) => {
|
||||
// need to keep looking for parents
|
||||
completed_request.downloaded_blocks.push(block);
|
||||
completed_request.state = BlockRequestsState::Queued;
|
||||
re_run = true;
|
||||
break;
|
||||
}
|
||||
Ok(BlockProcessingOutcome::Processed { block_root: _ }) => {}
|
||||
Ok(outcome) => {
|
||||
// it's a future slot or an invalid block, remove it and try again
|
||||
completed_request.failed_attempts += 1;
|
||||
trace!(
|
||||
self.log, "Invalid parent block";
|
||||
"outcome" => format!("{:?}", outcome),
|
||||
"peer" => format!("{:?}", completed_request.last_submitted_peer),
|
||||
);
|
||||
completed_request.state = BlockRequestsState::Queued;
|
||||
re_run = true;
|
||||
return (
|
||||
re_run,
|
||||
Some(ImportManagerOutcome::DownvotePeer(
|
||||
completed_request.last_submitted_peer.clone(),
|
||||
)),
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
completed_request.failed_attempts += 1;
|
||||
warn!(
|
||||
self.log, "Parent processing error";
|
||||
"error" => format!("{:?}", e)
|
||||
);
|
||||
completed_request.state = BlockRequestsState::Queued;
|
||||
re_run = true;
|
||||
return (
|
||||
re_run,
|
||||
Some(ImportManagerOutcome::DownvotePeer(
|
||||
completed_request.last_submitted_peer.clone(),
|
||||
)),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// remove any full completed and processed parent chains
|
||||
self.parent_queue.retain(|req| {
|
||||
if req.state == BlockRequestsState::Complete {
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
});
|
||||
(re_run, None)
|
||||
}
|
||||
|
||||
fn process_blocks(&mut self, blocks: Vec<BeaconBlock<T::EthSpec>>) -> Result<(), String> {
|
||||
for block in blocks {
|
||||
let processing_result = self.chain.process_block(block.clone());
|
||||
|
||||
if let Ok(outcome) = processing_result {
|
||||
match outcome {
|
||||
BlockProcessingOutcome::Processed { block_root } => {
|
||||
// The block was valid and we processed it successfully.
|
||||
trace!(
|
||||
self.log, "Imported block from network";
|
||||
"slot" => block.slot,
|
||||
"block_root" => format!("{}", block_root),
|
||||
);
|
||||
}
|
||||
BlockProcessingOutcome::ParentUnknown { parent } => {
|
||||
// blocks should be sequential and all parents should exist
|
||||
trace!(
|
||||
self.log, "ParentBlockUnknown";
|
||||
"parent_root" => format!("{}", parent),
|
||||
"baby_block_slot" => block.slot,
|
||||
);
|
||||
return Err(format!(
|
||||
"Block at slot {} has an unknown parent.",
|
||||
block.slot
|
||||
));
|
||||
}
|
||||
BlockProcessingOutcome::FutureSlot {
|
||||
present_slot,
|
||||
block_slot,
|
||||
} => {
|
||||
if present_slot + FUTURE_SLOT_TOLERANCE >= block_slot {
|
||||
// The block is too far in the future, drop it.
|
||||
trace!(
|
||||
self.log, "FutureBlock";
|
||||
"msg" => "block for future slot rejected, check your time",
|
||||
"present_slot" => present_slot,
|
||||
"block_slot" => block_slot,
|
||||
"FUTURE_SLOT_TOLERANCE" => FUTURE_SLOT_TOLERANCE,
|
||||
);
|
||||
return Err(format!(
|
||||
"Block at slot {} is too far in the future",
|
||||
block.slot
|
||||
));
|
||||
} else {
|
||||
// The block is in the future, but not too far.
|
||||
trace!(
|
||||
self.log, "QueuedFutureBlock";
|
||||
"msg" => "queuing future block, check your time",
|
||||
"present_slot" => present_slot,
|
||||
"block_slot" => block_slot,
|
||||
"FUTURE_SLOT_TOLERANCE" => FUTURE_SLOT_TOLERANCE,
|
||||
);
|
||||
}
|
||||
}
|
||||
BlockProcessingOutcome::FinalizedSlot => {
|
||||
trace!(
|
||||
self.log, "Finalized or earlier block processed";
|
||||
"outcome" => format!("{:?}", outcome),
|
||||
);
|
||||
// block reached our finalized slot or was earlier, move to the next block
|
||||
}
|
||||
_ => {
|
||||
trace!(
|
||||
self.log, "InvalidBlock";
|
||||
"msg" => "peer sent invalid block",
|
||||
"outcome" => format!("{:?}", outcome),
|
||||
);
|
||||
return Err(format!("Invalid block at slot {}", block.slot));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
trace!(
|
||||
self.log, "BlockProcessingFailure";
|
||||
"msg" => "unexpected condition in processing block.",
|
||||
"outcome" => format!("{:?}", processing_result)
|
||||
);
|
||||
return Err(format!(
|
||||
"Unexpected block processing error: {:?}",
|
||||
processing_result
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn root_at_slot<T: BeaconChainTypes>(
|
||||
chain: &Arc<BeaconChain<T>>,
|
||||
target_slot: Slot,
|
||||
) -> Option<Hash256> {
|
||||
chain
|
||||
.rev_iter_block_roots()
|
||||
.find(|(_root, slot)| *slot == target_slot)
|
||||
.map(|(root, _slot)| root)
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
mod import_queue;
|
||||
mod manager;
|
||||
/// Syncing for lighthouse.
|
||||
///
|
||||
/// Stores the various syncing methods for the beacon chain.
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user