Skip to content

Commit

Permalink
fix(claimer): fix duplicate checker verification
Browse files Browse the repository at this point in the history
Read the NewClaimToHistory event from the History contract instead of
calling the getClaim method from the Authority contract.

Co-authored-by: Gabriel de Quadros Ligneul <[email protected]>
  • Loading branch information
GMKrieger and gligneul committed Nov 14, 2023
1 parent 086047a commit 7019ae7
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 43 deletions.
115 changes: 73 additions & 42 deletions offchain/authority-claimer/src/checker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,23 @@
// SPDX-License-Identifier: Apache-2.0 (see LICENSE)

use async_trait::async_trait;
use contracts::authority::Authority;
use contracts::history::{Claim, History};
use ethers::{
self,
abi::AbiEncode,
providers::{Http, HttpRateLimitRetryPolicy, Provider, RetryClient},
types::{H160, U256},
contract::ContractError,
providers::{
Http, HttpRateLimitRetryPolicy, Middleware, Provider, RetryClient,
},
types::{ValueOrArray, H160},
};
use rollups_events::{Address, RollupsClaim};
use snafu::{ResultExt, Snafu};
use std::fmt::Debug;
use std::sync::Arc;
use tracing::info;
use tracing::trace;
use url::{ParseError, Url};

const GENESIS_BLOCK: u64 = 1;
const MAX_RETRIES: u32 = 10;
const INITIAL_BACKOFF: u64 = 1000;

Expand All @@ -25,7 +28,7 @@ pub trait DuplicateChecker: Debug {
type Error: snafu::Error + 'static;

async fn is_duplicated_rollups_claim(
&self,
&mut self,
dapp_address: Address,
rollups_claim: &RollupsClaim,
) -> Result<bool, Self::Error>;
Expand All @@ -37,16 +40,22 @@ pub trait DuplicateChecker: Debug {

#[derive(Debug)]
pub struct DefaultDuplicateChecker {
authority: Authority<Provider<RetryClient<Http>>>,
provider: Arc<Provider<RetryClient<Http>>>,
history: History<Provider<RetryClient<Http>>>,
claims: Vec<Claim>,
next_block_to_read: u64,
}

#[derive(Debug, Snafu)]
pub enum DuplicateCheckerError {
#[snafu(display("invalid provider URL"))]
#[snafu(display("failed to call contract"))]
ContractError {
source: ethers::contract::ContractError<
ethers::providers::Provider<RetryClient<Http>>,
>,
source: ContractError<ethers::providers::Provider<RetryClient<Http>>>,
},

#[snafu(display("failed to call provider"))]
ProviderError {
source: ethers::providers::ProviderError,
},

#[snafu(display("parser error"))]
Expand All @@ -56,25 +65,26 @@ pub enum DuplicateCheckerError {
impl DefaultDuplicateChecker {
pub fn new(
http_endpoint: String,
authority_address: Address,
history_address: Address,
) -> Result<Self, DuplicateCheckerError> {
let http = Http::new(Url::parse(&http_endpoint).context(ParseSnafu)?);

let retry_client = RetryClient::new(
http,
Box::new(HttpRateLimitRetryPolicy),
MAX_RETRIES,
INITIAL_BACKOFF,
);

let provider = Arc::new(Provider::new(retry_client));

let authority = Authority::new(
H160(authority_address.inner().to_owned()),
provider,
let history = History::new(
H160(history_address.inner().to_owned()),
provider.clone(),
);

Ok(Self { authority })
Ok(Self {
provider,
history,
claims: Vec::new(),
next_block_to_read: GENESIS_BLOCK,
})
}
}

Expand All @@ -83,32 +93,53 @@ impl DuplicateChecker for DefaultDuplicateChecker {
type Error = DuplicateCheckerError;

async fn is_duplicated_rollups_claim(
&self,
&mut self,
dapp_address: Address,
rollups_claim: &RollupsClaim,
) -> Result<bool, Self::Error> {
let proof_context =
U256([rollups_claim.epoch_index, 0, 0, 0]).encode().into();

match self
.authority
.get_claim(H160(dapp_address.inner().to_owned()), proof_context)
.block(ethers::types::BlockNumber::Latest)
.call()
self.update_claims(dapp_address).await?;
Ok(self.claims.iter().any(|read_claim| {
&read_claim.epoch_hash == rollups_claim.epoch_hash.inner()
&& read_claim.first_index == rollups_claim.first_index
&& read_claim.last_index == rollups_claim.last_index
}))
}
}

impl DefaultDuplicateChecker {
async fn update_claims(
&mut self,
dapp_address: Address,
) -> Result<(), DuplicateCheckerError> {
let current_block = self
.provider
.get_block_number()
.await
{
// If there's any response, the claim already exists
Ok(_response) => Ok(true),
Err(e) => {
// If there's an InvalidClaimIndex error, we're asking for an index
// bigger than the current one, which means it's a new claim
if e.to_string().contains("InvalidClaimIndex()") {
Ok(false)
} else {
info!("{:?}", e);
Err(e).context(ContractSnafu)
}
}
.context(ProviderSnafu)?
.as_u64();

let dapp_address = H160(dapp_address.inner().to_owned());
let topic = ValueOrArray::Value(Some(dapp_address.into()));

let mut claims: Vec<_> = self
.history
.new_claim_to_history_filter()
.from_block(self.next_block_to_read)
.to_block(current_block)
.topic1(topic)
.query()
.await
.context(ContractSnafu)?
.into_iter()
.map(|event| event.claim)
.collect();

if !claims.is_empty() {
trace!("read new claims {:?}", claims);
self.claims.append(&mut claims);
}
self.next_block_to_read = current_block + 1;

Ok(())
}
}
2 changes: 1 addition & 1 deletion offchain/authority-claimer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ pub async fn run(config: Config) -> Result<(), Box<dyn Error>> {
trace!("Creating the duplicate checker");
let duplicate_checker = DefaultDuplicateChecker::new(
config.tx_manager_config.provider_http_endpoint.clone(),
config.blockchain_config.authority_address.clone(),
config.blockchain_config.history_address.clone(),
)?;

// Creating the transaction sender.
Expand Down

0 comments on commit 7019ae7

Please sign in to comment.