Skip to content

Commit

Permalink
refactor(all): remove ethers and use alloy
Browse files Browse the repository at this point in the history
Signed-off-by: Gustavo Inacio <[email protected]>
  • Loading branch information
gusinacio committed Aug 2, 2024
1 parent 4cbeb32 commit 3512620
Show file tree
Hide file tree
Showing 27 changed files with 318 additions and 339 deletions.
6 changes: 1 addition & 5 deletions tap_aggregator/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,7 @@ anyhow = "1.0.70"
tokio = { version = "1.27.0", features = ["macros", "signal"] }
tap_core = { version = "1.0.0", path = "../tap_core" }
jsonrpsee = { version = "0.18.0", features = ["server", "macros"] }
ethers-signers = "2.0.3"
clap = { version = "4.2.4", features = ["derive", "env"] }
ethers-core = "2.0.3"
serde = { version = "1.0.163", features = ["derive"] }
serde_json = { version = "1.0.96", features = ["raw_value"] }
strum = { version = "0.24.1", features = ["strum_macros", "derive"] }
Expand All @@ -28,9 +26,7 @@ prometheus = "0.13.3"
axum = "0.6.18"
futures-util = "0.3.28"
lazy_static = "1.4.0"
alloy-sol-types = { version = "0.7.0", features = ["eip712-serde"] }
alloy-primitives = { version = "0.7.0", features = ["serde"] }
ethereum-types = "0.14.1"
alloy = { version = "0.2.0", features = ["full"] }
ruint = "1.10.1"

[dev-dependencies]
Expand Down
43 changes: 21 additions & 22 deletions tap_aggregator/src/aggregator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@

use std::collections::{hash_set, HashSet};

use alloy_primitives::Address;
use alloy_sol_types::{Eip712Domain, SolStruct};
use alloy::{
dyn_abi::Eip712Domain, primitives::Address, signers::local::PrivateKeySigner,
sol_types::SolStruct,
};
use anyhow::{bail, Ok, Result};
use ethers_core::types::Signature;
use ethers_signers::LocalWallet;

use tap_core::{
rav::ReceiptAggregateVoucher, receipt::Receipt, signed_message::EIP712SignedMessage,
Expand All @@ -17,7 +17,7 @@ pub fn check_and_aggregate_receipts(
domain_separator: &Eip712Domain,
receipts: &[EIP712SignedMessage<Receipt>],
previous_rav: Option<EIP712SignedMessage<ReceiptAggregateVoucher>>,
wallet: &LocalWallet,
wallet: &PrivateKeySigner,
accepted_addresses: &HashSet<Address>,
) -> Result<EIP712SignedMessage<ReceiptAggregateVoucher>> {
check_signatures_unique(receipts)?;
Expand Down Expand Up @@ -99,11 +99,15 @@ fn check_allocation_id(
}

fn check_signatures_unique(receipts: &[EIP712SignedMessage<Receipt>]) -> Result<()> {
let mut receipt_signatures: hash_set::HashSet<Signature> = hash_set::HashSet::new();
let mut receipt_signatures: hash_set::HashSet<[u8; 65]> = hash_set::HashSet::new();
for receipt in receipts.iter() {
let signature = receipt.signature;
let signature = receipt.signature.as_bytes();
if !receipt_signatures.insert(signature) {
return Err(tap_core::Error::DuplicateReceiptSignature(signature.to_string()).into());
return Err(tap_core::Error::DuplicateReceiptSignature(format!(
"{:?}",
receipt.signature
))
.into());
}
}
Ok(())
Expand Down Expand Up @@ -133,21 +137,16 @@ fn check_receipt_timestamps(
mod tests {
use std::str::FromStr;

use alloy_primitives::Address;
use alloy_sol_types::Eip712Domain;
use ethers_signers::{LocalWallet, Signer};
use alloy::{dyn_abi::Eip712Domain, primitives::Address, signers::local::PrivateKeySigner};
use rstest::*;

use crate::aggregator;
use tap_core::{receipt::Receipt, signed_message::EIP712SignedMessage, tap_eip712_domain};

#[fixture]
fn keys() -> (LocalWallet, Address) {
let wallet = LocalWallet::from_str(
"1ab42cc412b618bdea3a599e3c9bae199ebf030895b039e9db1e30dafb12b727",
)
.unwrap();
let address: [u8; 20] = wallet.address().into();
fn keys() -> (PrivateKeySigner, Address) {
let wallet = PrivateKeySigner::random();
let address = wallet.address();
(wallet, address.into())
}

Expand All @@ -169,7 +168,7 @@ mod tests {
#[rstest]
#[test]
fn check_signatures_unique_fail(
keys: (LocalWallet, Address),
keys: (PrivateKeySigner, Address),
allocation_ids: Vec<Address>,
domain_separator: Eip712Domain,
) {
Expand All @@ -191,7 +190,7 @@ mod tests {
#[rstest]
#[test]
fn check_signatures_unique_ok(
keys: (LocalWallet, Address),
keys: (PrivateKeySigner, Address),
allocation_ids: Vec<Address>,
domain_separator: Eip712Domain,
) {
Expand Down Expand Up @@ -219,7 +218,7 @@ mod tests {
#[test]
/// Test that a receipt with a timestamp greater then the rav timestamp passes
fn check_receipt_timestamps(
keys: (LocalWallet, Address),
keys: (PrivateKeySigner, Address),
allocation_ids: Vec<Address>,
domain_separator: Eip712Domain,
) {
Expand Down Expand Up @@ -289,7 +288,7 @@ mod tests {
/// Test check_allocation_id with 2 receipts that have the correct allocation id
/// and 1 receipt that has the wrong allocation id
fn check_allocation_id_fail(
keys: (LocalWallet, Address),
keys: (PrivateKeySigner, Address),
allocation_ids: Vec<Address>,
domain_separator: Eip712Domain,
) {
Expand Down Expand Up @@ -323,7 +322,7 @@ mod tests {
#[test]
/// Test check_allocation_id with 3 receipts that have the correct allocation id
fn check_allocation_id_ok(
keys: (LocalWallet, Address),
keys: (PrivateKeySigner, Address),
allocation_ids: Vec<Address>,
domain_separator: Eip712Domain,
) {
Expand Down
1 change: 1 addition & 0 deletions tap_aggregator/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,4 @@ pub mod error_codes;
pub mod jsonrpsee_helpers;
pub mod metrics;
pub mod server;
pub mod tap_aggregator;
10 changes: 6 additions & 4 deletions tap_aggregator/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ use std::borrow::Cow;
use std::collections::HashSet;
use std::str::FromStr;

use alloy_primitives::{Address, FixedBytes, U256};
use alloy_sol_types::Eip712Domain;
use alloy::dyn_abi::Eip712Domain;
use alloy::primitives::Address;
use alloy::primitives::FixedBytes;
use alloy::signers::local::PrivateKeySigner;
use anyhow::Result;
use clap::Parser;
use ethers_signers::{LocalWallet, Signer};
use ruint::aliases::U256;
use tokio::signal::unix::{signal, SignalKind};

use log::{debug, info};
Expand Down Expand Up @@ -96,7 +98,7 @@ async fn main() -> Result<()> {
tokio::spawn(metrics::run_server(args.metrics_port));

// Create a wallet from the mnemonic.
let wallet = LocalWallet::from_str(&args.private_key)?;
let wallet = PrivateKeySigner::from_str(&args.private_key)?;

info!("Wallet address: {:#40x}", wallet.address());

Expand Down
103 changes: 69 additions & 34 deletions tap_aggregator/src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@

use std::{collections::HashSet, str::FromStr};

use alloy_primitives::Address;
use alloy_sol_types::Eip712Domain;
use alloy::dyn_abi::Eip712Domain;
use alloy::primitives::Address;
use alloy::signers::local::PrivateKeySigner;
use anyhow::Result;
use ethers_signers::LocalWallet;
use jsonrpsee::{proc_macros::rpc, server::ServerBuilder, server::ServerHandle};
use lazy_static::lazy_static;
use prometheus::{register_counter, register_int_counter, Counter, IntCounter};
use tonic::{Request, Response, Status};

use crate::aggregator::check_and_aggregate_receipts;
use crate::api_versioning::{
Expand All @@ -18,6 +19,8 @@ use crate::api_versioning::{
};
use crate::error_codes::{JsonRpcErrorCode, JsonRpcWarningCode};
use crate::jsonrpsee_helpers::{JsonRpcError, JsonRpcResponse, JsonRpcResult, JsonRpcWarning};
use crate::tap_aggregator::tap_aggregator_server::TapAggregator;
use crate::tap_aggregator::{RavRequest, RavResponse};
use tap_core::{
rav::ReceiptAggregateVoucher, receipt::Receipt, signed_message::EIP712SignedMessage,
};
Expand Down Expand Up @@ -91,11 +94,56 @@ pub trait Rpc {
}

struct RpcImpl {
wallet: LocalWallet,
wallet: PrivateKeySigner,
accepted_addresses: HashSet<Address>,
domain_separator: Eip712Domain,
}

#[tonic::async_trait]
impl TapAggregator for RpcImpl {
async fn aggregate_receipts(
&self,
request: Request<RavRequest>,
) -> Result<Response<RavResponse>, tonic::Status> {
let RavRequest {
receipts,
previous_rav,
} = request.into_inner();

let receipts: Vec<EIP712SignedMessage<Receipt>> = receipts
.into_iter()
.map(|receipt| receipt.try_into())
.collect::<Result<Vec<_>, anyhow::Error>>()
.map_err(|e| Status::invalid_argument(format!("Invalid receipt: {e}")))?;

let previous_rav = previous_rav
.map(|rav| rav.try_into())
.transpose()
.map_err(|e| Status::invalid_argument(format!("Invalid previous RAV: {e}")))?;

let response = check_and_aggregate_receipts(
&self.domain_separator,
&receipts,
previous_rav,
&self.wallet,
&self.accepted_addresses,
)
.map_err(|e| {
AGGREGATION_FAILURE_COUNTER.inc();
Status::aborted(e.to_string())
})?;
let receipts_grt: u128 = receipts.iter().map(|r| r.message.value).sum();
let receipts_count: u64 = receipts.len() as u64;
TOTAL_GRT_AGGREGATED.inc_by(receipts_grt as f64);
TOTAL_AGGREGATED_RECEIPTS.inc_by(receipts_count);
AGGREGATION_SUCCESS_COUNTER.inc();

Ok(Response::new(RavResponse {
rav: Some(response.into()),
}))
}
}

/// Helper method that checks if the given API version is supported.
/// Returns an error if the API version is not supported.
fn parse_api_version(api_version: &str) -> Result<TapRpcApiVersion, JsonRpcError> {
Expand Down Expand Up @@ -128,7 +176,7 @@ fn check_api_version_deprecation(api_version: &TapRpcApiVersion) -> Option<JsonR

fn aggregate_receipts_(
api_version: String,
wallet: &LocalWallet,
wallet: &PrivateKeySigner,
accepted_addresses: &HashSet<Address>,
domain_separator: &Eip712Domain,
receipts: Vec<EIP712SignedMessage<Receipt>>,
Expand Down Expand Up @@ -210,7 +258,7 @@ impl RpcServer for RpcImpl {

pub async fn run_server(
port: u16,
wallet: LocalWallet,
wallet: PrivateKeySigner,
accepted_addresses: HashSet<Address>,
domain_separator: Eip712Domain,
max_request_body_size: u32,
Expand Down Expand Up @@ -243,9 +291,7 @@ mod tests {
use std::collections::HashSet;
use std::str::FromStr;

use alloy_primitives::Address;
use alloy_sol_types::Eip712Domain;
use ethers_signers::{coins_bip39::English, LocalWallet, MnemonicBuilder, Signer};
use alloy::{dyn_abi::Eip712Domain, primitives::Address, signers::local::PrivateKeySigner};
use jsonrpsee::{core::client::ClientT, http_client::HttpClientBuilder, rpc_params};
use rand::prelude::*;
use rand::seq::SliceRandom;
Expand All @@ -259,25 +305,14 @@ mod tests {

#[derive(Clone)]
struct Keys {
wallet: LocalWallet,
wallet: PrivateKeySigner,
address: Address,
}

fn keys(index: u32) -> Keys {
let wallet: LocalWallet = MnemonicBuilder::<English>::default()
.phrase("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about")
.index(index)
.unwrap()
.build()
.unwrap();
// Alloy library does not have feature parity with ethers library (yet) This workaround is needed to get the address
// to convert to an alloy Address. This will not be needed when the alloy library has wallet support.
let address: [u8; 20] = wallet.address().into();

Keys {
wallet,
address: address.into(),
}
fn keys() -> Keys {
let wallet = PrivateKeySigner::random();
let address = wallet.address();
Keys { wallet, address }
}

#[fixture]
Expand Down Expand Up @@ -319,7 +354,7 @@ mod tests {
http_max_concurrent_connections: u32,
) {
// The keys that will be used to sign the new RAVs
let keys_main = keys(0);
let keys_main = keys();

// Start the JSON-RPC server.
let (handle, local_addr) = server::run_server(
Expand Down Expand Up @@ -362,10 +397,10 @@ mod tests {
#[values(0, 1, 2)] random_seed: u64,
) {
// The keys that will be used to sign the new RAVs
let keys_main = keys(0);
let keys_main = keys();
// Extra keys to test the server's ability to accept multiple signers as input
let keys_0 = keys(1);
let keys_1 = keys(2);
let keys_0 = keys();
let keys_1 = keys();
// Vector of all wallets to make it easier to select one randomly
let all_wallets = vec![keys_main.clone(), keys_0.clone(), keys_1.clone()];
// PRNG for selecting a random wallet
Expand Down Expand Up @@ -443,10 +478,10 @@ mod tests {
#[values(0, 1, 2, 3, 4)] random_seed: u64,
) {
// The keys that will be used to sign the new RAVs
let keys_main = keys(0);
let keys_main = keys();
// Extra keys to test the server's ability to accept multiple signers as input
let keys_0 = keys(1);
let keys_1 = keys(2);
let keys_0 = keys();
let keys_1 = keys();
// Vector of all wallets to make it easier to select one randomly
let all_wallets = vec![keys_main.clone(), keys_0.clone(), keys_1.clone()];
// PRNG for selecting a random wallet
Expand Down Expand Up @@ -528,7 +563,7 @@ mod tests {
allocation_ids: Vec<Address>,
) {
// The keys that will be used to sign the new RAVs
let keys_main = keys(0);
let keys_main = keys();

// Start the JSON-RPC server.
let (handle, local_addr) = server::run_server(
Expand Down Expand Up @@ -611,7 +646,7 @@ mod tests {
#[values("0.0")] api_version: &str,
) {
// The keys that will be used to sign the new RAVs
let keys_main = keys(0);
let keys_main = keys();

// Set the request byte size limit to a value that easily triggers the HTTP 413
// error.
Expand Down
8 changes: 1 addition & 7 deletions tap_core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,9 @@ rand_core = "0.6.4"
serde = { version = "1.0", features = ["derive", "rc"] }
rand = "0.8.5"
thiserror = "1.0.38"
ethereum-types = { version = "0.14.1" }
rstest = "0.17.0"
ethers = { version = "2.0.0", default-features = false }
ethers-core = "2.0.0"
ethers-contract = "2.0.0"
ethers-contract-derive = "2.0.0"
anyhow = "1"
alloy-sol-types = { version = "0.7.0", features = ["eip712-serde"] }
alloy-primitives = { version = "0.7.0", features = ["serde"] }
alloy = { version = "0.2.0", features = ["full"] }

strum = "0.24.1"
strum_macros = "0.24.3"
Expand Down
Loading

0 comments on commit 3512620

Please sign in to comment.