Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/main' into alexey/eip-7002-withd…
Browse files Browse the repository at this point in the history
…rawal-requests
  • Loading branch information
shekhirin committed May 13, 2024
2 parents 6a0f553 + c2a05f0 commit 602bd89
Show file tree
Hide file tree
Showing 10 changed files with 105 additions and 74 deletions.
22 changes: 14 additions & 8 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

68 changes: 38 additions & 30 deletions crates/primitives/src/account.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
use crate::{
keccak256,
revm_primitives::{Bytecode as RevmBytecode, BytecodeState, Bytes, JumpMap},
revm_primitives::{Bytecode as RevmBytecode, Bytes},
GenesisAccount, B256, KECCAK_EMPTY, U256,
};
use byteorder::{BigEndian, ReadBytesExt};
use bytes::Buf;
use reth_codecs::{main_codec, Compact};
use revm_primitives::JumpTable;
use serde::{Deserialize, Serialize};
use std::ops::Deref;

Expand Down Expand Up @@ -80,27 +81,29 @@ impl Compact for Bytecode {
where
B: bytes::BufMut + AsMut<[u8]>,
{
buf.put_u32(self.0.bytecode.len() as u32);
buf.put_slice(self.0.bytecode.as_ref());
let len = match self.0.state() {
BytecodeState::Raw => {
let bytecode = &self.0.bytecode()[..];
buf.put_u32(bytecode.len() as u32);
buf.put_slice(bytecode);
let len = match &self.0 {
RevmBytecode::LegacyRaw(_) => {
buf.put_u8(0);
1
}
BytecodeState::Checked { len } => {
buf.put_u8(1);
buf.put_u64(*len as u64);
9
}
BytecodeState::Analysed { len, jump_map } => {
// `1` has been removed.
RevmBytecode::LegacyAnalyzed(analyzed) => {
buf.put_u8(2);
buf.put_u64(*len as u64);
let map = jump_map.as_slice();
buf.put_u64(analyzed.original_len() as u64);
let map = analyzed.jump_table().as_slice();
buf.put_slice(map);
9 + map.len()
1 + 8 + map.len()
}
RevmBytecode::Eof(_) => {
// buf.put_u8(3);
// TODO(EOF)
todo!("EOF")
}
};
len + self.0.bytecode.len() + 4
len + bytecode.len() + 4
}

fn from_compact(mut buf: &[u8], _: usize) -> (Self, &[u8]) {
Expand All @@ -109,17 +112,17 @@ impl Compact for Bytecode {
let variant = buf.read_u8().expect("could not read bytecode variant");
let decoded = match variant {
0 => Bytecode(RevmBytecode::new_raw(bytes)),
1 => Bytecode(unsafe {
RevmBytecode::new_checked(bytes, buf.read_u64::<BigEndian>().unwrap() as usize)
}),
2 => Bytecode(RevmBytecode {
bytecode: bytes,
state: BytecodeState::Analysed {
len: buf.read_u64::<BigEndian>().unwrap() as usize,
jump_map: JumpMap::from_slice(buf),
},
1 => unreachable!("Junk data in database: checked Bytecode variant was removed"),
2 => Bytecode(unsafe {
RevmBytecode::new_analyzed(
bytes,
buf.read_u64::<BigEndian>().unwrap() as usize,
JumpTable::from_slice(buf),
)
}),
_ => unreachable!("Junk data in database: unknown BytecodeState variant"),
// TODO(EOF)
3 => todo!("EOF"),
_ => unreachable!("Junk data in database: unknown Bytecode variant"),
};
(decoded, &[])
}
Expand All @@ -129,6 +132,7 @@ impl Compact for Bytecode {
mod tests {
use super::*;
use crate::hex_literal::hex;
use revm_primitives::LegacyAnalyzedBytecode;

#[test]
fn test_account() {
Expand Down Expand Up @@ -174,17 +178,21 @@ mod tests {
#[test]
fn test_bytecode() {
let mut buf = vec![];
let mut bytecode = Bytecode(RevmBytecode::new_raw(Bytes::default()));
let len = bytecode.clone().to_compact(&mut buf);
let bytecode = Bytecode::new_raw(Bytes::default());
let len = bytecode.to_compact(&mut buf);
assert_eq!(len, 5);

let mut buf = vec![];
bytecode.0.bytecode = Bytes::from(hex!("ffff").as_ref());
let len = bytecode.clone().to_compact(&mut buf);
let bytecode = Bytecode::new_raw(Bytes::from(&hex!("ffff")));
let len = bytecode.to_compact(&mut buf);
assert_eq!(len, 7);

let mut buf = vec![];
bytecode.0.state = BytecodeState::Analysed { len: 2, jump_map: JumpMap::from_slice(&[0]) };
let bytecode = Bytecode(RevmBytecode::LegacyAnalyzed(LegacyAnalyzedBytecode::new(
Bytes::from(&hex!("ffff")),
2,
JumpTable::from_slice(&[0]),
)));
let len = bytecode.clone().to_compact(&mut buf);
assert_eq!(len, 16);

Expand Down
2 changes: 1 addition & 1 deletion crates/primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ pub use alloy_primitives::{
StorageValue, TxHash, TxIndex, TxKind, TxNumber, B128, B256, B512, B64, U128, U256, U64, U8,
};
pub use reth_ethereum_forks::*;
pub use revm_primitives::{self, JumpMap};
pub use revm_primitives::{self, JumpTable};

#[doc(hidden)]
#[deprecated = "use B64 instead"]
Expand Down
14 changes: 5 additions & 9 deletions crates/primitives/src/revm/compat.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
use crate::{revm_primitives::AccountInfo, Account, Address, TxKind, KECCAK_EMPTY, U256};
use revm::{
interpreter::gas::validate_initial_tx_gas,
primitives::{MergeSpec, ShanghaiSpec},
};
use revm::{interpreter::gas::validate_initial_tx_gas, primitives::SpecId};

/// Converts a Revm [`AccountInfo`] into a Reth [`Account`].
///
Expand Down Expand Up @@ -38,9 +35,8 @@ pub fn calculate_intrinsic_gas_after_merge(
access_list: &[(Address, Vec<U256>)],
is_shanghai: bool,
) -> u64 {
if is_shanghai {
validate_initial_tx_gas::<ShanghaiSpec>(input, kind.is_create(), access_list)
} else {
validate_initial_tx_gas::<MergeSpec>(input, kind.is_create(), access_list)
}
let spec_id = if is_shanghai { SpecId::SHANGHAI } else { SpecId::MERGE };
// TODO(EOF)
let initcodes = &[];
validate_initial_tx_gas(spec_id, input, kind.is_create(), access_list, initcodes)
}
3 changes: 3 additions & 0 deletions crates/primitives/src/revm/env.rs
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,9 @@ fn fill_tx_env_with_system_contract_call(
// enveloped tx size.
enveloped_tx: Some(Bytes::default()),
},
// TODO(EOF)
eof_initcodes: vec![],
eof_initcodes_hashed: Default::default(),
};

// ensure the block gas limit is >= the tx
Expand Down
2 changes: 1 addition & 1 deletion crates/revm/src/state_change.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ where
}

// get previous env
let previous_env = Box::new(evm.env().clone());
let previous_env = Box::new(evm.context.env().clone());

// modify env for pre block call
fill_tx_env_with_beacon_root_contract_call(&mut evm.context.evm.env, parent_beacon_block_root);
Expand Down
2 changes: 1 addition & 1 deletion crates/rpc/rpc/src/eth/api/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ where
ExecutionResult::Success { .. } => {
// transaction succeeded by manually increasing the gas limit to
// highest, which means the caller lacks funds to pay for the tx
RpcInvalidTransactionError::BasicOutOfGas(U256::from(req_gas_limit)).into()
RpcInvalidTransactionError::BasicOutOfGas(req_gas_limit).into()
}
ExecutionResult::Revert { output, .. } => {
// reverted again after bumping the limit
Expand Down
61 changes: 38 additions & 23 deletions crates/rpc/rpc/src/eth/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use crate::result::{internal_rpc_err, invalid_params_rpc_err, rpc_err, rpc_error
use alloy_sol_types::decode_revert_reason;
use jsonrpsee::types::{error::CALL_EXECUTION_FAILED_CODE, ErrorObject};
use reth_interfaces::RethError;
use reth_primitives::{revm_primitives::InvalidHeader, Address, Bytes, U256};
use reth_primitives::{revm_primitives::InvalidHeader, Address, Bytes};
use reth_rpc_types::{
error::EthRpcErrorCode, request::TransactionInputError, BlockError, ToRpcError,
};
Expand Down Expand Up @@ -267,14 +267,14 @@ pub enum RpcInvalidTransactionError {
/// Thrown when calculating gas usage
#[error("gas uint64 overflow")]
GasUintOverflow,
/// returned if the transaction is specified to use less gas than required to start the
/// Thrown if the transaction is specified to use less gas than required to start the
/// invocation.
#[error("intrinsic gas too low")]
GasTooLow,
/// returned if the transaction gas exceeds the limit
/// Thrown if the transaction gas exceeds the limit
#[error("intrinsic gas too high")]
GasTooHigh,
/// thrown if a transaction is not supported in the current network configuration.
/// Thrown if a transaction is not supported in the current network configuration.
#[error("transaction type not supported")]
TxTypeNotSupported,
/// Thrown to ensure no one is able to specify a transaction with a tip higher than the total
Expand All @@ -291,25 +291,29 @@ pub enum RpcInvalidTransactionError {
#[error("max fee per gas less than block base fee")]
FeeCapTooLow,
/// Thrown if the sender of a transaction is a contract.
#[error("sender not an eoa")]
#[error("sender is not an EOA")]
SenderNoEOA,
/// Thrown during estimate if caller has insufficient funds to cover the tx.
#[error("out of gas: gas required exceeds allowance: {0:?}")]
BasicOutOfGas(U256),
/// As BasicOutOfGas but thrown when gas exhausts during memory expansion.
#[error("out of gas: gas exhausts during memory expansion: {0:?}")]
MemoryOutOfGas(U256),
/// As BasicOutOfGas but thrown when gas exhausts during precompiled contract execution.
#[error("out of gas: gas exhausts during precompiled contract execution: {0:?}")]
PrecompileOutOfGas(U256),
/// revm's Type cast error, U256 casts down to a u64 with overflow
#[error("out of gas: revm's Type cast error, U256 casts down to a u64 with overflow {0:?}")]
InvalidOperandOutOfGas(U256),
/// Gas limit was exceeded during execution.
/// Contains the gas limit.
#[error("out of gas: gas required exceeds allowance: {0}")]
BasicOutOfGas(u64),
/// Gas limit was exceeded during memory expansion.
/// Contains the gas limit.
#[error("out of gas: gas exhausted during memory expansion: {0}")]
MemoryOutOfGas(u64),
/// Gas limit was exceeded during precompile execution.
/// Contains the gas limit.
#[error("out of gas: gas exhausted during precompiled contract execution: {0}")]
PrecompileOutOfGas(u64),
/// An operand to an opcode was invalid or out of range.
/// Contains the gas limit.
#[error("out of gas: invalid operand to an opcode; {0}")]
InvalidOperandOutOfGas(u64),
/// Thrown if executing a transaction failed during estimate/call
#[error("{0}")]
#[error(transparent)]
Revert(RevertError),
/// Unspecific EVM halt error.
#[error("EVM error {0:?}")]
#[error("EVM error: {0:?}")]
EvmHalt(HaltReason),
/// Invalid chain id set for the transaction.
#[error("invalid chain ID")]
Expand Down Expand Up @@ -337,8 +341,13 @@ pub enum RpcInvalidTransactionError {
#[error("blob transaction missing blob hashes")]
BlobTransactionMissingBlobHashes,
/// Blob transaction has too many blobs
#[error("blob transaction exceeds max blobs per block")]
TooManyBlobs,
#[error("blob transaction exceeds max blobs per block; got {have}, max {max}")]
TooManyBlobs {
/// The maximum number of blobs allowed.
max: usize,
/// The number of blobs in the transaction.
have: usize,
},
/// Blob transaction is a create transaction
#[error("blob transaction is a create transaction")]
BlobTransactionIsCreate,
Expand Down Expand Up @@ -385,7 +394,6 @@ impl RpcInvalidTransactionError {

/// Converts the out of gas error
pub(crate) fn out_of_gas(reason: OutOfGasError, gas_limit: u64) -> Self {
let gas_limit = U256::from(gas_limit);
match reason {
OutOfGasError::Basic => RpcInvalidTransactionError::BasicOutOfGas(gas_limit),
OutOfGasError::Memory => RpcInvalidTransactionError::MemoryOutOfGas(gas_limit),
Expand Down Expand Up @@ -462,7 +470,9 @@ impl From<revm::primitives::InvalidTransaction> for RpcInvalidTransactionError {
InvalidTransaction::BlobVersionNotSupported => {
RpcInvalidTransactionError::BlobHashVersionMismatch
}
InvalidTransaction::TooManyBlobs => RpcInvalidTransactionError::TooManyBlobs,
InvalidTransaction::TooManyBlobs { max, have } => {
RpcInvalidTransactionError::TooManyBlobs { max, have }
}
InvalidTransaction::BlobCreateTransaction => {
RpcInvalidTransactionError::BlobTransactionIsCreate
}
Expand All @@ -476,6 +486,11 @@ impl From<revm::primitives::InvalidTransaction> for RpcInvalidTransactionError {
InvalidTransaction::HaltedDepositPostRegolith => RpcInvalidTransactionError::Optimism(
OptimismInvalidTransactionError::HaltedDepositPostRegolith,
),
// TODO(EOF)
InvalidTransaction::EofInitcodesNotSupported => todo!("EOF"),
InvalidTransaction::EofInitcodesNumberLimit => todo!("EOF"),
InvalidTransaction::EofInitcodesSizeLimit => todo!("EOF"),
InvalidTransaction::EofCrateShouldHaveToAddress => todo!("EOF"),
}
}
}
Expand Down
3 changes: 3 additions & 0 deletions crates/rpc/rpc/src/eth/revm_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -272,6 +272,9 @@ pub(crate) fn create_txn_env(
max_fee_per_blob_gas,
#[cfg(feature = "optimism")]
optimism: OptimismFields { enveloped_tx: Some(Bytes::new()), ..Default::default() },
// TODO(EOF)
eof_initcodes: Default::default(),
eof_initcodes_hashed: Default::default(),
};

Ok(env)
Expand Down
2 changes: 1 addition & 1 deletion examples/exex/rollup/src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ impl Database {
for (hash, bytecode) in changeset.contracts {
tx.execute(
"INSERT INTO bytecode (hash, data) VALUES (?, ?) ON CONFLICT(hash) DO NOTHING",
(hash.to_string(), bytecode.bytes().to_string()),
(hash.to_string(), bytecode.bytecode().to_string()),
)?;
}

Expand Down

0 comments on commit 602bd89

Please sign in to comment.