Skip to content

Commit

Permalink
refactor: replace ethers with alloy (#278)
Browse files Browse the repository at this point in the history
* refactor: replace ethers with alloy

Signed-off-by: Gustavo Inacio <[email protected]>

* test(tap-agent): check eq by signature bytes

Signed-off-by: Gustavo Inacio <[email protected]>

* chore: update clippy

Signed-off-by: Gustavo Inacio <[email protected]>

---------

Signed-off-by: Gustavo Inacio <[email protected]>
  • Loading branch information
gusinacio authored Aug 11, 2024
1 parent 55c4ea1 commit d8d1af9
Show file tree
Hide file tree
Showing 48 changed files with 926 additions and 1,564 deletions.
2,012 changes: 683 additions & 1,329 deletions Cargo.lock

Large diffs are not rendered by default.

12 changes: 5 additions & 7 deletions common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,9 @@ version = "0.1.0"
edition = "2021"

[dependencies]
alloy-primitives = { version = "0.6", features = ["serde"] }
alloy-sol-types = "0.6"
alloy = { version = "0.2.1", features = ["full", "signer-mnemonic"] }
anyhow = "1.0.75"
arc-swap = "1.6.0"
ethers = "2.0.10"
ethers-core = "2.0.10"
eventuals = "0.6.7"
keccak-hash = "0.10.0"
lazy_static = "1.4.0"
Expand All @@ -27,11 +24,10 @@ sqlx = { version = "0.7.1", features = [
"time",
] }
tokio = { version = "1.32.0", features = ["full", "macros", "rt"] }
thegraph = { git = "https://github.com/edgeandnode/toolshed", tag = "thegraph-v0.5.0" }
thegraph-graphql-http = { version = "0.2.1", features = [
"http-client-reqwest",
] }
tap_core = "1.0.0"
tap_core = { git = "https://github.com/semiotic-ai/timeline-aggregation-protocol", rev = "b5f2135" }
axum = { version = "0.7.5", default_features = true }
axum-extra = { version = "0.9.3", features = ["typed-header"] }
thiserror = "1.0.49"
Expand All @@ -47,7 +43,9 @@ tower-http = { version = "0.5.2", features = [
] }
tokio-util = "0.7.10"
bigdecimal = "0.4.2"
thegraph-core = { version = "0.5.2", features = ["subgraph-client"] }
thegraph-core = { git = "https://github.com/edgeandnode/toolshed", rev = "85ee00b", features = [
"subgraph-client",
] }

[dev-dependencies]
env_logger = "0.11.0"
Expand Down
11 changes: 5 additions & 6 deletions common/src/address.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
// Copyright 2023-, GraphOps and Semiotic Labs.
// SPDX-License-Identifier: Apache-2.0

use ethers::signers::{
coins_bip39::English, LocalWallet, MnemonicBuilder, Signer, Wallet, WalletError,
use alloy::signers::local::{
coins_bip39::English, LocalSignerError, MnemonicBuilder, PrivateKeySigner,
};
use ethers_core::k256::ecdsa::SigningKey;

/// Build Wallet from Private key or Mnemonic
pub fn build_wallet(value: &str) -> Result<Wallet<SigningKey>, WalletError> {
pub fn build_wallet(value: &str) -> Result<PrivateKeySigner, LocalSignerError> {
value
.parse::<LocalWallet>()
.parse::<PrivateKeySigner>()
.or(MnemonicBuilder::<English>::default().phrase(value).build())
}

// Format public key to a String
pub fn public_key(value: &str) -> Result<String, WalletError> {
pub fn public_key(value: &str) -> Result<String, LocalSignerError> {
let wallet = build_wallet(value)?;
let addr = format!("{:?}", wallet.address());
Ok(addr)
Expand Down
5 changes: 2 additions & 3 deletions common/src/allocations/mod.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
// Copyright 2023-, GraphOps and Semiotic Labs.
// SPDX-License-Identifier: Apache-2.0

use ethers_core::types::U256;
use alloy::primitives::U256;
use serde::{Deserialize, Deserializer};
use thegraph::types::Address;
use thegraph::types::DeploymentId;
use thegraph_core::{Address, DeploymentId};

pub mod monitor;

Expand Down
2 changes: 1 addition & 1 deletion common/src/allocations/monitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::{
use super::Allocation;
use crate::prelude::SubgraphClient;
use eventuals::{timer, Eventual, EventualExt};
use thegraph::types::Address;
use thegraph_core::Address;
use tokio::time::sleep;
use tracing::warn;

Expand Down
2 changes: 1 addition & 1 deletion common/src/attestations/dispute_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::time::Duration;

use eventuals::{timer, Eventual, EventualExt};
use serde::Deserialize;
use thegraph::types::Address;
use thegraph_core::Address;
use tokio::time::sleep;
use tracing::warn;

Expand Down
74 changes: 33 additions & 41 deletions common/src/attestations/signer.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
// Copyright 2023-, GraphOps and Semiotic Labs.
// SPDX-License-Identifier: Apache-2.0

use alloy_sol_types::Eip712Domain;
use ethers::signers::coins_bip39::English;
use ethers::signers::{MnemonicBuilder, Signer, Wallet};
use ethers_core::k256::ecdsa::SigningKey;
use thegraph::types::{attestation, Attestation, DeploymentId};
use thegraph::types::{Address, U256};
use alloy::{
dyn_abi::Eip712Domain,
signers::{
k256,
local::{coins_bip39::English, MnemonicBuilder, PrivateKeySigner},
},
};
use thegraph_core::{attestation, Address, Attestation, ChainId, DeploymentId};

use crate::prelude::Allocation;

Expand All @@ -15,7 +17,7 @@ pub fn derive_key_pair(
epoch: u64,
deployment: &DeploymentId,
index: u64,
) -> Result<Wallet<SigningKey>, anyhow::Error> {
) -> Result<PrivateKeySigner, anyhow::Error> {
let mut derivation_path = format!("m/{}/", epoch);
derivation_path.push_str(
&deployment
Expand All @@ -40,38 +42,29 @@ pub fn derive_key_pair(
pub struct AttestationSigner {
deployment: DeploymentId,
domain: Eip712Domain,
signer: SigningKey,
signer: k256::ecdsa::SigningKey,
}

impl AttestationSigner {
pub fn new(
indexer_mnemonic: &str,
allocation: &Allocation,
chain_id: ethers_core::types::U256,
chain_id: ChainId,
dispute_manager: Address,
) -> Result<Self, anyhow::Error> {
// Recreate a wallet that has the same address as the allocation
let wallet = wallet_for_allocation(indexer_mnemonic, allocation)?;

let mut chain_id_buf = [0_u8; 32];
chain_id.to_big_endian(&mut chain_id_buf);
let chain_id = U256::from_be_bytes(chain_id_buf);

Ok(Self {
deployment: allocation.subgraph_deployment.id,
domain: attestation::eip712_domain(chain_id, dispute_manager),
signer: wallet.signer().clone(),
signer: wallet.into_credential(),
})
}

pub fn create_attestation(&self, request: &str, response: &str) -> Attestation {
attestation::create(
&self.domain,
&self.signer,
&self.deployment,
request,
response,
)
let wallet = PrivateKeySigner::from_signing_key(self.signer.clone());
attestation::create(&self.domain, &wallet, &self.deployment, request, response)
}

pub fn verify(
Expand All @@ -94,7 +87,7 @@ impl AttestationSigner {
fn wallet_for_allocation(
indexer_mnemonic: &str,
allocation: &Allocation,
) -> Result<Wallet<SigningKey>, anyhow::Error> {
) -> Result<PrivateKeySigner, anyhow::Error> {
// Guess the allocation index by enumerating all indexes in the
// range [0, 100] and checking for a match
for i in 0..100 {
Expand All @@ -111,7 +104,7 @@ fn wallet_for_allocation(
)?;

// See if we have a match, i.e. a wallet whose address is identical to the allocation ID
if wallet.address().as_fixed_bytes() == allocation.id {
if wallet.address() == allocation.id {
return Ok(wallet);
}
}
Expand All @@ -124,7 +117,7 @@ fn wallet_for_allocation(

#[cfg(test)]
mod tests {
use ethers_core::types::U256;
use alloy::primitives::U256;
use std::str::FromStr;
use test_log::test;

Expand All @@ -150,8 +143,7 @@ mod tests {
0
)
.unwrap()
.address()
.as_fixed_bytes(),
.address(),
Address::from_str("0xfa44c72b753a66591f241c7dc04e8178c30e13af").unwrap()
);

Expand All @@ -166,8 +158,7 @@ mod tests {
2
)
.unwrap()
.address()
.as_fixed_bytes(),
.address(),
Address::from_str("0xa171cd12c3dde7eb8fe7717a0bcd06f3ffa65658").unwrap()
);
}
Expand All @@ -187,7 +178,7 @@ mod tests {
denied_at: None,
},
indexer: Address::ZERO,
allocated_tokens: U256::zero(),
allocated_tokens: U256::ZERO,
created_at_epoch: 940,
created_at_block_hash: "".to_string(),
closed_at_epoch: None,
Expand All @@ -198,22 +189,23 @@ mod tests {
query_fees_collected: None,
};
assert_eq!(
AttestationSigner::new(
INDEXER_OPERATOR_MNEMONIC,
&allocation,
U256::from(1),
*DISPUTE_MANAGER_ADDRESS
)
.unwrap()
.signer,
*derive_key_pair(
PrivateKeySigner::from_signing_key(
AttestationSigner::new(
INDEXER_OPERATOR_MNEMONIC,
&allocation,
1,
*DISPUTE_MANAGER_ADDRESS
)
.unwrap()
.signer
),
derive_key_pair(
INDEXER_OPERATOR_MNEMONIC,
940,
&allocation.subgraph_deployment.id,
2
)
.unwrap()
.signer()
);
}

Expand All @@ -233,7 +225,7 @@ mod tests {
denied_at: None,
},
indexer: Address::ZERO,
allocated_tokens: U256::zero(),
allocated_tokens: U256::ZERO,
created_at_epoch: 940,
created_at_block_hash: "".to_string(),
closed_at_epoch: None,
Expand All @@ -246,7 +238,7 @@ mod tests {
assert!(AttestationSigner::new(
INDEXER_OPERATOR_MNEMONIC,
&allocation,
U256::from(1),
1,
*DISPUTE_MANAGER_ADDRESS
)
.is_err());
Expand Down
7 changes: 3 additions & 4 deletions common/src/attestations/signers.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
// Copyright 2023-, GraphOps and Semiotic Labs.
// SPDX-License-Identifier: Apache-2.0

use ethers_core::types::U256;
use eventuals::{join, Eventual, EventualExt};
use std::collections::HashMap;
use std::sync::Arc;
use thegraph::types::Address;
use thegraph_core::{Address, ChainId};
use tokio::sync::Mutex;
use tracing::warn;

Expand All @@ -15,7 +14,7 @@ use crate::prelude::{Allocation, AttestationSigner};
pub fn attestation_signers(
indexer_allocations: Eventual<HashMap<Address, Allocation>>,
indexer_mnemonic: String,
chain_id: U256,
chain_id: ChainId,
dispute_manager: Eventual<Address>,
) -> Eventual<HashMap<Address, AttestationSigner>> {
let attestation_signers_map: &'static Mutex<HashMap<Address, AttestationSigner>> =
Expand Down Expand Up @@ -77,7 +76,7 @@ mod tests {
let signers = attestation_signers(
allocations,
(*INDEXER_OPERATOR_MNEMONIC).to_string(),
U256::from(1),
1,
dispute_manager,
);
let mut signers = signers.subscribe();
Expand Down
9 changes: 5 additions & 4 deletions common/src/escrow_accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,15 @@

use std::{
collections::{HashMap, HashSet},
str::FromStr,
time::Duration,
};

use alloy::primitives::U256;
use anyhow::Result;
use ethers_core::types::U256;
use eventuals::{timer, Eventual, EventualExt};
use serde::Deserialize;
use thegraph::types::Address;
use thegraph_core::Address;
use thiserror::Error;
use tokio::time::sleep;
use tracing::{error, warn};
Expand Down Expand Up @@ -179,8 +180,8 @@ pub fn escrow_accounts(
.iter()
.map(|account| {
let balance = U256::checked_sub(
U256::from_dec_str(&account.balance)?,
U256::from_dec_str(&account.total_amount_thawing)?,
U256::from_str(&account.balance)?,
U256::from_str(&account.total_amount_thawing)?,
)
.unwrap_or_else(|| {
warn!(
Expand Down
3 changes: 1 addition & 2 deletions common/src/indexer_service/http/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@
use std::net::SocketAddr;

use serde::{Deserialize, Serialize};
use thegraph::types::Address;
use thegraph::types::DeploymentId;
use thegraph_core::{Address, DeploymentId};

#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct DatabaseConfig {
Expand Down
7 changes: 3 additions & 4 deletions common/src/indexer_service/http/indexer_service.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use std::{
time::Duration,
};

use alloy_sol_types::eip712_domain;
use alloy::sol_types::eip712_domain;
use anyhow;
use autometrics::prometheus_exporter;
use axum::extract::MatchedPath;
Expand All @@ -25,8 +25,7 @@ use reqwest::StatusCode;
use serde::{de::DeserializeOwned, Serialize};
use sqlx::postgres::PgPoolOptions;
use tap_core::{manager::Manager, receipt::checks::CheckList};
use thegraph::types::Address;
use thegraph::types::{Attestation, DeploymentId};
use thegraph_core::{Address, Attestation, DeploymentId};
use thiserror::Error;
use tokio::net::TcpListener;
use tokio::signal;
Expand Down Expand Up @@ -238,7 +237,7 @@ impl IndexerService {
let attestation_signers = attestation_signers(
allocations.clone(),
options.config.indexer.operator_mnemonic.clone(),
options.config.graph_network.chain_id.into(),
options.config.graph_network.chain_id,
dispute_manager,
);

Expand Down
2 changes: 1 addition & 1 deletion common/src/indexer_service/http/request_handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use axum::{
};
use axum_extra::TypedHeader;
use reqwest::StatusCode;
use thegraph::types::DeploymentId;
use thegraph_core::DeploymentId;
use tracing::trace;

use crate::{indexer_service::http::IndexerServiceResponse, prelude::AttestationSigner};
Expand Down
2 changes: 1 addition & 1 deletion common/src/indexer_service/http/tap_receipt_header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ mod test {

use axum::http::HeaderValue;
use axum_extra::headers::Header;
use thegraph::types::Address;
use thegraph_core::Address;

use crate::test_vectors::create_signed_receipt;

Expand Down
Loading

0 comments on commit d8d1af9

Please sign in to comment.