Add API version headers and map_fork_name! (#2745)

## 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`.
This commit is contained in:
Michael Sproul
2021-10-28 01:18:04 +00:00
parent 8edd9d45ab
commit 2dc6163043
10 changed files with 295 additions and 146 deletions

View File

@@ -1,19 +1,21 @@
use crate::api_types::{EndpointVersion, ForkVersionedResponse};
use eth2::CONSENSUS_VERSION_HEADER;
use serde::Serialize;
use types::ForkName;
use types::{ForkName, InconsistentFork};
use warp::reply::{self, Reply, WithHeader};
pub const V1: EndpointVersion = EndpointVersion(1);
pub const V2: EndpointVersion = EndpointVersion(2);
pub fn fork_versioned_response<T: Serialize>(
endpoint_version: EndpointVersion,
fork_name: Option<ForkName>,
fork_name: ForkName,
data: T,
) -> Result<ForkVersionedResponse<T>, warp::reject::Rejection> {
let fork_name = if endpoint_version == V1 {
None
} else if endpoint_version == V2 {
fork_name
Some(fork_name)
} else {
return Err(unsupported_version_rejection(endpoint_version));
};
@@ -23,6 +25,15 @@ pub fn fork_versioned_response<T: Serialize>(
})
}
/// Add the `Eth-Consensus-Version` header to a response.
pub fn add_consensus_version_header<T: Reply>(reply: T, fork_name: ForkName) -> WithHeader<T> {
reply::with_header(reply, CONSENSUS_VERSION_HEADER, fork_name.to_string())
}
pub fn inconsistent_fork_rejection(error: InconsistentFork) -> warp::reject::Rejection {
warp_utils::reject::custom_server_error(format!("wrong fork: {:?}", error))
}
pub fn unsupported_version_rejection(version: EndpointVersion) -> warp::reject::Rejection {
warp_utils::reject::custom_bad_request(format!("Unsupported endpoint version: {}", version))
}