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

Support eip-1559 #1709

Merged
merged 5 commits into from
Dec 18, 2021
Merged
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
4 changes: 2 additions & 2 deletions primitives/src/evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -88,15 +88,15 @@ pub struct EstimateResourcesRequest {
#[derive(Clone, Eq, PartialEq, Encode, Decode, RuntimeDebug, TypeInfo)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub struct EthereumTransactionMessage {
pub chain_id: u64,
pub genesis: H256,
pub nonce: Nonce,
pub tip: Balance,
pub gas_limit: u64,
pub storage_limit: u32,
pub action: TransactionAction,
pub value: Balance,
pub input: Vec<u8>,
pub chain_id: u64,
pub genesis: H256,
pub valid_until: BlockNumber,
}

Expand Down
2 changes: 2 additions & 0 deletions primitives/src/signature.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ pub enum AcalaMultiSignature {
Ecdsa(ecdsa::Signature),
// An Ethereum compatible SECP256k1 signature.
Ethereum([u8; 65]),
// An Ethereum SECP256k1 signature using Eip1559 for message encoding.
Eip1559([u8; 65]),
// An Ethereum SECP256k1 signature using Eip712 for message encoding.
AcalaEip712([u8; 65]),
}
Expand Down
137 changes: 130 additions & 7 deletions primitives/src/unchecked_extrinsic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ use frame_support::{
traits::{ExtrinsicCall, Get},
weights::{DispatchInfo, GetDispatchInfo},
};
use module_evm_utiltity::ethereum::{LegacyTransactionMessage, TransactionAction};
use module_evm_utiltity::ethereum::{EIP1559TransactionMessage, LegacyTransactionMessage, TransactionAction};
use module_evm_utiltity_macro::keccak256;
use scale_info::TypeInfo;
use sp_core::{H160, H256, U256};
Expand Down Expand Up @@ -143,8 +143,8 @@ where
.saturating_add(eth_msg.gas_limit.into());

log::trace!(
target: "evm", "eth_msg.gas_limit: {:?}, eth_msg.storage_limit: {:?}, tx_gas_limit: {:?}, tx_gas_price: {:?}",
eth_msg.storage_limit, eth_msg.gas_limit, tx_gas_limit, tx_gas_price
target: "evm", "eth_msg.tip: {:?}, eth_msg.gas_limit: {:?}, eth_msg.storage_limit: {:?}, tx_gas_limit: {:?}, tx_gas_price: {:?}",
eth_msg.tip, eth_msg.storage_limit, eth_msg.gas_limit, tx_gas_limit, tx_gas_price
);

let msg = LegacyTransactionMessage {
Expand Down Expand Up @@ -173,6 +173,68 @@ where
function,
})
}
Some((addr, AcalaMultiSignature::Eip1559(sig), extra)) => {
let function = self.0.function;
let eth_msg = ConvertTx::convert((function.clone(), extra.clone()))?;

// tx_gas_price = tx_fee_per_gas + block_period << 16 + storage_entry_limit
// tx_gas_limit = gas_limit + storage_entry_deposit / tx_fee_per_gas * storage_entry_limit
let block_period = eth_msg.valid_until.checked_div(30).expect("divisor is non-zero; qed");
// u16: max value 0xffff * 64 = 4194240 bytes = 4MB
let storage_entry_limit: u16 = eth_msg
.storage_limit
.checked_div(64)
.expect("divisor is non-zero; qed")
.try_into()
.map_err(|_| InvalidTransaction::BadProof)?;
let storage_entry_deposit = StorageDepositPerByte::get().saturating_mul(64);
let tx_gas_price = TxFeePerGas::get()
.saturating_add((block_period << 16).into())
.saturating_add(storage_entry_limit.into());
// There is a loss of precision here, so the order of calculation must be guaranteed
// must ensure storage_deposit / tx_fee_per_gas * storage_limit
let tx_gas_limit = storage_entry_deposit
.checked_div(TxFeePerGas::get())
.expect("divisor is non-zero; qed")
.saturating_mul(storage_entry_limit.into())
.saturating_add(eth_msg.gas_limit.into());

// tip = priority_fee * gas_limit
let priority_fee = eth_msg.tip.checked_div(eth_msg.gas_limit.into()).unwrap_or_default();

log::trace!(
target: "evm", "eth_msg.tip: {:?}, eth_msg.gas_limit: {:?}, eth_msg.storage_limit: {:?}, tx_gas_limit: {:?}, tx_gas_price: {:?}",
eth_msg.tip, eth_msg.storage_limit, eth_msg.gas_limit, tx_gas_limit, tx_gas_price
);

let msg = EIP1559TransactionMessage {
chain_id: eth_msg.chain_id,
nonce: eth_msg.nonce.into(),
max_priority_fee_per_gas: priority_fee.into(),
max_fee_per_gas: tx_gas_price.into(),
gas_limit: tx_gas_limit.into(),
action: eth_msg.action,
value: eth_msg.value.into(),
input: eth_msg.input,
access_list: vec![],
};

let msg_hash = msg.hash(); // TODO: consider rewirte this to use `keccak_256` for hashing because it could be faster

let signer = recover_signer(&sig, msg_hash.as_fixed_bytes()).ok_or(InvalidTransaction::BadProof)?;

let acc = lookup.lookup(Address::Address20(signer.into()))?;
let expected = lookup.lookup(addr)?;

if acc != expected {
return Err(InvalidTransaction::BadProof.into());
}

Ok(CheckedExtrinsic {
signed: Some((acc, extra)),
function,
})
}
Some((addr, AcalaMultiSignature::AcalaEip712(sig), extra)) => {
let function = self.0.function;
let eth_msg = ConvertTx::convert((function.clone(), extra.clone()))?;
Expand Down Expand Up @@ -280,23 +342,25 @@ fn verify_eip712_signature(eth_msg: EthereumTransactionMessage, sig: [u8; 65]) -
#[cfg(test)]
mod tests {
use super::*;
use hex_literal::hex;
use module_evm_utiltity::ethereum::AccessListItem;
use std::{ops::Add, str::FromStr};

#[test]
fn verify_eip712_should_works() {
let msg = EthereumTransactionMessage {
chain_id: 595,
genesis: H256::from_str("0xc3751fc073ec83e6aa13e2be395d21b05dce0692618a129324261c80ede07d4c").unwrap(),
nonce: 1,
tip: 2,
gas_limit: 222,
storage_limit: 333,
action: TransactionAction::Call(H160::from_str("0x1111111111222222222233333333334444444444").unwrap()),
value: 111,
input: vec![],
chain_id: 595,
genesis: H256::from_str("0xc3751fc073ec83e6aa13e2be395d21b05dce0692618a129324261c80ede07d4c").unwrap(),
valid_until: 444,
};
let sign = hex_literal::hex!("acb56f12b407bd0bc8f7abefe2e2585affe28009abcb6980aa33aecb815c56b324ab60a41eff339a88631c4b0e5183427be1fcfde3c05fb9b6c71a691e977c4a1b");
let sign = hex!("acb56f12b407bd0bc8f7abefe2e2585affe28009abcb6980aa33aecb815c56b324ab60a41eff339a88631c4b0e5183427be1fcfde3c05fb9b6c71a691e977c4a1b");
let sender = Some(H160::from_str("0x14791697260E4c9A71f18484C9f997B308e59325").unwrap());

assert_eq!(verify_eip712_signature(msg.clone(), sign), sender);
Expand Down Expand Up @@ -354,7 +418,7 @@ mod tests {
chain_id: Some(595),
};

let sign = hex_literal::hex!("f84345a6459785986a1b2df711fe02597d70c1393757a243f8f924ea541d2ecb51476de1aa437cd820d59e1d9836e37e643fec711fe419464e637cab592918751c");
let sign = hex!("f84345a6459785986a1b2df711fe02597d70c1393757a243f8f924ea541d2ecb51476de1aa437cd820d59e1d9836e37e643fec711fe419464e637cab592918751c");
let sender = Some(H160::from_str("0x14791697260E4c9A71f18484C9f997B308e59325").unwrap());

assert_eq!(recover_signer(&sign, msg.hash().as_fixed_bytes()), sender);
Expand Down Expand Up @@ -387,4 +451,63 @@ mod tests {
new_msg.chain_id = None;
assert_ne!(recover_signer(&sign, new_msg.hash().as_fixed_bytes()), sender);
}

#[test]
fn verify_eth_1559_should_works() {
let msg = EIP1559TransactionMessage {
chain_id: 595,
nonce: U256::from(1),
max_priority_fee_per_gas: U256::from(1),
max_fee_per_gas: U256::from("0x640000006a"),
gas_limit: U256::from(21000),
action: TransactionAction::Call(H160::from_str("0x1111111111222222222233333333334444444444").unwrap()),
value: U256::from(123123),
input: vec![],
access_list: vec![],
};

let sign = hex!("e88df53d4d66cb7a4f54ea44a44942b9b7f4fb4951525d416d3f7d24755a1f817734270872b103ac04c59d74f4dacdb8a6eff09a6638bd95dad1fa3eda921d891b");
let sender = Some(H160::from_str("0x14791697260E4c9A71f18484C9f997B308e59325").unwrap());

assert_eq!(recover_signer(&sign, msg.hash().as_fixed_bytes()), sender);

let mut new_msg = msg.clone();
new_msg.chain_id = new_msg.chain_id.add(1u64);
assert_ne!(recover_signer(&sign, new_msg.hash().as_fixed_bytes()), sender);

let mut new_msg = msg.clone();
new_msg.nonce = new_msg.nonce.add(U256::one());
assert_ne!(recover_signer(&sign, new_msg.hash().as_fixed_bytes()), sender);

let mut new_msg = msg.clone();
new_msg.max_priority_fee_per_gas = new_msg.max_priority_fee_per_gas.add(U256::one());
assert_ne!(recover_signer(&sign, new_msg.hash().as_fixed_bytes()), sender);

let mut new_msg = msg.clone();
new_msg.max_fee_per_gas = new_msg.max_fee_per_gas.add(U256::one());
assert_ne!(recover_signer(&sign, new_msg.hash().as_fixed_bytes()), sender);

let mut new_msg = msg.clone();
new_msg.gas_limit = new_msg.gas_limit.add(U256::one());
assert_ne!(recover_signer(&sign, new_msg.hash().as_fixed_bytes()), sender);

let mut new_msg = msg.clone();
new_msg.action = TransactionAction::Create;
assert_ne!(recover_signer(&sign, new_msg.hash().as_fixed_bytes()), sender);

let mut new_msg = msg.clone();
new_msg.value = new_msg.value.add(U256::one());
assert_ne!(recover_signer(&sign, new_msg.hash().as_fixed_bytes()), sender);

let mut new_msg = msg.clone();
new_msg.input = vec![0x00];
assert_ne!(recover_signer(&sign, new_msg.hash().as_fixed_bytes()), sender);

let mut new_msg = msg.clone();
new_msg.access_list = vec![AccessListItem {
address: hex!("bb9bc244d798123fde783fcc1c72d3bb8c189413").into(),
slots: vec![],
}];
assert_ne!(recover_signer(&sign, new_msg.hash().as_fixed_bytes()), sender);
}
}
4 changes: 2 additions & 2 deletions runtime/mandala/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1987,15 +1987,15 @@ impl Convert<(Call, SignedExtra), Result<EthereumTransactionMessage, InvalidTran
let tip = tip.0;

Ok(EthereumTransactionMessage {
chain_id: ChainId::get(),
genesis: System::block_hash(0),
nonce,
tip,
gas_limit,
storage_limit,
action,
value,
input,
chain_id: ChainId::get(),
genesis: System::block_hash(0),
valid_until,
})
}
Expand Down
Loading