Skip to content
This repository has been archived by the owner on Aug 9, 2023. It is now read-only.

ci: Add clippy + fixing clippy errors #14

Merged
merged 6 commits into from
Jul 21, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,22 @@ jobs:
- run: |
rustup component add rustfmt
cargo fmt --all -- --check

clippy:
name: cargo clippy
runs-on: ubuntu-latest
container:
image: rust:latest
steps:
- uses: actions/checkout@v3
- uses: actions/cache@v3
with:
path: |
~/.cargo/registry
~/.cargo/git
target
key: ${{ runner.os }}-cargo-clippy
- run: |
rustup component add clippy
# Temporarily allowing dead-code, while denying all other warnings
cargo clippy --all-features --all-targets -- -A dead-code -D warnings
4 changes: 2 additions & 2 deletions native/src/signature_verification.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ impl SignatureVerifier {
message: &[u8],
signature: &RecoverableSignature,
) -> Result<bool, &'static str> {
let message = Message::from_slice(&keccak(&message).to_fixed_bytes()).unwrap();
let message = Message::from_slice(&keccak(message).to_fixed_bytes()).unwrap();

match self.signer.load().as_ref() {
// If we already have the public key we can do the fast path.
Expand All @@ -35,7 +35,7 @@ impl SignatureVerifier {
// verify method instead of the slow recover method.
Signer::Address(addr) => {
let recovered_signer = SECP256K1
.recover(&message, &signature)
.recover(&message, signature)
.map_err(|_| "Failed to recover signature")?;

let ser = recovered_signer.serialize_uncompressed();
Expand Down
4 changes: 2 additions & 2 deletions service/src/common/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ pub type Address = String;

/// Converts an address to checksum format and returns a typed instance.
pub fn to_address(s: impl AsRef<str>) -> Address {
let mut address = s.as_ref().to_ascii_lowercase();
let hash = &Keccak256::digest(&address);
let address = s.as_ref().to_ascii_lowercase();
let hash = &Keccak256::digest(address);
hex::encode(hash)
}

Expand Down
1 change: 0 additions & 1 deletion service/src/common/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ use diesel::prelude::*;
use diesel::r2d2::{ConnectionManager, Pool};
use dotenvy::dotenv;
use std::env;
use std::sync::{Arc, RwLock};

pub type PgPool = Pool<ConnectionManager<PgConnection>>;

Expand Down
4 changes: 0 additions & 4 deletions service/src/common/indexer_error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -314,10 +314,6 @@ impl IndexerError {
pub fn cause(&self) -> Option<&IndexerErrorCause> {
self.cause.as_ref()
}

pub fn to_string(&self) -> String {
format!("{}: {}", self.code.message(), self.explanation)
}
}

// pub fn indexer_error(code: IndexerErrorCode, cause: Option<IndexerErrorCause>) -> IndexerError {
Expand Down
22 changes: 6 additions & 16 deletions service/src/config.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
use autometrics::autometrics;
use clap::{command, error::ErrorKind, Args, CommandFactory, Parser, ValueEnum};
use ethers::signers::WalletError;

use serde::{Deserialize, Serialize};
use std::collections::HashSet;
use tracing::{debug, info};

use crate::{
common::address::build_wallet,
query_processor::QueryError,
util::{init_tracing, wallet_address},
};
use crate::{query_processor::QueryError, util::init_tracing};

#[derive(Clone, Debug, Parser, Serialize, Deserialize, Default)]
#[clap(
Expand Down Expand Up @@ -288,18 +281,15 @@ pub enum ConfigError {
Other(anyhow::Error),
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize)]
#[derive(
Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Serialize, Deserialize, Default,
)]
pub enum LogLevel {
Trace,
#[default]
Debug,
Info,
Warn,
Error,
Fatal,
}

impl Default for LogLevel {
fn default() -> Self {
LogLevel::Debug
}
}
13 changes: 3 additions & 10 deletions service/src/graph_node.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,4 @@
use anyhow;
use bs58;
use ethers_core::abi::AbiEncode;
use log::{debug, error, info, trace, warn, Log};
use regex::Regex;
use reqwest::{header, Client, Url};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::query_processor::UnattestedQueryResult;

Expand Down Expand Up @@ -34,13 +27,13 @@ impl GraphNodeInstance {
) -> Result<UnattestedQueryResult, reqwest::Error> {
let request = self
.client
.post(&format!("{}/subgraphs/id/{}", self.base_url, endpoint))
.post(format!("{}/subgraphs/id/{}", self.base_url, endpoint))
.body(data.clone())
.header(header::CONTENT_TYPE, "application/json");

let response = request.send().await?.text().await?;
Ok(UnattestedQueryResult {
graphQLResponse: response,
graphql_response: response,
attestable: true,
})
}
Expand All @@ -61,7 +54,7 @@ impl GraphNodeInstance {
// actually parse the JSON for the graphQL schema
let response_text = response.text().await?;
Ok(UnattestedQueryResult {
graphQLResponse: response_text,
graphql_response: response_text,
attestable: false,
})
}
Expand Down
20 changes: 6 additions & 14 deletions service/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,25 @@
use async_graphql::{EmptyMutation, EmptySubscription, Schema};
use axum::{
error_handling::HandleErrorLayer,
extract::{Path, Query},
http::{Method, StatusCode},
response::IntoResponse,
routing::{get, patch},
Json,
routing::get,
};
use axum::{routing::post, Extension, Router, Server};
use dotenvy::dotenv;
use model::QueryRoot;
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, sync::RwLock};
use std::{env, error::Error, sync::Arc, time::Duration};

use std::time::Duration;
use tower::{BoxError, ServiceBuilder};
use tower_http::cors::CorsLayer;
use tracing::info;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

use util::package_version;
use uuid::Uuid;

use crate::{
config::Cli,
metrics::handle_serve_metrics,
query_processor::{FreeQuery, QueryProcessor, SubgraphDeploymentID},
util::public_key,
config::Cli, metrics::handle_serve_metrics, query_processor::QueryProcessor, util::public_key,
};
// use server::{ServerOptions, index, subgraph_queries, network_queries};
use common::database::create_pg_pool;

use server::{routes, ServerOptions};

mod common;
Expand Down
4 changes: 1 addition & 3 deletions service/src/metrics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,7 @@ use axum::routing::get;
use axum::Router;
use once_cell::sync::Lazy;
use prometheus::{core::Collector, Registry};
use prometheus::{
linear_buckets, HistogramOpts, HistogramVec, IntCounterVec, IntGauge, IntGaugeVec, Opts,
};
use prometheus::{linear_buckets, HistogramOpts, HistogramVec, IntCounterVec, Opts};
use std::{net::SocketAddr, str::FromStr};
use tracing::{debug, info};

Expand Down
24 changes: 10 additions & 14 deletions service/src/query_fee/allocations.rs
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
use crate::common::{
address::{to_address, Address},
indexer_error,
indexer_error::{IndexerError, IndexerErrorCode},
};
use async_graphql::{Error, Object, SimpleObject, ID};

use async_trait::async_trait;
use bigdecimal::BigDecimal;
// use ethers::types::Address;
use super::ReceiptManager;
use crate::common::{database::PgPool, indexer_error::indexer_error};
use diesel::pg::PgConnection;
use ethers_core::{types::U256, utils::hex};

use ethers_core::utils::hex;
use native::signature_verification::SignatureVerifier;
use num_bigint::BigUint;

use regex::Regex;
use secp256k1::{
recovery::{RecoverableSignature, RecoveryId},
Message, PublicKey, Secp256k1, VerifyOnly,
};
use std::convert::TryInto;
use secp256k1::recovery::{RecoverableSignature, RecoveryId};

use std::{collections::HashMap, str::FromStr, sync::Arc};

type QueryFees = HashMap<String, HashMap<String, BigDecimal>>;
Expand All @@ -29,7 +25,7 @@ fn read_number(data: &str, start: usize, end: usize) -> BigDecimal {
BigDecimal::from_str(&hex_string).unwrap()
}

static ALLOCATION_RECEIPT_VALIDATOR: &'static str = "^[0-9A-Fa-f]{264}$";
static ALLOCATION_RECEIPT_VALIDATOR: &str = "^[0-9A-Fa-f]{264}$";

async fn validate_signature(
signer: &SignatureVerifier,
Expand All @@ -44,7 +40,7 @@ async fn validate_signature(
.unwrap();

if signer.verify(message, &signature).is_err() {
let code = IndexerErrorCode::IE031;
let _code = IndexerErrorCode::IE031;

return Err(indexer_error(IndexerErrorCode::IE031));
}
Expand Down Expand Up @@ -139,8 +135,8 @@ impl AllocationReceiptManager {
) -> Result<(String, Address, BigDecimal), IndexerError> {
// let id = &receipt_data[104..134].as_bytes(); // 15 bytes
let id = receipt_data[104..134].to_owned(); // 15 bytes
let allocation = to_address(&("0x".to_owned() + &receipt_data[0..40])); // 20 bytes
let fees = read_number(&receipt_data, 40, 104);
let allocation = to_address("0x".to_owned() + &receipt_data[0..40]); // 20 bytes
let fees = read_number(receipt_data, 40, 104);
Ok((id, allocation, fees))
}

Expand Down
6 changes: 3 additions & 3 deletions service/src/query_fee/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,14 @@ impl OutputType for BigDecimalWrapper {
todo!()
}

fn create_type_info(registry: &mut async_graphql::registry::Registry) -> String {
fn create_type_info(_registry: &mut async_graphql::registry::Registry) -> String {
todo!()
}

fn resolve<'life0, 'life1, 'life2, 'life3, 'async_trait>(
&'life0 self,
ctx: &'life1 async_graphql::ContextSelectionSet<'life2>,
field: &'life3 async_graphql::Positioned<async_graphql::parser::types::Field>,
_ctx: &'life1 async_graphql::ContextSelectionSet<'life2>,
_field: &'life3 async_graphql::Positioned<async_graphql::parser::types::Field>,
) -> core::pin::Pin<
Box<
dyn core::future::Future<Output = async_graphql::ServerResult<async_graphql::Value>>
Expand Down
29 changes: 12 additions & 17 deletions service/src/query_processor.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
use anyhow;
use bs58;
use ethers_core::abi::AbiEncode;
use log::{debug, error, info, trace, warn, Log};
use log::error;
use regex::Regex;
use reqwest::{header, Client, Url};
use reqwest::{Client, Url};
use serde::{Deserialize, Serialize};
use thiserror::Error;

use crate::graph_node::GraphNodeInstance;

Expand All @@ -27,17 +24,17 @@ impl SubgraphName {
/// Implement SubgraphName String representation
impl ToString for SubgraphName {
fn to_string(&self) -> String {
format!("{}", self.value)
self.value.to_string()
}
}

/// Security: Input validation
pub fn bytes32Check() -> Regex {
pub fn bytes32_check() -> Regex {
Regex::new(r"^0x[0-9a-f]{64}$").unwrap()
}

/// Security: Input Validation
pub fn multiHashCheck() -> Regex {
pub fn multihash_check() -> Regex {
Regex::new(r"^Qm[1-9a-km-zA-HJ-NP-Z]{44}$").unwrap()
}

Expand All @@ -53,16 +50,14 @@ impl SubgraphDeploymentID {
/// Assume byte 32
/// Later add Security: Input validation
pub fn new(id: String) -> SubgraphDeploymentID {
SubgraphDeploymentID {
value: id.to_owned(),
}
SubgraphDeploymentID { value: id }
}

fn bytes32(&self) -> String {
return self.value.clone();
self.value.clone()
}

fn ipfsHash(&self) -> String {
fn ipfs_hash(&self) -> String {
let value = self.value.clone();
let mut bytes: Vec<u8> = vec![0x12, 0x20];
bytes.extend(value.as_bytes().to_vec());
Expand All @@ -73,7 +68,7 @@ impl SubgraphDeploymentID {

impl ToString for SubgraphDeploymentID {
fn to_string(&self) -> String {
format!("{}", self.value)
self.value.to_string()
}
}
pub struct Signature {
Expand All @@ -83,13 +78,13 @@ pub struct Signature {
}

pub struct QueryResult {
graphQLResponse: String,
graphql_response: String,
attestation: Option<Signature>,
}

#[derive(Debug, Clone)]
pub struct UnattestedQueryResult {
pub graphQLResponse: String,
pub graphql_response: String,
pub attestable: bool,
}

Expand Down Expand Up @@ -130,7 +125,7 @@ pub struct QueryProcessor {

impl QueryProcessor {
pub fn new(graph_node_endpoint: &str, network_subgraph_endpoint: &str) -> QueryProcessor {
let graph_node = GraphNodeInstance::new(graph_node_endpoint.clone());
let graph_node = GraphNodeInstance::new(graph_node_endpoint);

QueryProcessor {
client: Client::new(),
Expand Down
6 changes: 2 additions & 4 deletions service/src/server/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
use crate::{
query_processor::{FreeQuery, QueryProcessor, SubgraphDeploymentID},
util::PackageVersion,
};
use crate::{query_processor::QueryProcessor, util::PackageVersion};

pub mod routes;

Expand All @@ -20,6 +17,7 @@ pub struct ServerOptions {
}

impl ServerOptions {
#[allow(clippy::too_many_arguments)]
pub fn new(
port: Option<u32>,
release: PackageVersion,
Expand Down
Loading