Skip to content

Commit

Permalink
Merge pull request #433 from chainbound/sidecar-lint
Browse files Browse the repository at this point in the history
chore(bolt-sidecar): add lints
  • Loading branch information
merklefruit authored Nov 27, 2024
2 parents 67efe9f + b34b1f1 commit 629d454
Show file tree
Hide file tree
Showing 18 changed files with 152 additions and 151 deletions.
13 changes: 12 additions & 1 deletion bolt-sidecar/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ alloy = { version = "0.6.4", features = [
"rpc-types-beacon",
"rpc-types-engine",
] }
alloy-rpc-types-engine = { version = "0.6.4", default_features = false, features = ["jwt"] }
alloy-rpc-types-engine = { version = "0.6.4", default_features = false, features = [
"jwt",
] }

# reth
reth-primitives = { git = "https://github.com/paradigmxyz/reth", version = "1.1.1" }
Expand Down Expand Up @@ -86,3 +88,12 @@ ignored = ["ethereum_ssz"]
[[bin]]
name = "bolt-sidecar"
path = "bin/sidecar.rs"

[lints.clippy]
explicit_iter_loop = "warn"
if_not_else = "warn"
manual_let_else = "warn"
match_bool = "warn"
redundant_else = "warn"
unnecessary_self_imports = "warn"
use_self = "warn"
8 changes: 4 additions & 4 deletions bolt-sidecar/src/api/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ where
}

/// Gets the status. Just forwards the request to constraints client and returns the status.
pub async fn status(State(server): State<Arc<BuilderProxyServer<T, P>>>) -> StatusCode {
pub async fn status(State(server): State<Arc<Self>>) -> StatusCode {
let start = std::time::Instant::now();
debug!("Received status request");

Expand All @@ -92,7 +92,7 @@ where
///
/// TODO: intercept this to register Bolt validators on-chain as well.
pub async fn register_validators(
State(server): State<Arc<BuilderProxyServer<T, P>>>,
State(server): State<Arc<Self>>,
Json(registrations): Json<Vec<SignedValidatorRegistration>>,
) -> Result<StatusCode, BuilderApiError> {
debug!("Received register validators request");
Expand All @@ -106,7 +106,7 @@ where
/// In case of a builder or relay failure, we return the locally built block header
/// and store the actual payload so we can return it later.
pub async fn get_header(
State(server): State<Arc<BuilderProxyServer<T, P>>>,
State(server): State<Arc<Self>>,
Path(params): Path<GetHeaderParams>,
) -> Result<Json<VersionedValue<SignedBuilderBid>>, BuilderApiError> {
let start = std::time::Instant::now();
Expand Down Expand Up @@ -171,7 +171,7 @@ where
/// Gets the payload. If we have a locally built payload, we return it.
/// Otherwise, we forward the request to the constraints client.
pub async fn get_payload(
State(server): State<Arc<BuilderProxyServer<T, P>>>,
State(server): State<Arc<Self>>,
req: Request<Body>,
) -> Result<Json<GetPayloadResponse>, BuilderApiError> {
let start = std::time::Instant::now();
Expand Down
22 changes: 11 additions & 11 deletions bolt-sidecar/src/api/commitments/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,48 +60,48 @@ pub enum CommitmentError {
impl IntoResponse for CommitmentError {
fn into_response(self) -> axum::http::Response<axum::body::Body> {
match self {
CommitmentError::Rejected(err) => {
Self::Rejected(err) => {
(StatusCode::BAD_REQUEST, Json(JsonResponse::from_error(-32000, err.to_string())))
.into_response()
}
CommitmentError::Duplicate => {
Self::Duplicate => {
(StatusCode::BAD_REQUEST, Json(JsonResponse::from_error(-32001, self.to_string())))
.into_response()
}
CommitmentError::Internal => (
Self::Internal => (
StatusCode::INTERNAL_SERVER_ERROR,
Json(JsonResponse::from_error(-32002, self.to_string())),
)
.into_response(),
CommitmentError::NoSignature => {
Self::NoSignature => {
(StatusCode::BAD_REQUEST, Json(JsonResponse::from_error(-32003, self.to_string())))
.into_response()
}
CommitmentError::InvalidSignature(err) => {
Self::InvalidSignature(err) => {
(StatusCode::BAD_REQUEST, Json(JsonResponse::from_error(-32004, err.to_string())))
.into_response()
}
CommitmentError::Signature(err) => {
Self::Signature(err) => {
(StatusCode::BAD_REQUEST, Json(JsonResponse::from_error(-32005, err.to_string())))
.into_response()
}
CommitmentError::Consensus(err) => {
Self::Consensus(err) => {
(StatusCode::BAD_REQUEST, Json(JsonResponse::from_error(-32006, err.to_string())))
.into_response()
}
CommitmentError::Validation(err) => {
Self::Validation(err) => {
(StatusCode::BAD_REQUEST, Json(JsonResponse::from_error(-32006, err.to_string())))
.into_response()
}
CommitmentError::MalformedHeader => {
Self::MalformedHeader => {
(StatusCode::BAD_REQUEST, Json(JsonResponse::from_error(-32007, self.to_string())))
.into_response()
}
CommitmentError::UnknownMethod => {
Self::UnknownMethod => {
(StatusCode::BAD_REQUEST, Json(JsonResponse::from_error(-32601, self.to_string())))
.into_response()
}
CommitmentError::InvalidJson(err) => (
Self::InvalidJson(err) => (
StatusCode::BAD_REQUEST,
Json(JsonResponse::from_error(-32600, format!("Invalid request: {err}"))),
)
Expand Down
28 changes: 14 additions & 14 deletions bolt-sidecar/src/api/spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,50 +84,50 @@ pub enum BuilderApiError {
impl IntoResponse for BuilderApiError {
fn into_response(self) -> Response {
match self {
BuilderApiError::FailedRegisteringValidators(error) => {
Self::FailedRegisteringValidators(error) => {
(StatusCode::from_u16(error.code).unwrap(), Json(error)).into_response()
}
BuilderApiError::FailedGettingHeader(error) => {
Self::FailedGettingHeader(error) => {
(StatusCode::from_u16(error.code).unwrap(), Json(error)).into_response()
}
BuilderApiError::FailedGettingPayload(error) => {
Self::FailedGettingPayload(error) => {
(StatusCode::from_u16(error.code).unwrap(), Json(error)).into_response()
}
BuilderApiError::FailedSubmittingConstraints(error) => {
Self::FailedSubmittingConstraints(error) => {
(StatusCode::from_u16(error.code).unwrap(), Json(error)).into_response()
}
BuilderApiError::FailedDelegating(error) => {
Self::FailedDelegating(error) => {
(StatusCode::from_u16(error.code).unwrap(), Json(error)).into_response()
}
BuilderApiError::FailedRevoking(error) => {
Self::FailedRevoking(error) => {
(StatusCode::from_u16(error.code).unwrap(), Json(error)).into_response()
}
BuilderApiError::AxumError(err) => {
Self::AxumError(err) => {
(StatusCode::BAD_REQUEST, err.to_string()).into_response()
}
BuilderApiError::JsonError(err) => {
Self::JsonError(err) => {
(StatusCode::BAD_REQUEST, err.to_string()).into_response()
}
BuilderApiError::FailedToFetchLocalPayload(_) => {
Self::FailedToFetchLocalPayload(_) => {
(StatusCode::NO_CONTENT, self.to_string()).into_response()
}
BuilderApiError::ReqwestError(_) => (
Self::ReqwestError(_) => (
StatusCode::INTERNAL_SERVER_ERROR,
StatusCode::INTERNAL_SERVER_ERROR.canonical_reason().unwrap(),
)
.into_response(),
BuilderApiError::Timeout(_) => (
Self::Timeout(_) => (
StatusCode::GATEWAY_TIMEOUT,
StatusCode::GATEWAY_TIMEOUT.canonical_reason().unwrap(),
)
.into_response(),
BuilderApiError::InvalidFork(err) => {
Self::InvalidFork(err) => {
(StatusCode::BAD_REQUEST, Json(err)).into_response()
}
BuilderApiError::LocalPayloadIntegrity(err) => {
Self::LocalPayloadIntegrity(err) => {
(StatusCode::BAD_REQUEST, err.to_string()).into_response()
}
BuilderApiError::Generic(err) => {
Self::Generic(err) => {
(StatusCode::INTERNAL_SERVER_ERROR, Json(err)).into_response()
}
}
Expand Down
2 changes: 1 addition & 1 deletion bolt-sidecar/src/builder/compat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub(crate) fn to_execution_payload_header(
List::default();

if let Some(withdrawals) = sealed_block.body.withdrawals.as_ref() {
for w in withdrawals.iter() {
for w in withdrawals {
withdrawals_ssz.push(to_consensus_withdrawal(w));
}
}
Expand Down
3 changes: 1 addition & 2 deletions bolt-sidecar/src/builder/payload_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -329,9 +329,8 @@ impl EngineHinter {
// payload response or an error message that we can't parse.
if raw_hint.contains("\"status\":\"VALID\"") {
return Ok(EngineApiHint::ValidPayload);
} else {
return Err(BuilderError::InvalidEngineHint(raw_hint));
}
return Err(BuilderError::InvalidEngineHint(raw_hint));
};

trace!("raw hint: {:?}", raw_hint);
Expand Down
4 changes: 2 additions & 2 deletions bolt-sidecar/src/builder/template.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,7 @@ impl BlockTemplate {

/// Adds a list of constraints to the block template and updates the state diff.
pub fn add_constraints(&mut self, constraints: SignedConstraints) {
for constraint in constraints.message.transactions.iter() {
for constraint in &constraints.message.transactions {
let max_cost = max_transaction_cost(constraint);
self.state_diff
.diffs
Expand All @@ -140,7 +140,7 @@ impl BlockTemplate {
fn remove_constraints_at_index(&mut self, index: usize) {
let constraints = self.signed_constraints_list.remove(index);

for constraint in constraints.message.transactions.iter() {
for constraint in &constraints.message.transactions {
self.state_diff
.diffs
.entry(*constraint.sender().expect("recovered sender"))
Expand Down
39 changes: 15 additions & 24 deletions bolt-sidecar/src/client/constraints_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,18 +64,10 @@ impl ConstraintsClient {
if delegatees.is_empty() {
if available_pubkeys.contains(&validator_pubkey) {
return Some(validator_pubkey);
} else {
return None;
}
} else {
for delegatee in delegatees {
if available_pubkeys.contains(&delegatee) {
return Some(delegatee);
}
}
return None;
}

None
delegatees.into_iter().find(|delegatee| available_pubkeys.contains(delegatee))
}

/// Finds all delegations for the given validator public key.
Expand Down Expand Up @@ -137,20 +129,19 @@ impl BuilderApi for ConstraintsClient {
// registrations to the relay
if self.delegations.is_empty() {
return Ok(());
} else {
let validator_pubkeys =
registrations.iter().map(|r| &r.message.public_key).collect::<HashSet<_>>();

let filtered_delegations = self
.delegations
.iter()
.filter(|d| validator_pubkeys.contains(&d.message.validator_pubkey))
.cloned()
.collect::<Vec<_>>();

if let Err(err) = self.delegate(&filtered_delegations).await {
error!(?err, "Failed to propagate delegations during validator registration");
}
}
let validator_pubkeys =
registrations.iter().map(|r| &r.message.public_key).collect::<HashSet<_>>();

let filtered_delegations = self
.delegations
.iter()
.filter(|d| validator_pubkeys.contains(&d.message.validator_pubkey))
.cloned()
.collect::<Vec<_>>();

if let Err(err) = self.delegate(&filtered_delegations).await {
error!(?err, "Failed to propagate delegations during validator registration");
}

Ok(())
Expand Down
12 changes: 6 additions & 6 deletions bolt-sidecar/src/common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,20 +118,20 @@ impl BlsSecretKeyWrapper {
}

impl<'de> Deserialize<'de> for BlsSecretKeyWrapper {
fn deserialize<D>(deserializer: D) -> Result<BlsSecretKeyWrapper, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let sk = String::deserialize(deserializer)?;
Ok(BlsSecretKeyWrapper::from(sk.as_str()))
Ok(Self::from(sk.as_str()))
}
}

impl From<&str> for BlsSecretKeyWrapper {
fn from(sk: &str) -> Self {
let hex_sk = sk.strip_prefix("0x").unwrap_or(sk);
let sk = SecretKey::from_bytes(&hex::decode(hex_sk).expect("valid hex")).expect("valid sk");
BlsSecretKeyWrapper(sk)
Self(sk)
}
}

Expand Down Expand Up @@ -160,12 +160,12 @@ impl EcdsaSecretKeyWrapper {
}

impl<'de> Deserialize<'de> for EcdsaSecretKeyWrapper {
fn deserialize<D>(deserializer: D) -> Result<EcdsaSecretKeyWrapper, D::Error>
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let sk = String::deserialize(deserializer)?;
Ok(EcdsaSecretKeyWrapper::from(sk.as_str()))
Ok(Self::from(sk.as_str()))
}
}

Expand All @@ -174,7 +174,7 @@ impl From<&str> for EcdsaSecretKeyWrapper {
let hex_sk = sk.strip_prefix("0x").unwrap_or(sk);
let bytes = hex::decode(hex_sk).expect("valid hex");
let sk = SigningKey::from_slice(&bytes).expect("valid sk");
EcdsaSecretKeyWrapper(sk)
Self(sk)
}
}

Expand Down
18 changes: 9 additions & 9 deletions bolt-sidecar/src/config/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,27 +100,27 @@ impl Chain {
/// Get the chain name for the given chain.
pub fn name(&self) -> &'static str {
match self {
Chain::Mainnet => "mainnet",
Chain::Holesky => "holesky",
Chain::Helder => "helder",
Chain::Kurtosis => "kurtosis",
Self::Mainnet => "mainnet",
Self::Holesky => "holesky",
Self::Helder => "helder",
Self::Kurtosis => "kurtosis",
}
}

/// Get the fork version for the given chain.
pub fn fork_version(&self) -> [u8; 4] {
match self {
Chain::Mainnet => [0, 0, 0, 0],
Chain::Holesky => [1, 1, 112, 0],
Chain::Helder => [16, 0, 0, 0],
Chain::Kurtosis => [16, 0, 0, 56],
Self::Mainnet => [0, 0, 0, 0],
Self::Holesky => [1, 1, 112, 0],
Self::Helder => [16, 0, 0, 0],
Self::Kurtosis => [16, 0, 0, 56],
}
}

/// Returns the address of the canonical BoltManager contract for a given chain, if present
pub const fn manager_address(&self) -> Option<Address> {
match self {
Chain::Holesky => Some(MANAGER_ADDRESS_HOLESKY),
Self::Holesky => Some(MANAGER_ADDRESS_HOLESKY),
_ => None,
}
}
Expand Down
2 changes: 1 addition & 1 deletion bolt-sidecar/src/config/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ impl Opts {
pub fn try_parse() -> eyre::Result<Self> {
read_env_file()?;

Ok(Opts::parse())
Ok(Self::parse())
}
}

Expand Down
4 changes: 2 additions & 2 deletions bolt-sidecar/src/driver.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ impl<C: StateFetcher, ECDSA: SignerECDSA> SidecarDriver<C, ECDSA> {

let unsafe_skip_consensus_checks = opts.unsafe_disable_consensus_checks;

Ok(SidecarDriver {
Ok(Self {
unsafe_skip_consensus_checks,
head_tracker,
execution,
Expand Down Expand Up @@ -342,7 +342,7 @@ impl<C: StateFetcher, ECDSA: SignerECDSA> SidecarDriver<C, ECDSA> {
//
// For more information, check out the constraints API docs:
// https://docs.boltprotocol.xyz/technical-docs/api/builder#constraints
for tx in inclusion_request.txs.iter() {
for tx in &inclusion_request.txs {
let tx_type = tx.tx_type();
let message =
ConstraintsMessage::from_tx(signing_pubkey.clone(), target_slot, tx.clone());
Expand Down
Loading

0 comments on commit 629d454

Please sign in to comment.