Skip to content
Draft
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
74 changes: 62 additions & 12 deletions availability-oracle/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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<P: JsonRpcClient>(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"
Expand Down Expand Up @@ -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);
}

Expand Down Expand Up @@ -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(())
}
}
Expand Down Expand Up @@ -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,
Expand Down
49 changes: 20 additions & 29 deletions availability-oracle/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand All @@ -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,
Expand All @@ -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<String>) -> Vec<String> {
Expand Down Expand Up @@ -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,
Expand All @@ -515,8 +508,8 @@ pub async fn reconcile_deny_list(
grace_period: Duration,
epoch_subgraph: Arc<impl EpochBlockOracleSubgraph>,
supported_ds_kinds: &[String],
valid_deployment_cache: Vec<(Cid, SystemTime)>,
) -> Result<Vec<(Cid, SystemTime)>, Error> {
valid_deployment_cache: &mut Vec<(Cid, SystemTime)>,
) -> Result<(), Error> {
let logger = logger.clone();

// Fetch supported networks
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -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 {
Expand Down
37 changes: 36 additions & 1 deletion availability-oracle/src/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String> = cache.iter().map(|(cid, _)| cid.to_string()).collect();
assert_eq!(cached, [ONE, FOUR, SUBSTREAM, FILE_DS]);
}

struct MockSubgraph;

impl NetworkSubgraph for MockSubgraph {
Expand Down Expand Up @@ -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]
Expand Down
Loading