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

EVM: Recovering transaction signer in the EVM module. #639

Merged
merged 11 commits into from
Aug 10, 2023
Merged
Show file tree
Hide file tree
Changes from 8 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
1 change: 1 addition & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,8 @@ reth-revm = { git = "https://github.com/paradigmxyz/reth", version = "0.1.0-alph
revm = { git = "https://github.com/bluealloy/revm/", branch = "release/v25" }
revm-primitives = { git = "https://github.com/bluealloy/revm/", branch = "release/v25" }

secp256k1 = { version = "0.27.0", default-features = false, features = ["global-context", "rand-std", "recovery"] }

[patch.crates-io]
# See reth: https://github.com/paradigmxyz/reth/blob/main/Cargo.toml#L79
revm = { git = "https://github.com/bluealloy/revm/", branch = "release/v25" }
Expand Down
36 changes: 23 additions & 13 deletions full-node/sov-ethereum/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@ pub mod experimental {
use jsonrpsee::types::ErrorObjectOwned;
use jsonrpsee::RpcModule;
use jupiter::da_service::DaServiceConfig;
use reth_primitives::Bytes as RethBytes;
use reth_primitives::TransactionSignedNoHash as RethTransactionSignedNoHash;
use reth_rpc::eth::error::EthApiError;
use sov_evm::call::CallMessage;
use sov_evm::evm::{EthAddress, EvmTransaction};
use sov_evm::evm::{EthAddress, RawEvmTransaction};
use sov_modules_api::transaction::Transaction;
use sov_modules_api::utils::to_jsonrpsee_error_object;
use sov_modules_api::EncodeCall;
Expand Down Expand Up @@ -47,24 +48,36 @@ pub mod experimental {
}

impl Ethereum {
fn make_raw_tx(&self, evm_tx: EvmTransaction) -> Result<Vec<u8>, std::io::Error> {
fn make_raw_tx(
&self,
raw_tx: RawEvmTransaction,
) -> Result<(H256, Vec<u8>), jsonrpsee::core::Error> {
let signed_transaction: RethTransactionSignedNoHash =
raw_tx.clone().try_into().map_err(EthApiError::from)?;

let tx_hash = signed_transaction.hash();
let sender = signed_transaction
.recover_signer()
.ok_or(EthApiError::InvalidTransactionSignature)?;

let mut nonces = self.nonces.lock().unwrap();
let nonce = *nonces
.entry(evm_tx.sender)
.entry(sender.into())
bkolad marked this conversation as resolved.
Show resolved Hide resolved
.and_modify(|n| *n += 1)
.or_insert(0);

let tx = CallMessage { tx: evm_tx };
let tx = CallMessage { tx: raw_tx };
let message =
<Runtime<DefaultContext> as EncodeCall<sov_evm::Evm<DefaultContext>>>::encode_call(
tx,
);

let tx = Transaction::<DefaultContext>::new_signed_tx(
&self.tx_signer_prov_key,
message,
nonce,
);
tx.try_to_vec()
Ok((H256::from(tx_hash), tx.try_to_vec()?))
}
}

Expand Down Expand Up @@ -111,21 +124,18 @@ pub mod experimental {
"eth_sendRawTransaction",
|parameters, ethereum| async move {
let data: Bytes = parameters.one().unwrap();
let data = RethBytes::from(data.as_ref());

let evm_transaction: EvmTransaction = data.try_into()?;

let tx_hash = evm_transaction.hash;
let raw_tx = ethereum
.make_raw_tx(evm_transaction)
let raw_evm_tx = RawEvmTransaction { tx: data.to_vec() };
let (tx_hash, raw_tx) = ethereum
.make_raw_tx(raw_evm_tx)
.map_err(|e| to_jsonrpsee_error_object(e, ETH_RPC_ERROR))?;

ethereum
.send_tx_to_da(raw_tx)
.await
.map_err(|e| to_jsonrpsee_error_object(e, ETH_RPC_ERROR))?;

Ok::<_, ErrorObjectOwned>(H256::from(tx_hash))
Ok::<_, ErrorObjectOwned>(tx_hash)
},
)?;

Expand Down
5 changes: 2 additions & 3 deletions module-system/module-implementations/sov-evm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,6 @@ ethers-contract = { workspace = true }
ethers-middleware = { workspace = true }
ethers-providers = { workspace = true }
ethers-signers = { workspace = true }



ethers = { workspace = true }

revm = { workspace = true }
Expand All @@ -48,12 +45,14 @@ reth-rpc-types = { workspace = true }
reth-rpc = { workspace = true }
reth-revm = { workspace = true }


[dev-dependencies]

primitive-types = "0.12.1"
tokio = { workspace = true }
tempfile = { workspace = true }
bytes = { workspace = true }
secp256k1 = { workspace = true }

sov-modules-api = { path = "../../sov-modules-api", version = "0.1", features = ["macros"] }

Expand Down
22 changes: 12 additions & 10 deletions module-system/module-implementations/sov-evm/src/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use sov_state::WorkingSet;

use crate::evm::db::EvmDb;
use crate::evm::executor::{self};
use crate::evm::transaction::{BlockEnv, EvmTransaction};
use crate::evm::{contract_address, EvmChainCfg};
use crate::evm::transaction::{BlockEnv, EvmTransactionSignedEcRecovered};
use crate::evm::{contract_address, EvmChainCfg, RawEvmTransaction};
use crate::experimental::SpecIdWrapper;
use crate::{Evm, TransactionReceipt};

Expand All @@ -18,38 +18,40 @@ use crate::{Evm, TransactionReceipt};
)]
#[derive(borsh::BorshDeserialize, borsh::BorshSerialize, Debug, PartialEq, Clone)]
pub struct CallMessage {
pub tx: EvmTransaction,
pub tx: RawEvmTransaction,
}

impl<C: sov_modules_api::Context> Evm<C> {
pub(crate) fn execute_call(
&self,
tx: EvmTransaction,
tx: RawEvmTransaction,
_context: &C,
working_set: &mut WorkingSet<C::Storage>,
) -> Result<CallResponse> {
// TODO https://github.com/Sovereign-Labs/sovereign-sdk/issues/515
let evm_tx_recovered: EvmTransactionSignedEcRecovered = tx.clone().try_into()?;

let block_env = self.block_env.get(working_set).unwrap_or_default();
let cfg = self.cfg.get(working_set).unwrap_or_default();
let cfg_env = get_cfg_env(&block_env, cfg, None);
self.transactions.set(&tx.hash, &tx, working_set);

let hash = evm_tx_recovered.hash();
self.transactions.set(&hash, &tx, working_set);

let evm_db: EvmDb<'_, C> = self.get_db(working_set);

// TODO https://github.com/Sovereign-Labs/sovereign-sdk/issues/505
let result = executor::execute_tx(evm_db, block_env, tx.clone(), cfg_env).unwrap();
let result = executor::execute_tx(evm_db, block_env, &evm_tx_recovered, cfg_env).unwrap();

let receipt = TransactionReceipt {
transaction_hash: tx.hash,
transaction_hash: hash.into(),
// TODO https://github.com/Sovereign-Labs/sovereign-sdk/issues/504
transaction_index: 0,
// TODO https://github.com/Sovereign-Labs/sovereign-sdk/issues/504
block_hash: Default::default(),
// TODO https://github.com/Sovereign-Labs/sovereign-sdk/issues/504
block_number: Some(0),
from: tx.sender,
to: tx.to,
from: evm_tx_recovered.signer().into(),
to: evm_tx_recovered.to(),
// TODO https://github.com/Sovereign-Labs/sovereign-sdk/issues/504
cumulative_gas_used: Default::default(),
// TODO https://github.com/Sovereign-Labs/sovereign-sdk/issues/504
Expand Down
79 changes: 79 additions & 0 deletions module-system/module-implementations/sov-evm/src/dev_signer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
use ethers_core::rand::rngs::StdRng;
use ethers_core::rand::SeedableRng;
use reth_primitives::{
public_key_to_address, sign_message, Bytes as RethBytes, Transaction as RethTransaction,
TransactionKind, TransactionSigned, TxEip1559 as RethTxEip1559, H256,
};
use reth_rpc::eth::error::SignError;
use secp256k1::{PublicKey, SecretKey};

use crate::evm::{EthAddress, RawEvmTransaction};

/// ETH transactions signer used in tests.
LukaszRozmej marked this conversation as resolved.
Show resolved Hide resolved
pub(crate) struct DevSigner {
secret_key: SecretKey,
pub(crate) address: EthAddress,
}

impl DevSigner {
/// Creates a new signer.
pub(crate) fn new(secret_key: SecretKey) -> Self {
let public_key = PublicKey::from_secret_key(secp256k1::SECP256K1, &secret_key);
let addr = public_key_to_address(public_key);
Self {
secret_key,
address: addr.into(),
}
}

/// Creates a new signer with random private key.
pub(crate) fn new_random() -> Self {
let mut rng = StdRng::seed_from_u64(22);
let secret_key = SecretKey::new(&mut rng);
Self::new(secret_key)
}

/// Signs Eip1559 transaction.
pub(crate) fn sign_transaction(
&self,
transaction: RethTxEip1559,
) -> Result<TransactionSigned, SignError> {
let transaction = RethTransaction::Eip1559(transaction);

let tx_signature_hash = transaction.signature_hash();

let signature = sign_message(
H256::from_slice(self.secret_key.as_ref()),
tx_signature_hash,
)
.map_err(|_| SignError::CouldNotSign)?;

Ok(TransactionSigned::from_transaction_and_signature(
transaction,
signature,
))
}

/// Signs default Eip1559 transaction with to, data and nonce overridden.
pub(crate) fn sign_default_transaction(
&self,
to: TransactionKind,
data: Vec<u8>,
nonce: u64,
) -> Result<RawEvmTransaction, SignError> {
let reth_tx = RethTxEip1559 {
to,
input: RethBytes::from(data),
nonce,
chain_id: 1,
gas_limit: u64::MAX,
..Default::default()
};

let signed = self.sign_transaction(reth_tx)?;

Ok(RawEvmTransaction {
tx: signed.envelope_encoded().to_vec(),
})
}
}
Loading