diff --git a/availability-oracle/src/contract.rs b/availability-oracle/src/contract.rs index 7082c5f..1fc1c20 100644 --- a/availability-oracle/src/contract.rs +++ b/availability-oracle/src/contract.rs @@ -6,7 +6,7 @@ use ethers::{ contract::abigen, core::types::U256, middleware::SignerMiddleware, - providers::{Http, Middleware, Provider}, + providers::{Http, JsonRpcClient, Middleware, PendingTransaction, Provider}, signers::{LocalWallet, Signer}, }; use secp256k1::SecretKey; @@ -21,6 +21,24 @@ pub trait StateManager { } abigen!(RewardsManagerABI, "src/abi/RewardsManager.abi.json"); + +/// How long a submitted transaction may stay unmined before the signer gives up on it. +const CONFIRMATION_TIMEOUT: Duration = Duration::from_secs(300); + +/// Waits for the receipt and fails if the transaction is dropped, reverted or not mined in time. +async fn confirmed(pending: PendingTransaction<'_, P>) -> Result<(), Error> { + let tx_hash = *pending; + let receipt = tokio::time::timeout(CONFIRMATION_TIMEOUT, pending) + .await + .map_err(|_| anyhow!("tx {:?} unmined after {:?}", tx_hash, CONFIRMATION_TIMEOUT))?? + .ok_or_else(|| anyhow!("tx {:?} dropped from the mempool", tx_hash))?; + ensure!( + receipt.status == Some(1u64.into()), + "tx {:?} reverted on chain", + tx_hash + ); + Ok(()) +} abigen!( SubgraphAvailabilityManagerABI, "src/abi/SubgraphAvailabilityManager.abi.json" @@ -132,11 +150,8 @@ impl StateManager for RewardsManagerContract { let gas_price = self.contract.client().get_gas_price().await?; let gas_price_with_buffer = gas_price * U256::from(120) / U256::from(100); - tx.gas(increased_estimate) - .gas_price(gas_price_with_buffer) - .send() - .await? - .await?; + let tx = tx.gas(increased_estimate).gas_price(gas_price_with_buffer); + confirmed(tx.send().await?).await?; METRICS.denied_subgraphs_total.inc_by(num_subgraphs); } @@ -197,12 +212,8 @@ impl SubgraphAvailabilityManagerContract { let gas_price = self.contract.client().get_gas_price().await?; let gas_price_with_buffer = gas_price * U256::from(120) / U256::from(100); - tx.gas(increased_estimate) - .gas_price(gas_price_with_buffer) - .send() - .await? - .await?; - + let tx = tx.gas(increased_estimate).gas_price(gas_price_with_buffer); + confirmed(tx.send().await?).await?; Ok(()) } } @@ -333,8 +344,47 @@ impl Metrics { #[cfg(test)] mod tests { use super::*; + use ethers::types::{Transaction, TransactionReceipt, TxHash}; use std::sync::Mutex; + async fn confirm_mocked(responses: &[serde_json::Value]) -> Result<(), Error> { + let (provider, mock) = Provider::mocked(); + // The mock serves responses last-in first-out. + for response in responses.iter().rev() { + mock.push(response.clone()).unwrap(); + } + let pending = PendingTransaction::new(TxHash::zero(), &provider) + .interval(Duration::from_millis(1)) + .retries(0); + confirmed(pending).await + } + + #[tokio::test] + async fn dropped_transaction_is_an_error() { + let err = confirm_mocked(&[serde_json::Value::Null]) + .await + .unwrap_err(); + assert!(format!("{:#}", err).contains("dropped from the mempool")); + } + + #[tokio::test] + async fn reverted_transaction_is_an_error() { + let mined = Transaction { + block_number: Some(1.into()), + ..Default::default() + }; + let reverted = TransactionReceipt { + status: Some(0.into()), + ..Default::default() + }; + let responses = [ + serde_json::to_value(mined).unwrap(), + serde_json::to_value(reverted).unwrap(), + ]; + let err = confirm_mocked(&responses).await.unwrap_err(); + assert!(format!("{:#}", err).contains("reverted on chain")); + } + struct MockSigner { index: u64, fail: bool, diff --git a/availability-oracle/src/main.rs b/availability-oracle/src/main.rs index de367a3..0e7848d 100644 --- a/availability-oracle/src/main.rs +++ b/availability-oracle/src/main.rs @@ -346,17 +346,11 @@ async fn run(logger: Logger, config: Config) -> Result<()> { grace_period, epoch_subgraph.clone(), &config.supported_data_source_kinds, - valid_deployment_cache.clone(), + &mut valid_deployment_cache, ) .await { - Ok(updated_deployment_cache) => { - METRICS.reconcile_runs_ok.inc(); - valid_deployment_cache = updated_deployment_cache; - info!(logger, "Deployment cache updated"; - "count" => valid_deployment_cache.len() - ); - } + Ok(()) => METRICS.reconcile_runs_ok.inc(), Err(e) => { METRICS.reconcile_runs_err.inc(); error!(logger, "Error, reconciliation aborted"; "error" => format!("{:#}", e)) @@ -375,7 +369,7 @@ async fn run(logger: Logger, config: Config) -> Result<()> { ipfs.invalidate_cache(); } } - match reconcile_deny_list( + reconcile_deny_list( &logger, &ipfs, &*contract, @@ -384,13 +378,9 @@ async fn run(logger: Logger, config: Config) -> Result<()> { grace_period, epoch_subgraph.clone(), &config.supported_data_source_kinds, - Vec::new(), + &mut Vec::new(), ) .await - { - Ok(_) => return Ok(()), - Err(e) => return Err(e), - } } fn split_list(value: &Option) -> Vec { @@ -506,6 +496,9 @@ async fn state_manager( /// 1. Grab the list of all deployments over the curation threshold from the subgraph. /// 2. Check if their availability status changed. /// 3. Update the deny list accordingly. +/// +/// The cache of valid deployments is refreshed before voting, so a failed vote +/// does not leave it to expire. pub async fn reconcile_deny_list( logger: &Logger, ipfs: &impl Ipfs, @@ -515,8 +508,8 @@ pub async fn reconcile_deny_list( grace_period: Duration, epoch_subgraph: Arc, supported_ds_kinds: &[String], - valid_deployment_cache: Vec<(Cid, SystemTime)>, -) -> Result, Error> { + valid_deployment_cache: &mut Vec<(Cid, SystemTime)>, +) -> Result<(), Error> { let logger = logger.clone(); // Fetch supported networks @@ -563,7 +556,7 @@ pub async fn reconcile_deny_list( }; }) .buffered(100) - .try_filter_map(move |(deployment, validity, last_validated)| { + .try_filter_map(|(deployment, validity, last_validated)| { let logger = logger.clone(); async move { info!(logger, "Check subgraph"; @@ -605,24 +598,22 @@ pub async fn reconcile_deny_list( .try_collect() .await?; + *valid_deployment_cache = deployment_status + .iter() + .filter(|(_, should_deny, _, _)| !*should_deny) + .map(|(cid, _, _, last_validated)| (bytes32_to_cid_v0(*cid), *last_validated)) + .collect(); + info!(logger, "Deployment cache updated"; + "count" => valid_deployment_cache.len() + ); + // Flip on chain status for those deployments that changed let changed_deployments = deployment_status .iter() .filter(|(_, _, status_changed, _)| *status_changed) .map(|(cid, should_deny, _, _)| (*cid, *should_deny)) .collect(); - match state_manager.deny_many(changed_deployments).await { - Ok(_) => {} - Err(e) => return Err(e), - }; - - // Return updated deployment cache - let updated_deployment_cache: Vec<(Cid, SystemTime)> = deployment_status - .iter() - .filter(|(_, should_deny, _, _)| !*should_deny) - .map(|(cid, _, _, last_validated)| (bytes32_to_cid_v0(*cid), *last_validated)) - .collect(); - Ok(updated_deployment_cache) + state_manager.deny_many(changed_deployments).await } enum Valid { diff --git a/availability-oracle/src/test.rs b/availability-oracle/src/test.rs index fd13864..15e73a8 100644 --- a/availability-oracle/src/test.rs +++ b/availability-oracle/src/test.rs @@ -61,12 +61,38 @@ mod tests { "file/ipfs".into(), "substreams".into(), ], - vec![], + &mut vec![], ) .await .unwrap(); } + // The valid deployments are cached even though voting failed. + #[tokio::test] + async fn test_cache_survives_failed_vote() { + let mut cache = vec![]; + crate::reconcile_deny_list( + &common::logging::create_logger(), + &MockIpfs, + &FailingStateManager, + Arc::new(MockSubgraph), + 0, + Duration::default(), + Arc::new(MockEBOSubgraph), + &vec![ + "ethereum".into(), + "ethereum/contract".into(), + "file/ipfs".into(), + "substreams".into(), + ], + &mut cache, + ) + .await + .unwrap_err(); + let cached: Vec = cache.iter().map(|(cid, _)| cid.to_string()).collect(); + assert_eq!(cached, [ONE, FOUR, SUBSTREAM, FILE_DS]); + } + struct MockSubgraph; impl NetworkSubgraph for MockSubgraph { @@ -144,6 +170,15 @@ mod tests { } } + struct FailingStateManager; + + #[async_trait] + impl contract::StateManager for FailingStateManager { + async fn deny_many(&self, _denied_status: Vec<([u8; 32], bool)>) -> Result<(), Error> { + Err(anyhow!("vote failed")) + } + } + struct MockStateManager; #[async_trait]