Skip to content

Commit

Permalink
Improve Error Handling & Linting
Browse files Browse the repository at this point in the history
  • Loading branch information
lucemans committed Nov 21, 2023
1 parent 18f5778 commit 0a085f4
Show file tree
Hide file tree
Showing 9 changed files with 67 additions and 32 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ postgres = "0.19.7"
postgres-types = { version = "0.2.6", features = ["derive", "with-serde_json-1"] }
serde = "1.0.193"
serde_json = "1.0.108"
thiserror = "1.0.50"
tokio = {version = "1", features = ["full"]}
tokio-postgres = "0.7.10"
tower-http = { version = "0.4.3", features = ["cors"] }
Expand Down
7 changes: 6 additions & 1 deletion src/ccip/lookup/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use ethers::abi::ParamType;
use thiserror::Error;

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ResolverFunctionCall {
Expand Down Expand Up @@ -28,11 +29,15 @@ pub enum ResolverFunctionCall {
PubKey,
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[derive(Debug, Clone, PartialEq, Eq, Error)]
pub enum ResolverFunctionCallDecodingError {
#[error("Invalid selector {0}")]
InvalidSelector(String),
#[error("Invalid payload")]
InvalidPayload,
#[error("Invalid namehash")]
InvalidNamehash,
#[error("ABI decode error")]
ABIDecodeError,
}

Expand Down
39 changes: 26 additions & 13 deletions src/gateway/endpoint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use axum::{
response::{IntoResponse, Response},
Json,
};
use thiserror::Error;

use crate::state::GlobalState;

Expand All @@ -16,20 +17,32 @@ pub async fn route(
State(state): State<Arc<GlobalState>>,
Json(request_payload): Json<ResolveCCIPPostPayload>,
) -> impl IntoResponse {
async fn handle(
r: ResolveCCIPPostPayload,
s: Arc<GlobalState>,
) -> Result<GatewayResponse, Response> {
Ok(r.decode()
.unwrap()
.resolve(s.clone())
.await
.unwrap()
.sign(s.clone())
.unwrap())
}

handle(request_payload, state)
.await
.map_err(|x| x.into_response())
}

#[derive(Debug, Error)]
pub enum CCIPEndpointError {
#[error("Invalid prefix {0}")]
DecodeError(#[from] super::payload::ResolverDecodeError),
}

impl IntoResponse for CCIPEndpointError {
fn into_response(self) -> Response {
GatewayResponse::Error(self.to_string()).into_response()
}
}

async fn handle(
payload: ResolveCCIPPostPayload,
state: Arc<GlobalState>,
) -> Result<GatewayResponse, CCIPEndpointError> {
Ok(payload
.decode()?
.resolve(state.clone())
.await
.unwrap()
.sign(state.clone())
.unwrap())
}
43 changes: 30 additions & 13 deletions src/gateway/payload.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,54 @@
use ethers::abi::ParamType;
use serde::Deserialize;
use thiserror::Error;
use tracing::info;

use crate::ccip::lookup::ResolverFunctionCall;
use crate::ccip::lookup::{ResolverFunctionCall, ResolverFunctionCallDecodingError};

use super::{resolution::UnresolvedQuery, response::GatewayResponse};
use super::resolution::UnresolvedQuery;

#[derive(Deserialize, Debug)]
pub struct ResolveCCIPPostPayload {
pub data: String,
pub sender: String,
}

#[derive(Debug, Error)]
pub enum ResolverDecodeError {
#[error("Invalid prefix")]
InvalidPrefix,
#[error("Invalid hex")]
InvalidHex(#[from] hex::FromHexError),
#[error("Invalid utf8")]
InvalidUtf8(#[from] std::string::FromUtf8Error),
#[error("Invalid abi")]
InvalidAbi(#[from] ethers::abi::Error),
#[error("Invalid bytes")]
InvalidBytes,
#[error("Resolver Function Call")]
ResolverFunctionCall(#[from] ResolverFunctionCallDecodingError),
}

impl ResolveCCIPPostPayload {
/// This function handles the initial decoding of the payload
/// It returns the name and the resolver function call that needs to be resolved
/// TODO: Implement error handling
pub fn decode(&self) -> Result<UnresolvedQuery, GatewayResponse> {
pub fn decode(&self) -> Result<UnresolvedQuery, ResolverDecodeError> {
let data = self
.data
.strip_prefix("0x9061b923")
.expect("Prefix is not correct, invld request");
let data = hex::decode(data).expect("Failed to decode to hex, invld request");
.ok_or(ResolverDecodeError::InvalidPrefix)?;

let decoded = ethers::abi::decode(&[ParamType::Bytes, ParamType::Bytes], &data)
.expect("Failed to abi decode, invld request");
let data = hex::decode(data)?;

let decoded = ethers::abi::decode(&[ParamType::Bytes, ParamType::Bytes], &data)?;

let dns_encoded_name = decoded[0]
.clone()
.into_bytes()
.expect("Failed to decode bytes, invld request");
.ok_or(ResolverDecodeError::InvalidBytes)?;

let name =
String::from_utf8(dns_encoded_name).expect("Failed to decode utf8, invld request");
let name = String::from_utf8(dns_encoded_name)?;

let name = crate::utils::dns::decode(&name);

Expand All @@ -41,12 +57,13 @@ impl ResolveCCIPPostPayload {
let rest_of_the_data = decoded[1]
.clone()
.into_bytes()
.expect("Failed to decode bytes, invld request");
.ok_or(ResolverDecodeError::InvalidBytes)?;

let data = ResolverFunctionCall::try_from(rest_of_the_data.as_slice())?;

Ok(UnresolvedQuery {
name,
data: ResolverFunctionCall::try_from(rest_of_the_data.as_slice())
.expect("Failed to decode resolver function call, invld request"),
data,
calldata: self,
})
}
Expand Down
3 changes: 1 addition & 2 deletions src/gateway/resolution.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use std::{collections::HashMap, sync::Arc};
use std::sync::Arc;

use axum::response::IntoResponse;
use ethers::{abi::Token, providers::namehash, utils::keccak256};
use tracing::info;

Expand Down
2 changes: 1 addition & 1 deletion src/gateway/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ impl IntoResponse for GatewayResponse {
(StatusCode::OK, Json(ResolveCCIPPostResponse { data })).into_response()
}
GatewayResponse::Error(message) => (
StatusCode::NOT_IMPLEMENTED,
StatusCode::BAD_REQUEST,
Json(ResolveCCIPPostErrorResponse { message }),
)
.into_response(),
Expand Down
1 change: 0 additions & 1 deletion src/gateway/signing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ use std::sync::Arc;

use ethers::{
abi::{AbiEncode, Token},
signers::Signer,
types::{H160, U256, U64},
utils::keccak256,
};
Expand Down
2 changes: 1 addition & 1 deletion src/http.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::{net::SocketAddr, sync::Arc};

use crate::{database::Database, state::GlobalState};
use crate::state::GlobalState;
use axum::{
routing::{get, post},
Router, Server,
Expand Down

0 comments on commit 0a085f4

Please sign in to comment.