Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix duplicate checker verification #150

Merged
merged 1 commit into from
Nov 16, 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
138 changes: 96 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 snafu::{ensure, 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,44 +40,61 @@ 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>,
confirmations: usize,
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"))]
ParseError { source: ParseError },

#[snafu(display(
"Depth of `{}` higher than latest block `{}`",
depth,
latest
))]
DepthTooHigh { depth: u64, latest: u64 },
}

impl DefaultDuplicateChecker {
pub fn new(
http_endpoint: String,
authority_address: Address,
history_address: Address,
confirmations: usize,
) -> 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(),
confirmations,
next_block_to_read: GENESIS_BLOCK,
})
}
}

Expand All @@ -83,32 +103,66 @@ 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 depth = self.confirmations as u64;

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();

ensure!(
depth <= current_block,
DepthTooHighSnafu {
depth: depth,
latest: current_block
}
);

let block_number = current_block - depth;

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(block_number)
.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 = block_number + 1;

Ok(())
}
}
3 changes: 2 additions & 1 deletion offchain/authority-claimer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ 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(),
config.tx_manager_config.default_confirmations,
)?;

// Creating the transaction sender.
Expand Down
Loading