Skip to content

Commit

Permalink
Merge branch 'main' into warn_panics_expects_and_unwraps
Browse files Browse the repository at this point in the history
  • Loading branch information
carneiro-cw authored Dec 27, 2024
2 parents 48c3b90 + d4d7315 commit 699a755
Show file tree
Hide file tree
Showing 14 changed files with 53 additions and 17 deletions.
4 changes: 4 additions & 0 deletions build.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
#![allow(clippy::unwrap_used)]
#![allow(clippy::expect_used)]
#![allow(clippy::panic)]

use std::collections::HashSet;
use std::env;
use std::fs;
Expand Down
19 changes: 11 additions & 8 deletions src/eth/executor/evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ impl Evm {
// parse result
let execution = match evm_result {
// executed
Ok(result) => Ok(parse_revm_execution(result, session_input, session_storage_changes)),
Ok(result) => Ok(parse_revm_execution(result, session_input, session_storage_changes)?),

// nonce errors
Err(EVMError::Transaction(InvalidTransaction::NonceTooHigh { tx, state })) => Err(StratusError::TransactionNonce {
Expand Down Expand Up @@ -303,9 +303,9 @@ impl Database for RevmSession {
// Conversion
// -----------------------------------------------------------------------------

fn parse_revm_execution(revm_result: RevmResultAndState, input: EvmInput, execution_changes: ExecutionChanges) -> EvmExecution {
fn parse_revm_execution(revm_result: RevmResultAndState, input: EvmInput, execution_changes: ExecutionChanges) -> Result<EvmExecution, StratusError> {
let (result, tx_output, logs, gas) = parse_revm_result(revm_result.result);
let changes = parse_revm_state(revm_result.state, execution_changes);
let changes = parse_revm_state(revm_result.state, execution_changes)?;

tracing::info!(?result, %gas, tx_output_len = %tx_output.len(), %tx_output, "evm executed");
let mut deployed_contract_address = None;
Expand All @@ -315,7 +315,7 @@ fn parse_revm_execution(revm_result: RevmResultAndState, input: EvmInput, execut
}
}

EvmExecution {
Ok(EvmExecution {
block_timestamp: input.block_timestamp,
receipt_applied: false,
result,
Expand All @@ -324,7 +324,7 @@ fn parse_revm_execution(revm_result: RevmResultAndState, input: EvmInput, execut
gas,
changes,
deployed_contract_address,
}
})
}

fn parse_revm_result(result: RevmExecutionResult) -> (ExecutionResult, Bytes, Vec<Log>, Gas) {
Expand All @@ -351,7 +351,7 @@ fn parse_revm_result(result: RevmExecutionResult) -> (ExecutionResult, Bytes, Ve
}
}

fn parse_revm_state(revm_state: RevmState, mut execution_changes: ExecutionChanges) -> ExecutionChanges {
fn parse_revm_state(revm_state: RevmState, mut execution_changes: ExecutionChanges) -> Result<ExecutionChanges, StratusError> {
for (revm_address, revm_account) in revm_state {
let address: Address = revm_address.into();
if address.is_ignored() {
Expand Down Expand Up @@ -387,10 +387,13 @@ fn parse_revm_state(revm_state: RevmState, mut execution_changes: ExecutionChang
} else if account_touched {
let Some(account_changes) = execution_changes.get_mut(&address) else {
tracing::error!(keys = ?execution_changes.keys(), %address, "account touched, but not loaded by evm");
panic!("Account '{}' was expected to be loaded by EVM, but it was not", address);
return Err(StratusError::Unexpected(anyhow!(
"Account '{}' was expected to be loaded by EVM, but it was not",
address
)));
};
account_changes.apply_modifications(account, account_modified_slots);
}
}
execution_changes
Ok(execution_changes)
}
2 changes: 2 additions & 0 deletions src/eth/external_rpc/postgres.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
#![allow(clippy::panic)]

use std::time::Duration;

use async_trait::async_trait;
Expand Down
1 change: 1 addition & 0 deletions src/eth/follower/importer/importer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -522,6 +522,7 @@ async fn fetch_block_and_receipts(chain: Arc<BlockchainClient>, block_number: Bl
(block, receipts)
}

#[allow(clippy::expect_used)]
#[tracing::instrument(name = "importer::fetch_block", skip_all, fields(block_number))]
async fn fetch_block(chain: Arc<BlockchainClient>, block_number: BlockNumber) -> ExternalBlock {
const RETRY_DELAY: Duration = Duration::from_millis(10);
Expand Down
1 change: 1 addition & 0 deletions src/eth/miner/miner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -508,6 +508,7 @@ mod interval_miner_ticker {
const TASK_NAME: &str = "interval-miner-ticker";

// sync to next second
#[allow(clippy::expect_used)]
let next_second = (Utc::now() + Duration::from_secs(1))
.with_nanosecond(0)
.expect("nanosecond above is set to `0`, which is always less than 2 billion");
Expand Down
2 changes: 1 addition & 1 deletion src/eth/primitives/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ impl From<LogTopic> for Address {
impl From<NameOrAddress> for Address {
fn from(value: NameOrAddress) -> Self {
match value {
NameOrAddress::Name(_) => panic!("TODO"),
NameOrAddress::Name(_) => todo!(),
NameOrAddress::Address(value) => Self(value),
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/eth/primitives/execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ impl EvmExecution {
let sender_next_nonce = sender_changes
.nonce
.take_original_ref()
.expect("from_original_values populates original values, so taking original ref here will succeed")
.ok_or_else(|| anyhow!("original nonce value not found when it should have been populated by from_original_values"))?
.next_nonce();
sender_changes.nonce.set_modified(sender_next_nonce);

Expand Down Expand Up @@ -197,7 +197,7 @@ impl EvmExecution {
};

// subtract execution cost from sender balance
let sender_balance = *sender_changes.balance.take_ref().expect("balance is never None");
let sender_balance = *sender_changes.balance.take_ref().ok_or(anyhow!("sender balance was None"))?;
let sender_new_balance = if sender_balance > execution_cost {
sender_balance - execution_cost
} else {
Expand Down
2 changes: 2 additions & 0 deletions src/eth/primitives/external_block.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,13 @@ pub struct ExternalBlock(#[deref] pub EthersBlockExternalTransaction);

impl ExternalBlock {
/// Returns the block hash.
#[allow(clippy::expect_used)]
pub fn hash(&self) -> Hash {
self.0.hash.expect("external block must have hash").into()
}

/// Returns the block number.
#[allow(clippy::expect_used)]
pub fn number(&self) -> BlockNumber {
self.0.number.expect("external block must have number").into()
}
Expand Down
2 changes: 2 additions & 0 deletions src/eth/primitives/external_receipt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,13 @@ impl ExternalReceipt {
}

/// Returns the block number.
#[allow(clippy::expect_used)]
pub fn block_number(&self) -> BlockNumber {
self.0.block_number.expect("external receipt must have block number").into()
}

/// Returns the block hash.
#[allow(clippy::expect_used)]
pub fn block_hash(&self) -> Hash {
self.0.block_hash.expect("external receipt must have block hash").into()
}
Expand Down
19 changes: 14 additions & 5 deletions src/eth/primitives/log_mined.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,12 +58,21 @@ impl LogMined {
impl TryFrom<EthersLog> for LogMined {
type Error = anyhow::Error;
fn try_from(value: EthersLog) -> Result<Self, Self::Error> {
let transaction_hash = value.transaction_hash.ok_or_else(|| anyhow::anyhow!("log must have transaction_hash"))?.into();
let transaction_index = value
.transaction_index
.ok_or_else(|| anyhow::anyhow!("log must have transaction_index"))?
.into();
let log_index = value.log_index.ok_or_else(|| anyhow::anyhow!("log must have log_index"))?.try_into()?;
let block_number = value.block_number.ok_or_else(|| anyhow::anyhow!("log must have block_number"))?.into();
let block_hash = value.block_hash.ok_or_else(|| anyhow::anyhow!("log must have block_hash"))?.into();

Ok(Self {
transaction_hash: value.transaction_hash.expect("log must have transaction_hash").into(),
transaction_index: value.transaction_index.expect("log must have transaction_index").into(),
log_index: value.log_index.expect("log must have log_index").try_into()?,
block_number: value.block_number.expect("log must have block_number").into(),
block_hash: value.block_hash.expect("log must have block_hash").into(),
transaction_hash,
transaction_index,
log_index,
block_number,
block_hash,
log: value.into(),
})
}
Expand Down
6 changes: 5 additions & 1 deletion src/eth/storage/temporary/inmemory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,7 +209,11 @@ impl TemporaryStorage for InMemoryTemporaryStorage {
#[cfg(not(feature = "dev"))]
let finished_block = {
let latest = RwLockWriteGuard::<Option<InMemoryTemporaryStorageState>>::downgrade(latest);
latest.as_ref().expect("latest should be Some after finishing the pending block").block.clone()
latest
.as_ref()
.ok_or_else(|| anyhow::anyhow!("latest should be Some after finishing the pending block"))?
.block
.clone()
};

Ok(finished_block)
Expand Down
6 changes: 6 additions & 0 deletions src/ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ impl<T> InfallibleExt<T, serde_json::Error> for Result<T, serde_json::Error>
where
T: Sized,
{
#[allow(clippy::expect_used)]
fn expect_infallible(self) -> T {
if let Err(ref e) = self {
tracing::error!(reason = ?e, "expected infallible serde serialization/deserialization");
Expand All @@ -144,6 +145,7 @@ where
}

impl InfallibleExt<Decimal, ()> for Option<Decimal> {
#[allow(clippy::expect_used)]
fn expect_infallible(self) -> Decimal {
if self.is_none() {
tracing::error!("expected infallible decimal conversion");
Expand All @@ -153,6 +155,7 @@ impl InfallibleExt<Decimal, ()> for Option<Decimal> {
}

impl InfallibleExt<DateTime<Utc>, ()> for Option<DateTime<Utc>> {
#[allow(clippy::expect_used)]
fn expect_infallible(self) -> DateTime<Utc> {
if self.is_none() {
tracing::error!("expected infallible datetime conversion");
Expand Down Expand Up @@ -238,6 +241,7 @@ pub async fn traced_sleep(duration: Duration, _: SleepReason) {

/// Spawns an async Tokio task with a name to be displayed in tokio-console.
#[track_caller]
#[allow(clippy::expect_used)]
pub fn spawn_named<T>(name: &str, task: impl std::future::Future<Output = T> + Send + 'static) -> tokio::task::JoinHandle<T>
where
T: Send + 'static,
Expand All @@ -252,6 +256,7 @@ where

/// Spawns a blocking Tokio task with a name to be displayed in tokio-console.
#[track_caller]
#[allow(clippy::expect_used)]
pub fn spawn_blocking_named<T>(name: &str, task: impl FnOnce() -> T + Send + 'static) -> tokio::task::JoinHandle<T>
where
T: Send + 'static,
Expand All @@ -265,6 +270,7 @@ where
}

/// Spawns a thread with the given name. Thread has access to Tokio current runtime.
#[allow(clippy::expect_used)]
#[track_caller]
pub fn spawn_thread<T>(name: &str, task: impl FnOnce() -> T + Send + 'static) -> std::thread::JoinHandle<T>
where
Expand Down
1 change: 1 addition & 0 deletions src/globals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ impl<T> GlobalServices<T>
where
T: clap::Parser + WithCommonConfig + Debug,
{
#[allow(clippy::expect_used)]
/// Executes global services initialization.
pub fn init() -> Self
where
Expand Down
1 change: 1 addition & 0 deletions src/infra/kafka/kafka.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ impl std::fmt::Display for KafkaSecurityProtocol {
}

impl KafkaConnector {
#[allow(clippy::expect_used)]
pub fn new(config: &KafkaConfig) -> Result<Self> {
tracing::info!(
topic = %config.topic,
Expand Down

0 comments on commit 699a755

Please sign in to comment.