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

308 lines
9.1 KiB
Rust
Raw Normal View History

2019-03-21 00:02:52 +00:00
use super::methods::*;
use libp2p::core::{upgrade, InboundUpgrade, OutboundUpgrade, UpgradeInfo};
use ssz::{impl_decode_via_from, impl_encode_via_from, ssz_encode, Decode, Encode};
2019-03-25 05:48:44 +00:00
use std::hash::{Hash, Hasher};
2019-03-14 14:50:59 +00:00
use std::io;
use std::iter;
use tokio::io::{AsyncRead, AsyncWrite};
/// The maximum bytes that can be sent across the RPC.
2019-03-20 23:43:21 +00:00
const MAX_READ_SIZE: usize = 4_194_304; // 4M
2019-03-14 14:50:59 +00:00
/// Implementation of the `ConnectionUpgrade` for the rpc protocol.
#[derive(Debug, Clone)]
pub struct RPCProtocol;
impl UpgradeInfo for RPCProtocol {
type Info = &'static [u8];
type InfoIter = iter::Once<Self::Info>;
#[inline]
fn protocol_info(&self) -> Self::InfoIter {
iter::once(b"/eth/serenity/rpc/1.0.0")
}
}
impl Default for RPCProtocol {
fn default() -> Self {
RPCProtocol
}
}
2019-03-25 05:48:44 +00:00
/// A monotonic counter for ordering `RPCRequest`s.
2019-04-03 05:23:09 +00:00
#[derive(Debug, Clone, Default)]
2019-03-25 05:48:44 +00:00
pub struct RequestId(u64);
impl RequestId {
/// Increment the request id.
pub fn increment(&mut self) {
self.0 += 1
}
/// Return the previous id.
pub fn previous(&self) -> Self {
Self(self.0 - 1)
}
}
impl Eq for RequestId {}
2019-04-03 05:23:09 +00:00
impl PartialEq for RequestId {
fn eq(&self, other: &RequestId) -> bool {
self.0 == other.0
}
}
2019-03-25 05:48:44 +00:00
impl Hash for RequestId {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.hash(state);
}
}
impl From<u64> for RequestId {
fn from(x: u64) -> RequestId {
RequestId(x)
}
}
impl Into<u64> for RequestId {
fn into(self) -> u64 {
self.0
}
}
impl_encode_via_from!(RequestId, u64);
impl_decode_via_from!(RequestId, u64);
2019-03-25 05:48:44 +00:00
2019-03-14 14:50:59 +00:00
/// The RPC types which are sent/received in this protocol.
#[derive(Debug, Clone)]
pub enum RPCEvent {
2019-03-14 14:50:59 +00:00
Request {
2019-03-25 05:48:44 +00:00
id: RequestId,
2019-03-14 14:50:59 +00:00
method_id: u16,
body: RPCRequest,
},
Response {
2019-03-25 05:48:44 +00:00
id: RequestId,
2019-03-14 14:50:59 +00:00
method_id: u16, //TODO: Remove and process decoding upstream
result: RPCResponse,
},
}
impl UpgradeInfo for RPCEvent {
2019-03-14 14:50:59 +00:00
type Info = &'static [u8];
type InfoIter = iter::Once<Self::Info>;
#[inline]
fn protocol_info(&self) -> Self::InfoIter {
iter::once(b"/eth/serenity/rpc/1.0.0")
}
}
2019-04-03 05:23:09 +00:00
type FnDecodeRPCEvent = fn(Vec<u8>, ()) -> Result<RPCEvent, DecodeError>;
2019-03-14 14:50:59 +00:00
impl<TSocket> InboundUpgrade<TSocket> for RPCProtocol
where
TSocket: AsyncRead + AsyncWrite,
{
type Output = RPCEvent;
2019-03-14 14:50:59 +00:00
type Error = DecodeError;
2019-04-03 05:23:09 +00:00
type Future = upgrade::ReadOneThen<upgrade::Negotiated<TSocket>, (), FnDecodeRPCEvent>;
2019-03-14 14:50:59 +00:00
2019-03-26 04:01:05 +00:00
fn upgrade_inbound(self, socket: upgrade::Negotiated<TSocket>, _: Self::Info) -> Self::Future {
2019-03-14 14:50:59 +00:00
upgrade::read_one_then(socket, MAX_READ_SIZE, (), |packet, ()| Ok(decode(packet)?))
}
}
2019-05-13 02:07:32 +00:00
// NOTE!
//
// This code has not been tested, it is a placeholder until we can update to the new libp2p
// spec.
fn decode(packet: Vec<u8>) -> Result<RPCEvent, DecodeError> {
2019-05-13 02:07:32 +00:00
let mut builder = ssz::SszDecoderBuilder::new(&packet);
builder.register_type::<bool>()?;
builder.register_type::<RequestId>()?;
builder.register_type::<u16>()?;
builder.register_type::<Vec<u8>>()?;
let mut decoder = builder.build()?;
let request: bool = decoder.decode_next()?;
let id: RequestId = decoder.decode_next()?;
let method_id: u16 = decoder.decode_next()?;
let bytes: Vec<u8> = decoder.decode_next()?;
2019-03-14 14:50:59 +00:00
if request {
let body = match RPCMethod::from(method_id) {
2019-05-13 02:07:32 +00:00
RPCMethod::Hello => RPCRequest::Hello(HelloMessage::from_ssz_bytes(&bytes)?),
RPCMethod::Goodbye => RPCRequest::Goodbye(GoodbyeReason::from_ssz_bytes(&bytes)?),
2019-03-21 00:02:52 +00:00
RPCMethod::BeaconBlockRoots => {
2019-05-13 02:07:32 +00:00
RPCRequest::BeaconBlockRoots(BeaconBlockRootsRequest::from_ssz_bytes(&bytes)?)
2019-03-21 00:02:52 +00:00
}
RPCMethod::BeaconBlockHeaders => {
2019-05-13 02:07:32 +00:00
RPCRequest::BeaconBlockHeaders(BeaconBlockHeadersRequest::from_ssz_bytes(&bytes)?)
}
2019-03-21 00:16:09 +00:00
RPCMethod::BeaconBlockBodies => {
2019-05-13 02:07:32 +00:00
RPCRequest::BeaconBlockBodies(BeaconBlockBodiesRequest::from_ssz_bytes(&bytes)?)
2019-03-21 00:16:09 +00:00
}
2019-03-21 00:18:47 +00:00
RPCMethod::BeaconChainState => {
2019-05-13 02:07:32 +00:00
RPCRequest::BeaconChainState(BeaconChainStateRequest::from_ssz_bytes(&bytes)?)
2019-03-21 00:18:47 +00:00
}
RPCMethod::Unknown => return Err(DecodeError::UnknownRPCMethod),
2019-03-14 14:50:59 +00:00
};
2019-03-19 12:20:39 +00:00
Ok(RPCEvent::Request {
2019-03-14 14:50:59 +00:00
id,
method_id,
body,
2019-03-19 12:20:39 +00:00
})
2019-03-14 14:50:59 +00:00
}
// we have received a response
else {
let result = match RPCMethod::from(method_id) {
2019-05-13 02:07:32 +00:00
RPCMethod::Hello => RPCResponse::Hello(HelloMessage::from_ssz_bytes(&bytes)?),
2019-03-21 00:02:52 +00:00
RPCMethod::BeaconBlockRoots => {
2019-05-13 02:07:32 +00:00
RPCResponse::BeaconBlockRoots(BeaconBlockRootsResponse::from_ssz_bytes(&bytes)?)
2019-03-21 00:02:52 +00:00
}
RPCMethod::BeaconBlockHeaders => {
2019-05-13 02:07:32 +00:00
RPCResponse::BeaconBlockHeaders(BeaconBlockHeadersResponse::from_ssz_bytes(&bytes)?)
}
2019-03-21 00:16:09 +00:00
RPCMethod::BeaconBlockBodies => {
2019-05-13 02:07:32 +00:00
RPCResponse::BeaconBlockBodies(BeaconBlockBodiesResponse::from_ssz_bytes(&packet)?)
2019-03-21 00:16:09 +00:00
}
2019-03-21 00:18:47 +00:00
RPCMethod::BeaconChainState => {
2019-05-13 02:07:32 +00:00
RPCResponse::BeaconChainState(BeaconChainStateResponse::from_ssz_bytes(&packet)?)
2019-03-21 00:18:47 +00:00
}
2019-05-13 02:07:32 +00:00
// We should never receive a goodbye response; it is invalid.
RPCMethod::Goodbye => return Err(DecodeError::UnknownRPCMethod),
2019-03-21 00:18:47 +00:00
RPCMethod::Unknown => return Err(DecodeError::UnknownRPCMethod),
2019-03-14 14:50:59 +00:00
};
2019-05-13 02:07:32 +00:00
2019-03-19 12:20:39 +00:00
Ok(RPCEvent::Response {
2019-03-14 14:50:59 +00:00
id,
method_id,
result,
2019-03-19 12:20:39 +00:00
})
2019-03-14 14:50:59 +00:00
}
}
impl<TSocket> OutboundUpgrade<TSocket> for RPCEvent
2019-03-14 14:50:59 +00:00
where
TSocket: AsyncWrite,
{
type Output = ();
type Error = io::Error;
2019-03-26 04:01:05 +00:00
type Future = upgrade::WriteOne<upgrade::Negotiated<TSocket>>;
2019-03-14 14:50:59 +00:00
#[inline]
2019-03-26 04:01:05 +00:00
fn upgrade_outbound(self, socket: upgrade::Negotiated<TSocket>, _: Self::Info) -> Self::Future {
2019-03-14 14:50:59 +00:00
let bytes = ssz_encode(&self);
upgrade::write_one(socket, bytes)
}
}
impl Encode for RPCEvent {
2019-05-13 02:07:32 +00:00
fn is_ssz_fixed_len() -> bool {
false
}
// NOTE!
//
// This code has not been tested, it is a placeholder until we can update to the new libp2p
// spec.
fn ssz_append(&self, buf: &mut Vec<u8>) {
let offset = <bool as Encode>::ssz_fixed_len()
+ <u16 as Encode>::ssz_fixed_len()
+ <Vec<u8> as Encode>::ssz_fixed_len();
2019-05-13 02:07:32 +00:00
let mut encoder = ssz::SszEncoder::container(buf, offset);
2019-03-14 14:50:59 +00:00
match self {
RPCEvent::Request {
2019-03-14 14:50:59 +00:00
id,
method_id,
body,
} => {
2019-05-13 02:07:32 +00:00
encoder.append(&true);
encoder.append(id);
encoder.append(method_id);
// Encode the `body` as a `Vec<u8>`.
2019-03-14 14:50:59 +00:00
match body {
RPCRequest::Hello(body) => {
2019-05-13 02:07:32 +00:00
encoder.append(&body.as_ssz_bytes());
}
RPCRequest::Goodbye(body) => {
2019-05-13 02:07:32 +00:00
encoder.append(&body.as_ssz_bytes());
}
RPCRequest::BeaconBlockRoots(body) => {
2019-05-13 02:07:32 +00:00
encoder.append(&body.as_ssz_bytes());
}
RPCRequest::BeaconBlockHeaders(body) => {
2019-05-13 02:07:32 +00:00
encoder.append(&body.as_ssz_bytes());
}
RPCRequest::BeaconBlockBodies(body) => {
2019-05-13 02:07:32 +00:00
encoder.append(&body.as_ssz_bytes());
}
RPCRequest::BeaconChainState(body) => {
2019-05-13 02:07:32 +00:00
encoder.append(&body.as_ssz_bytes());
}
}
2019-03-14 14:50:59 +00:00
}
RPCEvent::Response {
2019-03-14 14:50:59 +00:00
id,
method_id,
result,
} => {
2019-05-13 02:07:32 +00:00
encoder.append(&true);
encoder.append(id);
encoder.append(method_id);
2019-03-14 14:50:59 +00:00
match result {
RPCResponse::Hello(response) => {
2019-05-13 02:07:32 +00:00
encoder.append(&response.as_ssz_bytes());
2019-03-14 14:50:59 +00:00
}
RPCResponse::BeaconBlockRoots(response) => {
2019-05-13 02:07:32 +00:00
encoder.append(&response.as_ssz_bytes());
}
RPCResponse::BeaconBlockHeaders(response) => {
2019-05-13 02:07:32 +00:00
encoder.append(&response.as_ssz_bytes());
}
RPCResponse::BeaconBlockBodies(response) => {
2019-05-13 02:07:32 +00:00
encoder.append(&response.as_ssz_bytes());
}
RPCResponse::BeaconChainState(response) => {
2019-05-13 02:07:32 +00:00
encoder.append(&response.as_ssz_bytes());
}
2019-03-14 14:50:59 +00:00
}
}
}
2019-05-13 02:07:32 +00:00
// Finalize the encoder, writing to `buf`.
encoder.finalize();
2019-03-14 14:50:59 +00:00
}
}
#[derive(Debug)]
2019-03-14 14:50:59 +00:00
pub enum DecodeError {
ReadError(upgrade::ReadOneError),
SSZDecodeError(ssz::DecodeError),
UnknownRPCMethod,
}
impl From<upgrade::ReadOneError> for DecodeError {
#[inline]
fn from(err: upgrade::ReadOneError) -> Self {
DecodeError::ReadError(err)
}
}
impl From<ssz::DecodeError> for DecodeError {
#[inline]
fn from(err: ssz::DecodeError) -> Self {
DecodeError::SSZDecodeError(err)
}
}