lighthouse/beacon_node/eth2-libp2p/src/rpc/protocol.rs

334 lines
11 KiB
Rust
Raw Normal View History

2019-03-21 00:02:52 +00:00
use super::methods::*;
2019-07-15 07:07:23 +00:00
use crate::rpc::codec::{
base::{BaseInboundCodec, BaseOutboundCodec},
ssz::{SSZInboundCodec, SSZOutboundCodec},
2019-07-15 08:41:05 +00:00
InboundCodec, OutboundCodec,
};
use futures::{
future::{self, FutureResult},
sink, stream, Sink, Stream,
2019-07-15 07:07:23 +00:00
};
use libp2p::core::{upgrade, InboundUpgrade, OutboundUpgrade, UpgradeInfo};
2019-07-15 07:07:23 +00:00
use ssz::Encode;
use ssz_derive::{Decode, Encode};
2019-03-14 14:50:59 +00:00
use std::io;
2019-07-09 05:44:23 +00:00
use std::time::Duration;
2019-07-15 07:07:23 +00:00
use tokio::codec::Framed;
2019-03-14 14:50:59 +00:00
use tokio::io::{AsyncRead, AsyncWrite};
2019-07-09 05:44:23 +00:00
use tokio::prelude::future::MapErr;
2019-07-15 07:07:23 +00:00
use tokio::prelude::*;
2019-07-15 08:41:05 +00:00
use tokio::timer::timeout;
2019-07-09 05:44:23 +00:00
use tokio::util::FutureExt;
2019-03-14 14:50:59 +00:00
/// The maximum bytes that can be sent across the RPC.
const MAX_RPC_SIZE: usize = 4_194_304; // 4M
/// The protocol prefix the RPC protocol id.
const PROTOCOL_PREFIX: &str = "/eth/serenity/rpc/";
2019-07-06 13:43:44 +00:00
/// The number of seconds to wait for a response before the stream is terminated.
const RESPONSE_TIMEOUT: u64 = 10;
2019-03-14 14:50:59 +00:00
2019-07-15 07:07:23 +00:00
/// Implementation of the `ConnectionUpgrade` for the RPC protocol.
2019-03-14 14:50:59 +00:00
#[derive(Debug, Clone)]
pub struct RPCProtocol;
impl UpgradeInfo for RPCProtocol {
type Info = &'static [u8];
type InfoIter = Vec<Self::Info>;
2019-03-14 14:50:59 +00:00
fn protocol_info(&self) -> Self::InfoIter {
vec![
b"/eth/serenity/rpc/hello/1.0.0/ssz",
b"/eth/serenity/rpc/goodbye/1.0.0/ssz",
b"/eth/serenity/rpc/beacon_block_roots/1.0.0/ssz",
b"/eth/serenity/rpc/beacon_block_headers/1.0.0/ssz",
b"/eth/serenity/rpc/beacon_block_bodies/1.0.0/ssz",
b"/eth/serenity/rpc/beacon_chain_state/1.0.0/ssz",
]
2019-03-14 14:50:59 +00:00
}
}
/// The raw protocol id sent over the wire.
type RawProtocolId = Vec<u8>;
2019-07-04 04:05:01 +00:00
/// Tracks the types in a protocol id.
pub struct ProtocolId {
/// The rpc message type/name.
pub message_name: String,
2019-07-04 04:05:01 +00:00
/// The version of the RPC.
pub version: String,
2019-07-04 04:05:01 +00:00
/// The encoding of the RPC.
pub encoding: String,
}
2019-07-04 04:05:01 +00:00
/// An RPC protocol ID.
impl ProtocolId {
pub fn new(message_name: &str, version: &str, encoding: &str) -> Self {
ProtocolId {
2019-07-09 05:44:23 +00:00
message_name: message_name.into(),
version: version.into(),
2019-07-09 05:44:23 +00:00
encoding: encoding.into(),
}
}
2019-07-04 04:05:01 +00:00
/// Converts a raw RPC protocol id string into an `RPCProtocolId`
2019-07-09 05:44:23 +00:00
pub fn from_bytes(bytes: &[u8]) -> Result<Self, RPCError> {
let protocol_string = String::from_utf8(bytes.to_vec())
.map_err(|_| RPCError::InvalidProtocol("Invalid protocol Id"))?;
2019-07-09 05:44:23 +00:00
let protocol_list: Vec<&str> = protocol_string.as_str().split('/').take(5).collect();
if protocol_list.len() != 5 {
return Err(RPCError::InvalidProtocol("Not enough '/'"));
}
2019-07-04 04:05:01 +00:00
Ok(ProtocolId {
2019-07-09 05:44:23 +00:00
message_name: protocol_list[3].into(),
version: protocol_list[4].into(),
2019-07-09 05:44:23 +00:00
encoding: protocol_list[5].into(),
})
}
}
2019-04-03 05:23:09 +00:00
impl Into<RawProtocolId> for ProtocolId {
2019-07-09 05:44:23 +00:00
fn into(self) -> RawProtocolId {
format!(
"{}/{}/{}/{}",
PROTOCOL_PREFIX, self.message_name, self.version, self.encoding
)
.as_bytes()
2019-07-09 05:44:23 +00:00
.to_vec()
}
}
2019-03-14 14:50:59 +00:00
2019-07-09 05:44:23 +00:00
/* Inbound upgrade */
// The inbound protocol reads the request, decodes it and returns the stream to the protocol
// handler to respond to once ready.
2019-07-15 08:41:05 +00:00
type InboundFramed<TSocket> = Framed<upgrade::Negotiated<TSocket>, InboundCodec>;
type FnAndThen<TSocket> =
fn((Option<RPCRequest>, InboundFramed<TSocket>)) -> FutureResult<RPCRequest, RPCError>;
type FnMapErr<TSocket> = fn(timeout::Error<(RPCError, InboundFramed<TSocket>)>) -> RPCError;
2019-07-09 05:44:23 +00:00
impl<TSocket> InboundUpgrade<TSocket> for RPCProtocol
where
TSocket: AsyncRead + AsyncWrite,
{
2019-07-15 07:07:23 +00:00
type Output = RPCRequest;
2019-07-09 05:44:23 +00:00
type Error = RPCError;
2019-07-15 07:07:23 +00:00
2019-07-15 08:41:05 +00:00
type Future = future::AndThen<
future::MapErr<
timeout::Timeout<stream::StreamFuture<InboundFramed<TSocket>>>,
FnMapErr<TSocket>,
2019-07-09 05:44:23 +00:00
>,
2019-07-15 08:41:05 +00:00
FutureResult<RPCRequest, RPCError>,
FnAndThen<TSocket>,
2019-07-09 05:44:23 +00:00
>;
fn upgrade_inbound(
self,
socket: upgrade::Negotiated<TSocket>,
protocol: &'static [u8],
) -> Self::Future {
2019-07-15 08:41:05 +00:00
// TODO: Verify this
let protocol_id =
ProtocolId::from_bytes(protocol).expect("Can decode all supported protocols");
2019-07-15 07:07:23 +00:00
match protocol_id.encoding.as_str() {
"ssz" | _ => {
2019-07-15 08:41:05 +00:00
let ssz_codec = BaseInboundCodec::new(SSZInboundCodec::new(protocol_id, 4096));
let codec = InboundCodec::SSZ(ssz_codec);
Framed::new(socket, codec)
.into_future()
.timeout(Duration::from_secs(RESPONSE_TIMEOUT))
.map_err(RPCError::from as FnMapErr<TSocket>)
.and_then({
|(madouby, _)| match madouby {
2019-07-15 07:07:23 +00:00
Some(x) => futures::future::ok(x),
None => futures::future::err(RPCError::Custom("Go home".into())),
2019-07-15 08:41:05 +00:00
}
} as FnAndThen<TSocket>)
2019-07-15 07:07:23 +00:00
}
}
2019-07-09 05:44:23 +00:00
}
}
/* Outbound request */
// Combines all the RPC requests into a single enum to implement `UpgradeInfo` and
// `OutboundUpgrade`
#[derive(Debug, Clone)]
pub enum RPCRequest {
Hello(HelloMessage),
Goodbye(Goodbye),
BeaconBlockRoots(BeaconBlockRootsRequest),
BeaconBlockHeaders(BeaconBlockHeadersRequest),
BeaconBlockBodies(BeaconBlockBodiesRequest),
BeaconChainState(BeaconChainStateRequest),
}
2019-03-14 14:50:59 +00:00
impl UpgradeInfo for RPCRequest {
type Info = RawProtocolId;
type InfoIter = Vec<Self::Info>;
2019-07-04 04:05:01 +00:00
// add further protocols as we support more encodings/versions
fn protocol_info(&self) -> Self::InfoIter {
self.supported_protocols()
}
}
2019-07-04 04:05:01 +00:00
/// Implements the encoding per supported protocol for RPCRequest.
impl RPCRequest {
pub fn supported_protocols(&self) -> Vec<RawProtocolId> {
match self {
// add more protocols when versions/encodings are supported
RPCRequest::Hello(_) => vec![ProtocolId::new("hello", "1.0.0", "ssz").into()],
RPCRequest::Goodbye(_) => vec![ProtocolId::new("goodbye", "1.0.0", "ssz").into()],
RPCRequest::BeaconBlockRoots(_) => {
vec![ProtocolId::new("beacon_block_roots", "1.0.0", "ssz").into()]
}
RPCRequest::BeaconBlockHeaders(_) => {
vec![ProtocolId::new("beacon_block_headers", "1.0.0", "ssz").into()]
2019-03-21 00:16:09 +00:00
}
RPCRequest::BeaconBlockBodies(_) => {
vec![ProtocolId::new("beacon_block_bodies", "1.0.0", "ssz").into()]
2019-03-21 00:18:47 +00:00
}
2019-07-09 05:44:23 +00:00
RPCRequest::BeaconChainState(_) => {
vec![ProtocolId::new("beacon_block_state", "1.0.0", "ssz").into()]
2019-03-21 00:16:09 +00:00
}
}
}
/// Encodes the Request object based on the negotiated protocol.
2019-07-09 05:44:23 +00:00
pub fn encode(&self, protocol: ProtocolId) -> Result<Vec<u8>, RPCError> {
// Match on the encoding and in the future, the version
2019-07-09 05:44:23 +00:00
match protocol.encoding.as_str() {
"ssz" => Ok(self.ssz_encode()),
_ => {
return Err(RPCError::Custom(format!(
"Unknown Encoding: {}",
protocol.encoding
)))
2019-03-21 00:18:47 +00:00
}
}
}
2019-07-09 05:44:23 +00:00
fn ssz_encode(&self) -> Vec<u8> {
match self {
RPCRequest::Hello(req) => req.as_ssz_bytes(),
RPCRequest::Goodbye(req) => req.as_ssz_bytes(),
RPCRequest::BeaconBlockRoots(req) => req.as_ssz_bytes(),
RPCRequest::BeaconBlockHeaders(req) => req.as_ssz_bytes(),
RPCRequest::BeaconBlockBodies(req) => req.as_ssz_bytes(),
RPCRequest::BeaconChainState(req) => req.as_ssz_bytes(),
}
}
}
2019-07-15 07:07:23 +00:00
/* RPC Response type - used for outbound upgrades */
2019-07-13 08:35:33 +00:00
2019-07-09 05:44:23 +00:00
/* Outbound upgrades */
2019-07-15 08:41:05 +00:00
type OutboundFramed<TSocket> = Framed<upgrade::Negotiated<TSocket>, OutboundCodec>;
2019-07-09 05:44:23 +00:00
impl<TSocket> OutboundUpgrade<TSocket> for RPCRequest
where
TSocket: AsyncRead + AsyncWrite,
{
2019-07-15 08:41:05 +00:00
type Output = OutboundFramed<TSocket>;
2019-07-09 05:44:23 +00:00
type Error = RPCError;
2019-07-15 08:41:05 +00:00
type Future = sink::Send<OutboundFramed<TSocket>>;
2019-07-09 05:44:23 +00:00
fn upgrade_outbound(
self,
socket: upgrade::Negotiated<TSocket>,
protocol: Self::Info,
) -> Self::Future {
2019-07-15 08:41:05 +00:00
let protocol_id =
ProtocolId::from_bytes(&protocol).expect("Can decode all supported protocols");
match protocol_id.encoding.as_str() {
"ssz" | _ => {
let ssz_codec = BaseOutboundCodec::new(SSZOutboundCodec::new(protocol_id, 4096));
let codec = OutboundCodec::SSZ(ssz_codec);
2019-07-15 07:07:23 +00:00
Framed::new(socket, codec).send(self)
}
}
2019-03-14 14:50:59 +00:00
}
}
/// Error in RPC Encoding/Decoding.
#[derive(Debug)]
pub enum RPCError {
/// Error when reading the packet from the socket.
2019-03-14 14:50:59 +00:00
ReadError(upgrade::ReadOneError),
/// Error when decoding the raw buffer from ssz.
2019-03-14 14:50:59 +00:00
SSZDecodeError(ssz::DecodeError),
2019-07-09 05:44:23 +00:00
/// Invalid Protocol ID.
InvalidProtocol(&'static str),
2019-07-09 05:44:23 +00:00
/// IO Error.
IoError(io::Error),
/// Waiting for a request/response timed out, or timer error'd.
StreamTimeout,
/// Custom message.
Custom(String),
2019-03-14 14:50:59 +00:00
}
impl From<upgrade::ReadOneError> for RPCError {
2019-03-14 14:50:59 +00:00
#[inline]
fn from(err: upgrade::ReadOneError) -> Self {
RPCError::ReadError(err)
2019-03-14 14:50:59 +00:00
}
}
impl From<ssz::DecodeError> for RPCError {
2019-03-14 14:50:59 +00:00
#[inline]
fn from(err: ssz::DecodeError) -> Self {
RPCError::SSZDecodeError(err)
2019-03-14 14:50:59 +00:00
}
}
2019-07-09 05:44:23 +00:00
impl<T> From<tokio::timer::timeout::Error<T>> for RPCError {
fn from(err: tokio::timer::timeout::Error<T>) -> Self {
if err.is_elapsed() {
RPCError::StreamTimeout
} else {
RPCError::Custom("Stream timer failed".into())
}
}
}
impl From<io::Error> for RPCError {
fn from(err: io::Error) -> Self {
RPCError::IoError(err)
}
}
// Error trait is required for `ProtocolsHandler`
impl std::fmt::Display for RPCError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
RPCError::ReadError(ref err) => write!(f, "Error while reading from socket: {}", err),
RPCError::SSZDecodeError(ref err) => write!(f, "Error while decoding ssz: {:?}", err),
RPCError::InvalidProtocol(ref err) => write!(f, "Invalid Protocol: {}", err),
RPCError::IoError(ref err) => write!(f, "IO Error: {}", err),
RPCError::StreamTimeout => write!(f, "Stream Timeout"),
RPCError::Custom(ref err) => write!(f, "{}", err),
}
}
}
impl std::error::Error for RPCError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match *self {
RPCError::ReadError(ref err) => Some(err),
RPCError::SSZDecodeError(ref err) => None,
RPCError::InvalidProtocol(ref err) => None,
RPCError::IoError(ref err) => Some(err),
RPCError::StreamTimeout => None,
RPCError::Custom(ref err) => None,
}
}
}