2020-06-04 10:17:49 -07:00
|
|
|
use super::{Request, Response};
|
|
|
|
use futures::prelude::*;
|
|
|
|
use std::{
|
2020-06-10 03:39:51 -07:00
|
|
|
error,
|
2020-06-04 10:17:49 -07:00
|
|
|
future::Future,
|
|
|
|
pin::Pin,
|
|
|
|
task::{Context, Poll},
|
|
|
|
};
|
|
|
|
use tower::{buffer::Buffer, Service};
|
|
|
|
|
|
|
|
mod block_index;
|
|
|
|
|
|
|
|
#[derive(Default)]
|
|
|
|
struct ZebraState {
|
|
|
|
index: block_index::BlockIndex,
|
|
|
|
}
|
|
|
|
|
2020-06-10 03:39:51 -07:00
|
|
|
type Error = Box<dyn error::Error + Send + Sync + 'static>;
|
|
|
|
|
2020-06-04 10:17:49 -07:00
|
|
|
impl Service<Request> for ZebraState {
|
|
|
|
type Response = Response;
|
2020-06-10 03:39:51 -07:00
|
|
|
type Error = Error;
|
2020-06-04 10:17:49 -07:00
|
|
|
type Future =
|
|
|
|
Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
|
|
|
|
|
|
|
|
fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
|
|
|
|
Poll::Ready(Ok(()))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn call(&mut self, req: Request) -> Self::Future {
|
|
|
|
match req {
|
|
|
|
Request::AddBlock { block } => {
|
2020-06-11 21:52:27 -07:00
|
|
|
let hash = block.as_ref().into();
|
|
|
|
let result = self.index.insert(block).map(|_| Response::Added { hash });
|
2020-06-04 10:17:49 -07:00
|
|
|
|
|
|
|
async { result }.boxed()
|
|
|
|
}
|
|
|
|
Request::GetBlock { hash } => {
|
|
|
|
let result = self
|
|
|
|
.index
|
|
|
|
.get(hash)
|
|
|
|
.map(|block| Response::Block { block })
|
|
|
|
.ok_or_else(|| "block could not be found".into());
|
|
|
|
|
|
|
|
async move { result }.boxed()
|
|
|
|
}
|
|
|
|
Request::GetTip => {
|
|
|
|
let result = self
|
|
|
|
.index
|
|
|
|
.get_tip()
|
|
|
|
.map(|block| block.as_ref().into())
|
|
|
|
.map(|hash| Response::Tip { hash })
|
|
|
|
.ok_or_else(|| "zebra-state contains no blocks".into());
|
|
|
|
|
|
|
|
async move { result }.boxed()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn init() -> impl Service<
|
|
|
|
Request,
|
|
|
|
Response = Response,
|
2020-06-10 03:39:51 -07:00
|
|
|
Error = Error,
|
|
|
|
Future = impl Future<Output = Result<Response, Error>>,
|
2020-06-04 10:17:49 -07:00
|
|
|
> + Send
|
|
|
|
+ Clone
|
|
|
|
+ 'static {
|
|
|
|
Buffer::new(ZebraState::default(), 1)
|
|
|
|
}
|