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

Auto publish contracts #2099

Merged
merged 12 commits into from
May 16, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 2 additions & 0 deletions modules/evm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,9 @@ primitives = { package = "acala-primitives", path = "../../primitives", default-
module-idle-scheduler = { path = "../idle-scheduler", default-features = false, optional = true }

[dev-dependencies]
hex = "0.4"
env_logger = "0.9.0"
serde_json = "1.0.68"

[features]
default = ["std"]
Expand Down
9 changes: 3 additions & 6 deletions modules/evm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -418,10 +418,7 @@ pub mod module {
);

let out = runtime.machine().return_value();
<Pallet<T>>::create_contract(source, *address, out);

#[cfg(not(feature = "with-ethereum-compatibility"))]
<Pallet<T>>::mark_published(*address, None).expect("Genesis contract failed to publish");
<Pallet<T>>::create_contract(source, *address, true, out);

for (index, value) in &account.storage {
AccountStorages::<T>::insert(address, index, value);
Expand Down Expand Up @@ -1287,7 +1284,7 @@ impl<T: Config> Pallet<T> {
/// - Update codes info.
/// - Update maintainer of the contract.
/// - Save `code` if not saved yet.
pub fn create_contract(source: H160, address: H160, code: Vec<u8>) {
pub fn create_contract(source: H160, address: H160, publish: bool, code: Vec<u8>) {
let bounded_code: BoundedVec<u8, MaxCodeSize> = code
.try_into()
.expect("checked by create_contract_limit in ACALA_CONFIG; qed");
Expand All @@ -1312,7 +1309,7 @@ impl<T: Config> Pallet<T> {
#[cfg(feature = "with-ethereum-compatibility")]
published: true,
#[cfg(not(feature = "with-ethereum-compatibility"))]
published: false,
published: publish,
};

CodeInfos::<T>::mutate_exists(&code_hash, |maybe_code_info| {
Expand Down
17 changes: 10 additions & 7 deletions modules/evm/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -219,12 +219,13 @@ construct_runtime!(
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Pallet, Call, Storage, Config, Event<T>},
EVM: evm_mod::{Pallet, Config<T>, Call, Storage, Event<T>},
Tokens: orml_tokens::{Pallet, Storage, Event<T>},
Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
Currencies: orml_currencies::{Pallet, Call},
IdleScheduler: module_idle_scheduler::{Pallet, Call, Storage, Event<T>},
System: frame_system,
Timestamp: pallet_timestamp,
EVM: evm_mod,
Tokens: orml_tokens,
Balances: pallet_balances,
Currencies: orml_currencies,
IdleScheduler: module_idle_scheduler,
}
);

Expand Down Expand Up @@ -299,7 +300,9 @@ pub fn new_test_ext() -> sp_io::TestExternalities {
.unwrap();

let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
ext.execute_with(|| {
System::set_block_number(1);
});
ext
}

Expand Down
60 changes: 30 additions & 30 deletions modules/evm/src/runner/stack.rs
Original file line number Diff line number Diff line change
Expand Up @@ -723,43 +723,43 @@ impl<'vicinity, 'config, T: Config> StackStateT<'config> for SubstrateStackState
address
);

let caller: H160;
let mut substate = &self.substate;

loop {
// get maintainer from parent caller
// `enter_substate` will do `spit_child`
if substate.parent.is_none() {
log::error!(
target: "evm",
"get parent's maintainer failed. address: {:?}",
address
);
debug_assert!(false);
return;
}

substate = substate.parent.as_ref().expect("has checked; qed");
// get maintainer from parent caller `enter_substate` will do `spit_child`
if self.substate.parent.is_none() {
zjb0807 marked this conversation as resolved.
Show resolved Hide resolved
log::error!(
target: "evm",
"get parent's maintainer failed. address: {:?}",
address
);
debug_assert!(false);
return;
}

if let Some(c) = substate.metadata().caller() {
// the caller maybe is contract and not published.
// get the parent's maintainer.
if !Pallet::<T>::is_account_empty(c) {
caller = *c;
break;
}
}
let parent = self.substate.parent.as_ref().expect("has checked; qed");
if parent.metadata().caller().is_none() {
log::error!(
target: "evm",
"get parent's caller failed. address: {:?}",
address
);
debug_assert!(false);
return;
}
let caller = parent.metadata().caller().expect("has checked; qed");

let is_published = self.substate.metadata.call_address().map_or(false, |addr| {
Pallet::<T>::accounts(addr).map_or(false, |account| account.contract_info.map_or(false, |v| v.published))
});

log::debug!(
target: "evm",
"set_code: address: {:?}, maintainer: {:?}",
address,
caller
target: "evm",
"set_code: address: {:?}, maintainer: {:?}, publish: {:?}",
address,
caller,
is_published
);

let code_size = code.len() as u32;
Pallet::<T>::create_contract(caller, address, code);
Pallet::<T>::create_contract(caller, address, is_published, code);

let used_storage = code_size.saturating_add(T::NewContractExtraBytes::get());
Pallet::<T>::update_contract_storage_size(&address, used_storage as i32);
Expand Down
14 changes: 14 additions & 0 deletions modules/evm/src/runner/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,8 @@ pub struct StackSubstateMetadata<'config> {
caller: Option<H160>,
// save the contract to charge storage
target: Option<H160>,
// save the call contract address, publish status will sync from it.
call_address: Option<H160>,
zjb0807 marked this conversation as resolved.
Show resolved Hide resolved
// this is needed only for evm-tests to keep track of dirty accounts
#[cfg(feature = "evm-tests")]
pub dirty_accounts: std::cell::RefCell<BTreeSet<H160>>,
Expand All @@ -167,6 +169,7 @@ impl<'config> StackSubstateMetadata<'config> {
accessed,
caller: None,
target: None,
call_address: None,
#[cfg(feature = "evm-tests")]
dirty_accounts: std::cell::RefCell::new(BTreeSet::new()),
}
Expand Down Expand Up @@ -218,6 +221,7 @@ impl<'config> StackSubstateMetadata<'config> {
accessed: self.accessed.as_ref().map(|_| Accessed::default()),
caller: None,
target: None,
call_address: self.call_address,
#[cfg(feature = "evm-tests")]
dirty_accounts: std::cell::RefCell::new(BTreeSet::new()),
}
Expand Down Expand Up @@ -296,6 +300,14 @@ impl<'config> StackSubstateMetadata<'config> {
pub fn target_mut(&mut self) -> &mut Option<H160> {
&mut self.target
}

pub fn call_address(&mut self) -> &Option<H160> {
&self.call_address
}

pub fn call_address_mut(&mut self) -> &mut Option<H160> {
&mut self.call_address
}
}

pub trait StackState<'config>: Backend {
Expand Down Expand Up @@ -632,6 +644,8 @@ impl<'config, 'precompiles, S: StackState<'config>, P: PrecompileSet> StackExecu
Ok(()) => (),
Err(e) => return emit_exit!(e.into(), Vec::new()),
}
// set call_address. publish status will sync from it.
*self.state.metadata_mut().call_address_mut() = Some(address);

// Initialize initial addresses for EIP-2929
if self.config.increase_state_access_gas {
Expand Down
165 changes: 165 additions & 0 deletions modules/evm/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2080,3 +2080,168 @@ fn remove_account_works() {
assert_eq!(Accounts::<Runtime>::contains_key(&address), false);
});
}

#[test]
fn auto_publish_works() {
let json: serde_json::Value =
serde_json::from_str(include_str!("../../../ts-tests/build/CreateContractFactory.json")).unwrap();
let code = hex::decode(json.get("bytecode").unwrap().as_str().unwrap()).unwrap();

new_test_ext().execute_with(|| {
let alice_account_id = <Runtime as Config>::AddressMapping::get_account_id(&alice());
assert_ok!(EVM::create(
Origin::signed(alice_account_id.clone()),
code,
0,
2_100_000,
10000,
vec![]
));

let factory = H160::from_str("0x5f8bd49cd9f0cb2bd5bb9d4320dfe9b61023249d").unwrap();
System::assert_last_event(Event::EVM(crate::Event::Created {
from: alice(),
contract: factory,
logs: vec![],
used_gas: 354694,
used_storage: 1498,
}));

// call method `createContract()`
assert_ok!(EVM::call(
Origin::signed(alice_account_id.clone()),
factory,
from_hex("0x412a5a6d").unwrap(),
0,
1000000,
1000,
vec![],
));
System::assert_last_event(Event::EVM(crate::Event::Executed {
from: alice(),
contract: factory,
logs: vec![
crate::Log {
address: H160::from_str("0x7b8f8ca099f6e33cf1817cf67d0556429cfc54e4").unwrap(),
topics: vec![
H256::from_str("0xb0199510a4d57fac89f9b613861450ae948394f2abe3bf9918eb3c6890243f00").unwrap(),
H256::from_str("0x00000000000000000000000030f612c54706d40f65acaf10b8f6989103c2af58").unwrap(),
],
data: vec![],
},
crate::Log {
address: factory,
topics: vec![
H256::from_str("0x6837ff1e738d95fc8bb5f12ce1513f42866f6c59c226c77342c4f36a1958ea10").unwrap(),
H256::from_str("0x0000000000000000000000007b8f8ca099f6e33cf1817cf67d0556429cfc54e4").unwrap(),
],
data: vec![],
},
],
used_gas: 248186,
used_storage: 834,
}));

assert_eq!(
EVM::accounts(factory).unwrap().contract_info,
Some(ContractInfo {
code_hash: H256::from_str("0x0aaddd7924d6a6789dba233a48270c4a52ca44074d2a0453362b249712c6a21c")
.unwrap(),
maintainer: alice(),
published: false
})
);
assert_eq!(
EVM::accounts(H160::from_str("0x7b8f8ca099f6e33cf1817cf67d0556429cfc54e4").unwrap())
.unwrap()
.contract_info,
Some(ContractInfo {
code_hash: H256::from_str("0x3c098bc145b56c64e688ccc6055980b993fefd794cb97a69654d3e125cdda9dc")
.unwrap(),
maintainer: alice(),
published: false
})
);
assert_eq!(
EVM::accounts(H160::from_str("0x30f612c54706d40f65acaf10b8f6989103c2af58").unwrap())
.unwrap()
.contract_info,
Some(ContractInfo {
code_hash: H256::from_str("0x21da9211a5ef5e10cf7efc58b70c09e2a586844a4798b5e506927cc05808ca4c")
.unwrap(),
maintainer: H160::from_str("0x7b8f8ca099f6e33cf1817cf67d0556429cfc54e4").unwrap(),
published: false
})
);

// publish the factory
assert_ok!(EVM::publish_free(Origin::signed(CouncilAccount::get()), factory));

// call method `createContract()`
assert_ok!(EVM::call(
Origin::signed(alice_account_id.clone()),
factory,
from_hex("0x412a5a6d").unwrap(),
0,
1000000,
1000,
vec![],
));
System::assert_last_event(Event::EVM(crate::Event::Executed {
from: alice(),
contract: factory,
logs: vec![
crate::Log {
address: H160::from_str("0x39b26a36a8a175ce7d498b5ef187d1ab2f381bbd").unwrap(),
topics: vec![
H256::from_str("0xb0199510a4d57fac89f9b613861450ae948394f2abe3bf9918eb3c6890243f00").unwrap(),
H256::from_str("0x000000000000000000000000769a55efaf4dbdd6f44efce668455522b61abb82").unwrap(),
],
data: vec![],
},
crate::Log {
address: factory,
topics: vec![
H256::from_str("0x6837ff1e738d95fc8bb5f12ce1513f42866f6c59c226c77342c4f36a1958ea10").unwrap(),
H256::from_str("0x00000000000000000000000039b26a36a8a175ce7d498b5ef187d1ab2f381bbd").unwrap(),
],
data: vec![],
},
],
used_gas: 231086,
used_storage: 770,
}));

assert_eq!(
EVM::accounts(factory).unwrap().contract_info,
Some(ContractInfo {
code_hash: H256::from_str("0x0aaddd7924d6a6789dba233a48270c4a52ca44074d2a0453362b249712c6a21c")
.unwrap(),
maintainer: alice(),
published: true
})
);
assert_eq!(
EVM::accounts(H160::from_str("0x39b26a36a8a175ce7d498b5ef187d1ab2f381bbd").unwrap())
.unwrap()
.contract_info,
Some(ContractInfo {
code_hash: H256::from_str("0x3c098bc145b56c64e688ccc6055980b993fefd794cb97a69654d3e125cdda9dc")
.unwrap(),
maintainer: alice(),
published: true
})
);
assert_eq!(
EVM::accounts(H160::from_str("0x769a55efaf4dbdd6f44efce668455522b61abb82").unwrap())
.unwrap()
.contract_info,
Some(ContractInfo {
code_hash: H256::from_str("0x21da9211a5ef5e10cf7efc58b70c09e2a586844a4798b5e506927cc05808ca4c")
.unwrap(),
maintainer: H160::from_str("0x39b26a36a8a175ce7d498b5ef187d1ab2f381bbd").unwrap(),
xlc marked this conversation as resolved.
Show resolved Hide resolved
published: true
})
);
});
}
Loading