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

chore: Refactor and fix lints #97

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
37 changes: 13 additions & 24 deletions lib/src/builder/execute/ethereum.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ impl TxExecStrategy<EthereumTxEssence> for EthTxExecStrategy {
.unwrap();

debug!("Block no. {}", header.number);
debug!(" EVM spec ID: {:?}", spec_id);
debug!(" Timestamp: {}", dt);
debug!(" EVM spec ID: {spec_id:?}");
debug!(" Timestamp: {dt}");
trace!(
" Transactions: {}",
block_builder.input.state_input.transactions.len()
Expand All @@ -97,7 +97,7 @@ impl TxExecStrategy<EthereumTxEssence> for EthTxExecStrategy {
.with_spec_id(spec_id)
.modify_block_env(|blk_env| {
// set the EVM block environment
blk_env.number = header.number.try_into().unwrap();
blk_env.number = U256::from(header.number);
blk_env.coinbase = block_builder.input.state_input.beneficiary;
blk_env.timestamp = header.timestamp;
blk_env.difficulty = U256::ZERO;
Expand Down Expand Up @@ -131,32 +131,32 @@ impl TxExecStrategy<EthereumTxEssence> for EthTxExecStrategy {
#[cfg(not(target_os = "zkvm"))]
{
let tx_hash = tx.hash();
trace!("Tx no. {} (hash: {})", tx_no, tx_hash);
trace!("Tx no. {tx_no} (hash: {tx_hash})");
trace!(" Type: {}", tx.essence.tx_type());
trace!(" Fr: {:?}", tx_from);
trace!(" Fr: {tx_from:?}");
trace!(" To: {:?}", tx.essence.to().unwrap_or_default());
}

// verify transaction gas
let block_available_gas =
block_builder.input.state_input.gas_limit - cumulative_gas_used;
if block_available_gas < tx.essence.gas_limit() {
bail!("Error at transaction {}: gas exceeds block limit", tx_no);
bail!("Error at transaction {tx_no}: gas exceeds block limit");
}

// process the transaction
fill_eth_tx_env(&mut evm.env_mut().tx, &tx.essence, tx_from);
let ResultAndState { result, state } = evm
.transact()
.map_err(|evm_err| anyhow!("Error at transaction {}: {:?}", tx_no, evm_err))
.map_err(|evm_err| anyhow!("Error at transaction {tx_no}: {evm_err:?}"))
// todo: change unrecoverable panic to host-side recoverable `Result`
.expect("Block construction failure.");

let gas_used = result.gas_used().try_into().unwrap();
cumulative_gas_used = cumulative_gas_used.checked_add(gas_used).unwrap();

#[cfg(not(target_os = "zkvm"))]
trace!(" Ok: {:?}", result);
trace!(" Ok: {result:?}");

// create the receipt from the EVM result
let receipt = Receipt::new(
Expand Down Expand Up @@ -186,8 +186,7 @@ impl TxExecStrategy<EthereumTxEssence> for EthTxExecStrategy {
if account.is_touched() {
// log account
trace!(
" State {:?} (is_selfdestructed={}, is_loaded_as_not_existing={}, is_created={}, is_empty={})",
address,
" State {address:?} (is_selfdestructed={}, is_loaded_as_not_existing={}, is_created={}, is_empty={})",
account.is_selfdestructed(),
account.is_loaded_as_not_existing(),
account.is_created(),
Expand All @@ -203,7 +202,7 @@ impl TxExecStrategy<EthereumTxEssence> for EthTxExecStrategy {
// log state changes
for (addr, slot) in &account.storage {
if slot.is_changed() {
trace!(" Storage address: {:?}", addr);
trace!(" Storage address: {addr:?}");
trace!(" Before: {:?}", slot.original_value());
trace!(" After: {:?}", slot.present_value());
}
Expand All @@ -229,7 +228,7 @@ impl TxExecStrategy<EthereumTxEssence> for EthTxExecStrategy {
{
trace!("Withdrawal no. {}", withdrawal.index);
trace!(" Recipient: {:?}", withdrawal.address);
trace!(" Value: {}", amount_wei);
trace!(" Value: {amount_wei}");
}
// Credit withdrawal amount
increase_account_balance(&mut evm.context.evm.db, withdrawal.address, amount_wei)
Expand All @@ -247,11 +246,7 @@ impl TxExecStrategy<EthereumTxEssence> for EthTxExecStrategy {
header.receipts_root = receipt_trie.hash();
header.logs_bloom = logs_bloom;
header.gas_used = cumulative_gas_used;
header.withdrawals_root = if spec_id < SpecId::SHANGHAI {
None
} else {
Some(withdrawals_trie.hash())
};
header.withdrawals_root = (spec_id >= SpecId::SHANGHAI).then_some(withdrawals_trie.hash());

// Leak memory, save cycles
guest_mem_forget([tx_trie, receipt_trie, withdrawals_trie]);
Expand Down Expand Up @@ -325,13 +320,7 @@ where
// Read account from database
let mut account: Account = db
.basic(address)
.map_err(|db_err| {
anyhow!(
"Error increasing account balance for {}: {:?}",
address,
db_err
)
})?
.map_err(|db_err| anyhow!("Error increasing account balance for {address}: {db_err:?}"))?
.unwrap_or_default()
.into();
// Credit withdrawal amount
Expand Down
29 changes: 12 additions & 17 deletions lib/src/builder/execute/optimism.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,8 +70,8 @@ impl TxExecStrategy<OptimismTxEssence> for OpTxExecStrategy {
.unwrap();

trace!("Block no. {}", header.number);
trace!(" EVM spec ID: {:?}", spec_id);
trace!(" Timestamp: {}", dt);
trace!(" EVM spec ID: {spec_id:?}");
trace!(" Timestamp: {dt}");
trace!(
" Transactions: {}",
block_builder.input.state_input.transactions.len()
Expand All @@ -95,7 +95,7 @@ impl TxExecStrategy<OptimismTxEssence> for OpTxExecStrategy {
.with_spec_id(spec_id)
.modify_block_env(|blk_env| {
// set the EVM block environment
blk_env.number = header.number.try_into().unwrap();
blk_env.number = U256::from(header.number);
blk_env.coinbase = block_builder.input.state_input.beneficiary;
blk_env.timestamp = header.timestamp;
blk_env.difficulty = U256::ZERO;
Expand Down Expand Up @@ -129,17 +129,17 @@ impl TxExecStrategy<OptimismTxEssence> for OpTxExecStrategy {
#[cfg(not(target_os = "zkvm"))]
{
let tx_hash = tx.hash();
trace!("Tx no. {} (hash: {})", tx_no, tx_hash);
trace!("Tx no. {tx_no} (hash: {tx_hash})");
trace!(" Type: {}", tx.essence.tx_type());
trace!(" Fr: {:?}", tx_from);
trace!(" Fr: {tx_from:?}");
trace!(" To: {:?}", tx.essence.to().unwrap_or_default());
}

// verify transaction gas
let block_available_gas =
block_builder.input.state_input.gas_limit - cumulative_gas_used;
if block_available_gas < tx.essence.gas_limit() {
bail!("Error at transaction {}: gas exceeds block limit", tx_no);
bail!("Error at transaction {tx_no}: gas exceeds block limit");
}

// cache account nonce if the transaction is a deposit, starting with Canyon
Expand Down Expand Up @@ -176,15 +176,15 @@ impl TxExecStrategy<OptimismTxEssence> for OpTxExecStrategy {
// process the transaction
let ResultAndState { result, state } = evm
.transact()
.map_err(|evm_err| anyhow!("Error at transaction {}: {:?}", tx_no, evm_err))
.map_err(|evm_err| anyhow!("Error at transaction {tx_no}: {evm_err:?}"))
// todo: change unrecoverable panic to host-side recoverable `Result`
.expect("Block construction failure.");

let gas_used = result.gas_used().try_into().unwrap();
let gas_used = U256::from(result.gas_used());
cumulative_gas_used = cumulative_gas_used.checked_add(gas_used).unwrap();

#[cfg(not(target_os = "zkvm"))]
trace!(" Ok: {:?}", result);
trace!(" Ok: {result:?}");

// create the receipt from the EVM result
let mut receipt = Receipt::new(
Expand All @@ -203,8 +203,7 @@ impl TxExecStrategy<OptimismTxEssence> for OpTxExecStrategy {
if account.is_touched() {
// log account
trace!(
" State {:?} (is_selfdestructed={}, is_loaded_as_not_existing={}, is_created={})",
address,
" State {address:?} (is_selfdestructed={}, is_loaded_as_not_existing={}, is_created={})",
account.is_selfdestructed(),
account.is_loaded_as_not_existing(),
account.is_created()
Expand All @@ -219,7 +218,7 @@ impl TxExecStrategy<OptimismTxEssence> for OpTxExecStrategy {
// log state changes
for (addr, slot) in &account.storage {
if slot.is_changed() {
trace!(" Storage address: {:?}", addr);
trace!(" Storage address: {addr:?}");
trace!(" Before: {:?}", slot.original_value());
trace!(" After: {:?}", slot.present_value());
}
Expand Down Expand Up @@ -249,11 +248,7 @@ impl TxExecStrategy<OptimismTxEssence> for OpTxExecStrategy {
header.receipts_root = receipt_trie.hash();
header.logs_bloom = logs_bloom;
header.gas_used = cumulative_gas_used;
header.withdrawals_root = if spec_id < SpecId::CANYON {
None
} else {
Some(EMPTY_ROOT)
};
header.withdrawals_root = (spec_id >= SpecId::CANYON).then_some(EMPTY_ROOT);

// Leak memory, save cycles
guest_mem_forget([tx_trie, receipt_trie]);
Expand Down
14 changes: 4 additions & 10 deletions lib/src/builder/prepare.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,16 +51,14 @@ impl HeaderPrepStrategy for EthHeaderPrepStrategy {
block_builder.input.state_input.parent_header.gas_limit / GAS_LIMIT_BOUND_DIVISOR;
if diff >= limit {
bail!(
"Invalid gas limit: expected {} +- {}, got {}",
"Invalid gas limit: expected {} +- {limit}, got {}",
block_builder.input.state_input.parent_header.gas_limit,
limit,
block_builder.input.state_input.gas_limit,
);
}
if block_builder.input.state_input.gas_limit < MIN_GAS_LIMIT {
bail!(
"Invalid gas limit: expected >= {}, got {}",
MIN_GAS_LIMIT,
"Invalid gas limit: expected >= {MIN_GAS_LIMIT}, got {}",
block_builder.input.state_input.gas_limit,
);
}
Expand All @@ -76,11 +74,7 @@ impl HeaderPrepStrategy for EthHeaderPrepStrategy {
// Validate extra data
let extra_data_bytes = block_builder.input.state_input.extra_data.len();
if extra_data_bytes > MAX_EXTRA_DATA_BYTES {
bail!(
"Invalid extra data: expected <= {}, got {}",
MAX_EXTRA_DATA_BYTES,
extra_data_bytes,
)
bail!("Invalid extra data: expected <= {MAX_EXTRA_DATA_BYTES}, got {extra_data_bytes}",)
}
// Validate number
let parent_number = block_builder.input.state_input.parent_header.number;
Expand All @@ -92,7 +86,7 @@ impl HeaderPrepStrategy for EthHeaderPrepStrategy {
let spec_id = block_builder
.chain_spec
.active_fork(number, &timestamp)
.unwrap_or_else(|err| panic!("Invalid version: {:#}", err));
.unwrap_or_else(|err| panic!("Invalid version: {err:#}"));
block_builder.spec_id = Some(spec_id);
// Derive header
block_builder.header = Some(Header {
Expand Down
14 changes: 7 additions & 7 deletions lib/src/host/mpt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,18 +42,18 @@ pub fn mpt_from_proof(proof_nodes: &[MptNode]) -> Result<MptNode> {
// find the child that references the next node
let resolved: MptNode = match node.as_data().clone() {
MptNodeData::Branch(mut children) => {
if let Some(child) = children.iter_mut().flatten().find(
let Some(child) = children.iter_mut().flatten().find(
|child| matches!(child.as_data(), MptNodeData::Digest(d) if d == child_ref),
) {
*child = Box::new(replacement);
} else {
bail!("node {} does not reference the successor", i);
}
) else {
bail!("node {i} does not reference the successor");
};
*child = Box::new(replacement);

MptNodeData::Branch(children).into()
}
MptNodeData::Extension(prefix, child) => {
if !matches!(child.as_data(), MptNodeData::Digest(d) if d == child_ref) {
bail!("node {} does not reference the successor", i);
bail!("node {i} does not reference the successor");
}
MptNodeData::Extension(prefix, Box::new(replacement)).into()
}
Expand Down
22 changes: 12 additions & 10 deletions lib/src/host/preflight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -309,7 +309,7 @@ fn proofs_to_tries(

let fini_proofs = proofs
.get(&address)
.with_context(|| format!("missing fini_proofs for address {:#}", &address))?;
.with_context(|| format!("missing fini_proofs for address {address:#}"))?;

// assure that addresses can be deleted from the state trie
add_orphaned_leafs(address, &fini_proofs.account_proof, &mut state_nodes)?;
Expand Down Expand Up @@ -366,15 +366,17 @@ fn add_orphaned_leafs(
proof: &[impl AsRef<[u8]>],
nodes_by_reference: &mut HashMap<MptNodeReference, MptNode>,
) -> Result<()> {
if !proof.is_empty() {
let proof_nodes = parse_proof(proof).context("invalid proof encoding")?;
if is_not_included(&keccak(key), &proof_nodes)? {
// add the leaf node to the nodes
let leaf = proof_nodes.last().unwrap();
shorten_node_path(leaf).into_iter().for_each(|node| {
nodes_by_reference.insert(node.reference(), node);
});
}
if proof.is_empty() {
return Ok(());
}

let proof_nodes = parse_proof(proof).context("invalid proof encoding")?;
if is_not_included(&keccak(key), &proof_nodes)? {
// add the leaf node to the nodes
let leaf = proof_nodes.last().unwrap();
shorten_node_path(leaf).into_iter().for_each(|node| {
nodes_by_reference.insert(node.reference(), node);
});
}

Ok(())
Expand Down
16 changes: 8 additions & 8 deletions lib/src/host/provider/file_provider.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,56 +144,56 @@ impl Provider for FileProvider {
fn get_full_block(&mut self, query: &BlockQuery) -> Result<Block<Transaction>> {
match self.full_blocks.get(query) {
Some(val) => Ok(val.clone()),
None => Err(anyhow!("No data for {:?}", query)),
None => Err(anyhow!("No data for {query:?}")),
}
}

fn get_partial_block(&mut self, query: &BlockQuery) -> Result<Block<H256>> {
match self.partial_blocks.get(query) {
Some(val) => Ok(val.clone()),
None => Err(anyhow!("No data for {:?}", query)),
None => Err(anyhow!("No data for {query:?}")),
}
}

fn get_block_receipts(&mut self, query: &BlockQuery) -> Result<Vec<TransactionReceipt>> {
match self.receipts.get(query) {
Some(val) => Ok(val.clone()),
None => Err(anyhow!("No data for {:?}", query)),
None => Err(anyhow!("No data for {query:?}")),
}
}

fn get_proof(&mut self, query: &ProofQuery) -> Result<EIP1186ProofResponse> {
match self.proofs.get(query) {
Some(val) => Ok(val.clone()),
None => Err(anyhow!("No data for {:?}", query)),
None => Err(anyhow!("No data for {query:?}")),
}
}

fn get_transaction_count(&mut self, query: &AccountQuery) -> Result<U256> {
match self.transaction_count.get(query) {
Some(val) => Ok(*val),
None => Err(anyhow!("No data for {:?}", query)),
None => Err(anyhow!("No data for {query:?}")),
}
}

fn get_balance(&mut self, query: &AccountQuery) -> Result<U256> {
match self.balance.get(query) {
Some(val) => Ok(*val),
None => Err(anyhow!("No data for {:?}", query)),
None => Err(anyhow!("No data for {query:?}")),
}
}

fn get_code(&mut self, query: &AccountQuery) -> Result<Bytes> {
match self.code.get(query) {
Some(val) => Ok(val.clone()),
None => Err(anyhow!("No data for {:?}", query)),
None => Err(anyhow!("No data for {query:?}")),
}
}

fn get_storage(&mut self, query: &StorageQuery) -> Result<H256> {
match self.storage.get(query) {
Some(val) => Ok(*val),
None => Err(anyhow!("No data for {:?}", query)),
None => Err(anyhow!("No data for {query:?}")),
}
}
}
Expand Down
Loading
Loading