## Proposed Changes * Add the `Eth-Consensus-Version` header to the HTTP API for the block and state endpoints. This is part of the v2.1.0 API that was recently released: https://github.com/ethereum/beacon-APIs/pull/170 * Add tests for the above. I refactored the `eth2` crate's helper functions to make this more straight-forward, and introduced some new mixin traits that I think greatly improve readability and flexibility. * Add a new `map_with_fork!` macro which is useful for decoding a superstruct type without naming all its variants. It is now used for SSZ-decoding `BeaconBlock` and `BeaconState`, and for JSON-decoding `SignedBeaconBlock` in the API. ## Additional Info The `map_with_fork!` changes will conflict with the Merge changes, but when resolving the conflict the changes from this branch should be preferred (it is no longer necessary to enumerate every fork). The merge fork _will_ need to be added to `map_fork_name_with`.
51 lines
1.5 KiB
Rust
51 lines
1.5 KiB
Rust
use crate::{types::Accept, Error, CONSENSUS_VERSION_HEADER};
|
|
use reqwest::{header::ACCEPT, RequestBuilder, Response, StatusCode};
|
|
use std::str::FromStr;
|
|
use types::ForkName;
|
|
|
|
/// Trait for converting a 404 error into an `Option<Response>`.
|
|
pub trait ResponseOptional {
|
|
fn optional(self) -> Result<Option<Response>, Error>;
|
|
}
|
|
|
|
impl ResponseOptional for Result<Response, Error> {
|
|
fn optional(self) -> Result<Option<Response>, Error> {
|
|
match self {
|
|
Ok(x) => Ok(Some(x)),
|
|
Err(e) if e.status() == Some(StatusCode::NOT_FOUND) => Ok(None),
|
|
Err(e) => Err(e),
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Trait for extracting the fork name from the headers of a response.
|
|
pub trait ResponseForkName {
|
|
#[allow(clippy::result_unit_err)]
|
|
fn fork_name_from_header(&self) -> Result<Option<ForkName>, ()>;
|
|
}
|
|
|
|
impl ResponseForkName for Response {
|
|
fn fork_name_from_header(&self) -> Result<Option<ForkName>, ()> {
|
|
self.headers()
|
|
.get(CONSENSUS_VERSION_HEADER)
|
|
.map(|fork_name| {
|
|
fork_name
|
|
.to_str()
|
|
.map_err(|_| ())
|
|
.and_then(ForkName::from_str)
|
|
})
|
|
.transpose()
|
|
}
|
|
}
|
|
|
|
/// Trait for adding an "accept" header to a request builder.
|
|
pub trait RequestAccept {
|
|
fn accept(self, accept: Accept) -> RequestBuilder;
|
|
}
|
|
|
|
impl RequestAccept for RequestBuilder {
|
|
fn accept(self, accept: Accept) -> RequestBuilder {
|
|
self.header(ACCEPT, accept.to_string())
|
|
}
|
|
}
|