diff --git a/Cargo.lock b/Cargo.lock index 67a66244f3b76..39eb0412a6bb5 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -12832,8 +12832,6 @@ dependencies = [ "sp-keystore 0.34.0", "sp-runtime 31.0.1", "sp-tracing 16.0.0", - "staging-xcm", - "staging-xcm-builder", "substrate-bn", "subxt-signer 0.41.0", ] @@ -12889,35 +12887,6 @@ dependencies = [ "toml 0.8.19", ] -[[package]] -name = "pallet-revive-mock-network" -version = "0.1.0" -dependencies = [ - "frame-support", - "frame-system", - "pallet-assets", - "pallet-balances", - "pallet-message-queue", - "pallet-revive", - "pallet-revive-fixtures", - "pallet-revive-uapi", - "pallet-timestamp", - "pallet-xcm", - "parity-scale-codec", - "polkadot-parachain-primitives", - "polkadot-primitives", - "polkadot-runtime-parachains", - "scale-info", - "sp-core 28.0.0", - "sp-io 30.0.0", - "sp-runtime 31.0.1", - "sp-tracing 16.0.0", - "staging-xcm", - "staging-xcm-builder", - "staging-xcm-executor", - "xcm-simulator", -] - [[package]] name = "pallet-revive-proc-macro" version = "0.1.0" @@ -16034,7 +16003,6 @@ dependencies = [ "pallet-remark", "pallet-revive", "pallet-revive-eth-rpc", - "pallet-revive-mock-network", "pallet-revive-proc-macro", "pallet-revive-uapi", "pallet-root-offences", diff --git a/Cargo.toml b/Cargo.toml index 101a4cfa18903..959bf00209f2f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -415,7 +415,6 @@ members = [ "substrate/frame/remark", "substrate/frame/revive", "substrate/frame/revive/fixtures", - "substrate/frame/revive/mock-network", "substrate/frame/revive/proc-macro", "substrate/frame/revive/rpc", "substrate/frame/revive/uapi", @@ -1019,7 +1018,6 @@ pallet-remark = { default-features = false, path = "substrate/frame/remark" } pallet-revive = { path = "substrate/frame/revive", default-features = false } pallet-revive-eth-rpc = { path = "substrate/frame/revive/rpc", default-features = false } pallet-revive-fixtures = { path = "substrate/frame/revive/fixtures", default-features = false } -pallet-revive-mock-network = { default-features = false, path = "substrate/frame/revive/mock-network" } pallet-revive-proc-macro = { path = "substrate/frame/revive/proc-macro", default-features = false } pallet-revive-uapi = { path = "substrate/frame/revive/uapi", default-features = false } pallet-root-offences = { default-features = false, path = "substrate/frame/root-offences" } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs index 0093058ad2c37..3696319485171 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs @@ -51,7 +51,7 @@ use frame_support::{ fungibles, tokens::{imbalance::ResolveAssetTo, nonfungibles_v2::Inspect}, AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, - ConstantStoragePrice, Equals, InstanceFilter, Nothing, TransformOrigin, + ConstantStoragePrice, Equals, InstanceFilter, TransformOrigin, }, weights::{ConstantMultiplier, Weight}, BoundedVec, PalletId, @@ -1073,7 +1073,6 @@ impl pallet_revive::Config for Runtime { type Currency = Balances; type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; - type CallFilter = Nothing; type DepositPerItem = DepositPerItem; type DepositPerByte = DepositPerByte; type WeightPrice = pallet_transaction_payment::Pallet; @@ -1090,7 +1089,6 @@ impl pallet_revive::Config for Runtime { type InstantiateOrigin = EnsureSigned; type RuntimeHoldReason = RuntimeHoldReason; type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; - type Xcm = pallet_xcm::Pallet; type ChainId = ConstU64<420_420_421>; type NativeToEthRatio = ConstU32<1_000_000>; // 10^(18 - 12) Eth is 10^18, Native is 10^12. type EthGasEncoder = (); diff --git a/cumulus/parachains/runtimes/testing/penpal/src/lib.rs b/cumulus/parachains/runtimes/testing/penpal/src/lib.rs index 48095e95d4116..6557315317377 100644 --- a/cumulus/parachains/runtimes/testing/penpal/src/lib.rs +++ b/cumulus/parachains/runtimes/testing/penpal/src/lib.rs @@ -64,7 +64,7 @@ use frame_support::{ traits::{ tokens::{fungible, fungibles, imbalance::ResolveAssetTo}, AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU32, ConstU64, ConstU8, Everything, - Nothing, TransformOrigin, + TransformOrigin, }, weights::{ constants::WEIGHT_REF_TIME_PER_SECOND, ConstantMultiplier, FeePolynomial, @@ -840,7 +840,6 @@ impl pallet_revive::Config for Runtime { type Currency = Balances; type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; - type CallFilter = Nothing; type DepositPerItem = DepositPerItem; type DepositPerByte = DepositPerByte; type WeightPrice = pallet_transaction_payment::Pallet; @@ -854,7 +853,6 @@ impl pallet_revive::Config for Runtime { type InstantiateOrigin = EnsureSigned; type RuntimeHoldReason = RuntimeHoldReason; type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; - type Xcm = PolkadotXcm; type ChainId = ConstU64<420_420_999>; type NativeToEthRatio = ConstU32<1_000_000>; // 10^(18 - 12) Eth is 10^18, Native is 10^12. type EthGasEncoder = (); diff --git a/prdoc/pr_8584.prdoc b/prdoc/pr_8584.prdoc new file mode 100644 index 0000000000000..541b0a02aaff2 --- /dev/null +++ b/prdoc/pr_8584.prdoc @@ -0,0 +1,18 @@ +title: Remove all XCM dependencies from `pallet-revive` +doc: +- audience: Runtime Dev + description: This PR removes all XCM dependencies from `pallet-revive`, including + the `mock-network` crate which was primarily used to test the unstable `xcm_execute` + and `xcm_send` APIs. These APIs (along their respective tests) will be moved to + the XCM precompile in `pallet-xcm` to avoid cyclic dependencies. +crates: +- name: asset-hub-westend-runtime + bump: major +- name: penpal-runtime + bump: major +- name: pallet-revive + bump: major +- name: pallet-revive-uapi + bump: major +- name: polkadot-sdk + bump: major diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 600f28f71062d..b8c099600e180 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -1469,7 +1469,6 @@ impl pallet_revive::Config for Runtime { type Currency = Balances; type RuntimeEvent = RuntimeEvent; type RuntimeCall = RuntimeCall; - type CallFilter = Nothing; type DepositPerItem = DepositPerItem; type DepositPerByte = DepositPerByte; type WeightPrice = pallet_transaction_payment::Pallet; @@ -1484,7 +1483,6 @@ impl pallet_revive::Config for Runtime { type InstantiateOrigin = EnsureSigned; type RuntimeHoldReason = RuntimeHoldReason; type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; - type Xcm = (); type ChainId = ConstU64<420_420_420>; type NativeToEthRatio = ConstU32<1_000_000>; // 10^(18 - 12) Eth is 10^18, Native is 10^12. type EthGasEncoder = (); diff --git a/substrate/frame/revive/Cargo.toml b/substrate/frame/revive/Cargo.toml index a96035a12e048..0968b84e49210 100644 --- a/substrate/frame/revive/Cargo.toml +++ b/substrate/frame/revive/Cargo.toml @@ -19,7 +19,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] alloy-core = { workspace = true, features = ["sol-types"] } codec = { features = ["derive", "max-encoded-len"], workspace = true } -derive_more = { workspace = true } +derive_more = { workspace = true, features = ["from", "try_into"] } environmental = { workspace = true } ethereum-standards = { workspace = true } ethereum-types = { workspace = true, features = ["codec", "rlp", "serialize"] } @@ -58,8 +58,6 @@ sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } subxt-signer = { workspace = true, optional = true, features = ["unstable-eth"] } -xcm = { workspace = true } -xcm-builder = { workspace = true } [dev-dependencies] array-bytes = { workspace = true, default-features = true } @@ -77,7 +75,6 @@ pallet-timestamp = { workspace = true, default-features = true } pallet-utility = { workspace = true, default-features = true } sp-keystore = { workspace = true, default-features = true } sp-tracing = { workspace = true, default-features = true } -xcm-builder = { workspace = true, default-features = true } [features] default = ["std"] @@ -118,8 +115,6 @@ std = [ "sp-keystore/std", "sp-runtime/std", "subxt-signer", - "xcm-builder/std", - "xcm/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", @@ -138,8 +133,6 @@ runtime-benchmarks = [ "sp-consensus-babe", "sp-consensus-slots", "sp-runtime/runtime-benchmarks", - "xcm-builder/runtime-benchmarks", - "xcm/runtime-benchmarks", ] try-runtime = [ "frame-support/try-runtime", diff --git a/substrate/frame/revive/fixtures/contracts/call_runtime.rs b/substrate/frame/revive/fixtures/contracts/call_runtime.rs deleted file mode 100644 index e6e4c855269d5..0000000000000 --- a/substrate/frame/revive/fixtures/contracts/call_runtime.rs +++ /dev/null @@ -1,42 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -//! This passes its input to `call_runtime` and returns the return value to its caller. -#![no_std] -#![no_main] -include!("../panic_handler.rs"); - -use uapi::{input, HostFn, HostFnImpl as api}; - -#[no_mangle] -#[polkavm_derive::polkavm_export] -pub extern "C" fn deploy() {} - -#[no_mangle] -#[polkavm_derive::polkavm_export] -pub extern "C" fn call() { - // Fixture calls should fit into 100 bytes. - input!(100, call: [u8], ); - - // Use the call passed as input to call the runtime. - let err_code = match api::call_runtime(call) { - Ok(_) => 0u32, - Err(code) => code as u32, - }; - - api::return_value(uapi::ReturnFlags::empty(), &err_code.to_le_bytes()); -} diff --git a/substrate/frame/revive/fixtures/contracts/call_runtime_and_call.rs b/substrate/frame/revive/fixtures/contracts/call_runtime_and_call.rs deleted file mode 100644 index 7ac21bff94dd1..0000000000000 --- a/substrate/frame/revive/fixtures/contracts/call_runtime_and_call.rs +++ /dev/null @@ -1,53 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#![no_std] -#![no_main] -include!("../panic_handler.rs"); - -use uapi::{input, HostFn, HostFnImpl as api}; - -#[no_mangle] -#[polkavm_derive::polkavm_export] -pub extern "C" fn deploy() {} - -#[no_mangle] -#[polkavm_derive::polkavm_export] -pub extern "C" fn call() { - input!( - 512, - callee_input: [u8; 4], - callee_addr: &[u8; 20], - call: [u8], - ); - - // Use the call passed as input to call the runtime. - api::call_runtime(call).unwrap(); - - // Call the callee - api::call( - uapi::CallFlags::empty(), - callee_addr, - u64::MAX, // How much ref_time to devote for the execution. u64::MAX = use all. - u64::MAX, // How much proof_size to devote for the execution. u64::MAX = use all. - &[u8::MAX; 32], // No deposit limit. - &[0u8; 32], // Value transferred to the contract. - callee_input, - None, - ) - .unwrap(); -} diff --git a/substrate/frame/revive/fixtures/contracts/xcm_execute.rs b/substrate/frame/revive/fixtures/contracts/xcm_execute.rs deleted file mode 100644 index 0817682735a33..0000000000000 --- a/substrate/frame/revive/fixtures/contracts/xcm_execute.rs +++ /dev/null @@ -1,40 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#![no_std] -#![no_main] -include!("../panic_handler.rs"); - -use uapi::{input, HostFn, HostFnImpl as api}; - -#[no_mangle] -#[polkavm_derive::polkavm_export] -pub extern "C" fn deploy() {} - -#[no_mangle] -#[polkavm_derive::polkavm_export] -pub extern "C" fn call() { - input!(512, msg: [u8],); - - #[allow(deprecated)] - let err_code = match api::xcm_execute(msg) { - Ok(_) => 0u32, - Err(code) => code as u32, - }; - - api::return_value(uapi::ReturnFlags::empty(), &err_code.to_le_bytes()); -} diff --git a/substrate/frame/revive/fixtures/contracts/xcm_send.rs b/substrate/frame/revive/fixtures/contracts/xcm_send.rs deleted file mode 100644 index f94cb765edfc3..0000000000000 --- a/substrate/frame/revive/fixtures/contracts/xcm_send.rs +++ /dev/null @@ -1,42 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -#![no_std] -#![no_main] -include!("../panic_handler.rs"); - -use uapi::{input, HostFn, HostFnImpl as api}; - -#[no_mangle] -#[polkavm_derive::polkavm_export] -pub extern "C" fn deploy() {} - -#[no_mangle] -#[polkavm_derive::polkavm_export] -pub extern "C" fn call() { - input!( - 512, - dest: [u8; 3], - msg: [u8], - ); - - let mut message_id = [0u8; 32]; - - #[allow(deprecated)] - api::xcm_send(dest, msg, &mut message_id).unwrap(); - api::return_value(uapi::ReturnFlags::empty(), &message_id); -} diff --git a/substrate/frame/revive/mock-network/Cargo.toml b/substrate/frame/revive/mock-network/Cargo.toml deleted file mode 100644 index becce626e7298..0000000000000 --- a/substrate/frame/revive/mock-network/Cargo.toml +++ /dev/null @@ -1,88 +0,0 @@ -[package] -name = "pallet-revive-mock-network" -version = "0.1.0" -authors.workspace = true -edition.workspace = true -license.workspace = true -homepage.workspace = true -repository.workspace = true -description = "A mock network for testing pallet-revive." - -[lints] -workspace = true - -[dependencies] -codec = { features = ["derive", "max-encoded-len"], workspace = true } - -frame-support = { workspace = true } -frame-system = { workspace = true } -pallet-assets = { workspace = true, default-features = true } -pallet-balances = { workspace = true, default-features = true } -pallet-message-queue = { workspace = true, default-features = true } -pallet-revive = { workspace = true, default-features = true } -pallet-revive-uapi = { workspace = true } -pallet-timestamp = { workspace = true, default-features = true } -pallet-xcm = { workspace = true } -polkadot-parachain-primitives = { workspace = true, default-features = true } -polkadot-primitives = { workspace = true, default-features = true } -polkadot-runtime-parachains = { workspace = true, default-features = true } -scale-info = { features = ["derive"], workspace = true } -sp-core = { workspace = true } -sp-io = { workspace = true } -sp-runtime = { workspace = true } -sp-tracing = { workspace = true, default-features = true } -xcm = { workspace = true } -xcm-builder = { workspace = true, default-features = true } -xcm-executor = { workspace = true } -xcm-simulator = { workspace = true, default-features = true } - -[dev-dependencies] -pallet-revive-fixtures = { workspace = true } - -[features] -default = ["std"] -std = [ - "codec/std", - "frame-support/std", - "frame-system/std", - "pallet-balances/std", - "pallet-revive-fixtures/std", - "pallet-revive/std", - "pallet-timestamp/std", - "pallet-xcm/std", - "scale-info/std", - "sp-core/std", - "sp-io/std", - "sp-runtime/std", - "xcm-executor/std", - "xcm/std", -] -runtime-benchmarks = [ - "frame-support/runtime-benchmarks", - "frame-system/runtime-benchmarks", - "pallet-assets/runtime-benchmarks", - "pallet-balances/runtime-benchmarks", - "pallet-message-queue/runtime-benchmarks", - "pallet-revive/runtime-benchmarks", - "pallet-timestamp/runtime-benchmarks", - "pallet-xcm/runtime-benchmarks", - "polkadot-parachain-primitives/runtime-benchmarks", - "polkadot-primitives/runtime-benchmarks", - "polkadot-runtime-parachains/runtime-benchmarks", - "sp-runtime/runtime-benchmarks", - "xcm-builder/runtime-benchmarks", - "xcm-executor/runtime-benchmarks", - "xcm/runtime-benchmarks", -] -try-runtime = [ - "frame-support/try-runtime", - "frame-system/try-runtime", - "pallet-assets/try-runtime", - "pallet-balances/try-runtime", - "pallet-message-queue/try-runtime", - "pallet-revive/try-runtime", - "pallet-timestamp/try-runtime", - "pallet-xcm/try-runtime", - "polkadot-runtime-parachains/try-runtime", - "sp-runtime/try-runtime", -] diff --git a/substrate/frame/revive/mock-network/src/lib.rs b/substrate/frame/revive/mock-network/src/lib.rs deleted file mode 100644 index 3e9d1fe33914e..0000000000000 --- a/substrate/frame/revive/mock-network/src/lib.rs +++ /dev/null @@ -1,154 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Substrate. - -// Substrate is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Substrate is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Substrate. If not, see . - -pub mod mocks; -pub mod parachain; -pub mod primitives; -pub mod relay_chain; - -#[cfg(test)] -mod tests; - -use crate::primitives::{AccountId, UNITS}; -pub use pallet_revive::test_utils::{ALICE, BOB}; -use sp_runtime::BuildStorage; -use xcm::latest::prelude::*; -use xcm_executor::traits::ConvertLocation; -pub use xcm_simulator::TestExt; -use xcm_simulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain}; - -// Accounts -pub const ADMIN: sp_runtime::AccountId32 = sp_runtime::AccountId32::new([0u8; 32]); - -// Balances -pub const INITIAL_BALANCE: u128 = 1_000_000_000 * UNITS; - -decl_test_parachain! { - pub struct ParaA { - Runtime = parachain::Runtime, - XcmpMessageHandler = parachain::MsgQueue, - DmpMessageHandler = parachain::MsgQueue, - new_ext = para_ext(1), - } -} - -decl_test_relay_chain! { - pub struct Relay { - Runtime = relay_chain::Runtime, - RuntimeCall = relay_chain::RuntimeCall, - RuntimeEvent = relay_chain::RuntimeEvent, - XcmConfig = relay_chain::XcmConfig, - MessageQueue = relay_chain::MessageQueue, - System = relay_chain::System, - new_ext = relay_ext(), - } -} - -decl_test_network! { - pub struct MockNet { - relay_chain = Relay, - parachains = vec![ - (1, ParaA), - ], - } -} - -pub fn relay_sovereign_account_id() -> AccountId { - let location: Location = (Parent,).into(); - parachain::SovereignAccountOf::convert_location(&location).unwrap() -} - -pub fn parachain_sovereign_account_id(para: u32) -> AccountId { - let location: Location = (Parachain(para),).into(); - relay_chain::SovereignAccountOf::convert_location(&location).unwrap() -} - -pub fn parachain_account_sovereign_account_id( - para: u32, - who: sp_runtime::AccountId32, -) -> AccountId { - let location: Location = ( - Parachain(para), - AccountId32 { network: Some(relay_chain::RelayNetwork::get()), id: who.into() }, - ) - .into(); - relay_chain::SovereignAccountOf::convert_location(&location).unwrap() -} - -pub fn para_ext(para_id: u32) -> sp_io::TestExternalities { - use parachain::{MsgQueue, Runtime, System}; - - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); - - pallet_balances::GenesisConfig:: { - balances: vec![ - (ALICE, INITIAL_BALANCE), - (relay_sovereign_account_id(), INITIAL_BALANCE), - (BOB, INITIAL_BALANCE), - ], - ..Default::default() - } - .assimilate_storage(&mut t) - .unwrap(); - - pallet_assets::GenesisConfig:: { - assets: vec![ - (0u128, ADMIN, false, 1u128), // Create derivative asset for relay's native token - ], - metadata: Default::default(), - accounts: vec![ - (0u128, ALICE, INITIAL_BALANCE), - (0u128, relay_sovereign_account_id(), INITIAL_BALANCE), - ], - next_asset_id: None, - } - .assimilate_storage(&mut t) - .unwrap(); - - let mut ext = sp_io::TestExternalities::new(t); - ext.execute_with(|| { - sp_tracing::try_init_simple(); - System::set_block_number(1); - MsgQueue::set_para_id(para_id.into()); - }); - ext -} - -pub fn relay_ext() -> sp_io::TestExternalities { - use relay_chain::{Runtime, System}; - - let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); - - pallet_balances::GenesisConfig:: { - balances: vec![ - (ALICE, INITIAL_BALANCE), - (parachain_sovereign_account_id(1), INITIAL_BALANCE), - (parachain_account_sovereign_account_id(1, ALICE), INITIAL_BALANCE), - ], - ..Default::default() - } - .assimilate_storage(&mut t) - .unwrap(); - - let mut ext = sp_io::TestExternalities::new(t); - ext.execute_with(|| { - System::set_block_number(1); - }); - ext -} - -pub type ParachainPalletXcm = pallet_xcm::Pallet; -pub type ParachainBalances = pallet_balances::Pallet; diff --git a/substrate/frame/revive/mock-network/src/mocks.rs b/substrate/frame/revive/mock-network/src/mocks.rs deleted file mode 100644 index b02e3bacc495b..0000000000000 --- a/substrate/frame/revive/mock-network/src/mocks.rs +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Substrate. - -// Substrate is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Substrate is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Substrate. If not, see . - -pub mod msg_queue; -pub mod relay_message_queue; diff --git a/substrate/frame/revive/mock-network/src/mocks/msg_queue.rs b/substrate/frame/revive/mock-network/src/mocks/msg_queue.rs deleted file mode 100644 index f2f7f6305f455..0000000000000 --- a/substrate/frame/revive/mock-network/src/mocks/msg_queue.rs +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Substrate. - -// Substrate is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Substrate is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Substrate. If not, see . - -//! Parachain runtime mock. - -use codec::{Decode, Encode}; - -use frame_support::weights::Weight; -use polkadot_parachain_primitives::primitives::{ - DmpMessageHandler, Id as ParaId, XcmpMessageFormat, XcmpMessageHandler, -}; -use polkadot_primitives::BlockNumber as RelayBlockNumber; -use sp_runtime::traits::{Get, Hash}; - -use xcm::{latest::prelude::*, VersionedXcm}; - -#[frame_support::pallet] -pub mod pallet { - use super::*; - use frame_support::pallet_prelude::*; - - #[pallet::config] - pub trait Config: frame_system::Config { - #[allow(deprecated)] - type RuntimeEvent: From> + IsType<::RuntimeEvent>; - type XcmExecutor: ExecuteXcm; - } - - #[pallet::call] - impl Pallet {} - - #[pallet::pallet] - #[pallet::without_storage_info] - pub struct Pallet(_); - - #[pallet::storage] - pub(super) type ParachainId = StorageValue<_, ParaId, ValueQuery>; - - #[pallet::storage] - /// A queue of received DMP messages - pub(super) type ReceivedDmp = StorageValue<_, Vec>, ValueQuery>; - - impl Get for Pallet { - fn get() -> ParaId { - ParachainId::::get() - } - } - - pub type MessageId = [u8; 32]; - - #[pallet::event] - #[pallet::generate_deposit(pub(super) fn deposit_event)] - pub enum Event { - /// Some XCM was executed OK. - Success(Option), - /// Some XCM failed. - Fail(Option, XcmError), - /// Bad XCM version used. - BadVersion(Option), - /// Bad XCM format used. - BadFormat(Option), - - // DMP - /// Downward message is invalid XCM. - InvalidFormat(MessageId), - /// Downward message is unsupported version of XCM. - UnsupportedVersion(MessageId), - /// Downward message executed with the given outcome. - ExecutedDownward(MessageId, Outcome), - } - - impl Pallet { - pub fn set_para_id(para_id: ParaId) { - ParachainId::::put(para_id); - } - - pub fn parachain_id() -> ParaId { - ParachainId::::get() - } - - pub fn received_dmp() -> Vec> { - ReceivedDmp::::get() - } - - fn handle_xcmp_message( - sender: ParaId, - _sent_at: RelayBlockNumber, - xcm: VersionedXcm, - max_weight: Weight, - ) -> Result { - let hash = Encode::using_encoded(&xcm, T::Hashing::hash); - let mut message_hash = Encode::using_encoded(&xcm, sp_io::hashing::blake2_256); - let (result, event) = match Xcm::::try_from(xcm) { - Ok(xcm) => { - let location = (Parent, Parachain(sender.into())); - match T::XcmExecutor::prepare_and_execute( - location, - xcm, - &mut message_hash, - max_weight, - Weight::zero(), - ) { - Outcome::Error(InstructionError { error, .. }) => - (Err(error), Event::Fail(Some(hash), error)), - Outcome::Complete { used } => (Ok(used), Event::Success(Some(hash))), - // As far as the caller is concerned, this was dispatched without error, so - // we just report the weight used. - Outcome::Incomplete { - used, error: InstructionError { error, .. }, .. - } => (Ok(used), Event::Fail(Some(hash), error)), - } - }, - Err(()) => (Err(XcmError::UnhandledXcmVersion), Event::BadVersion(Some(hash))), - }; - Self::deposit_event(event); - result - } - } - - impl XcmpMessageHandler for Pallet { - fn handle_xcmp_messages<'a, I: Iterator>( - iter: I, - max_weight: Weight, - ) -> Weight { - for (sender, sent_at, data) in iter { - let mut data_ref = data; - let _ = XcmpMessageFormat::decode(&mut data_ref) - .expect("Simulator encodes with versioned xcm format; qed"); - - let mut remaining_fragments = data_ref; - while !remaining_fragments.is_empty() { - if let Ok(xcm) = - VersionedXcm::::decode(&mut remaining_fragments) - { - let _ = Self::handle_xcmp_message(sender, sent_at, xcm, max_weight); - } else { - debug_assert!(false, "Invalid incoming XCMP message data"); - } - } - } - max_weight - } - } - - impl DmpMessageHandler for Pallet { - fn handle_dmp_messages( - iter: impl Iterator)>, - limit: Weight, - ) -> Weight { - for (_i, (_sent_at, data)) in iter.enumerate() { - let mut id = sp_io::hashing::blake2_256(&data[..]); - let maybe_versioned = VersionedXcm::::decode(&mut &data[..]); - match maybe_versioned { - Err(_) => { - Self::deposit_event(Event::InvalidFormat(id)); - }, - Ok(versioned) => match Xcm::try_from(versioned) { - Err(()) => Self::deposit_event(Event::UnsupportedVersion(id)), - Ok(x) => { - let outcome = T::XcmExecutor::prepare_and_execute( - Parent, - x.clone(), - &mut id, - limit, - Weight::zero(), - ); - ReceivedDmp::::append(x); - Self::deposit_event(Event::ExecutedDownward(id, outcome)); - }, - }, - } - } - limit - } - } -} diff --git a/substrate/frame/revive/mock-network/src/mocks/relay_message_queue.rs b/substrate/frame/revive/mock-network/src/mocks/relay_message_queue.rs deleted file mode 100644 index 8f493c4b46429..0000000000000 --- a/substrate/frame/revive/mock-network/src/mocks/relay_message_queue.rs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Substrate. - -// Substrate is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Substrate is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Substrate. If not, see . - -use frame_support::{parameter_types, weights::Weight}; -use xcm::latest::prelude::*; -use xcm_simulator::{ - AggregateMessageOrigin, ProcessMessage, ProcessMessageError, UmpQueueId, WeightMeter, -}; - -use crate::relay_chain::{RuntimeCall, XcmConfig}; - -parameter_types! { - /// Amount of weight that can be spent per block to service messages. - pub MessageQueueServiceWeight: Weight = Weight::from_parts(1_000_000_000, 1_000_000); - pub const MessageQueueHeapSize: u32 = 65_536; - pub const MessageQueueMaxStale: u32 = 16; -} - -/// Message processor to handle any messages that were enqueued into the `MessageQueue` pallet. -pub struct MessageProcessor; -impl ProcessMessage for MessageProcessor { - type Origin = AggregateMessageOrigin; - - fn process_message( - message: &[u8], - origin: Self::Origin, - meter: &mut WeightMeter, - id: &mut [u8; 32], - ) -> Result { - let para = match origin { - AggregateMessageOrigin::Ump(UmpQueueId::Para(para)) => para, - }; - xcm_builder::ProcessXcmMessage::< - Junction, - xcm_executor::XcmExecutor, - RuntimeCall, - >::process_message(message, Junction::Parachain(para.into()), meter, id) - } -} diff --git a/substrate/frame/revive/mock-network/src/parachain.rs b/substrate/frame/revive/mock-network/src/parachain.rs deleted file mode 100644 index 9a07517588f31..0000000000000 --- a/substrate/frame/revive/mock-network/src/parachain.rs +++ /dev/null @@ -1,353 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Substrate. - -// Substrate is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Substrate is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Substrate. If not, see . - -//! Parachain runtime mock. - -mod contracts_config; -use crate::{ - mocks::msg_queue::pallet as mock_msg_queue, - primitives::{AccountId, AssetIdForAssets, Balance}, -}; -use core::marker::PhantomData; -use frame_support::{ - construct_runtime, derive_impl, parameter_types, - traits::{ - AsEnsureOriginWithArg, Contains, ContainsPair, Disabled, Everything, EverythingBut, Nothing, - }, - weights::{ - constants::{WEIGHT_PROOF_SIZE_PER_MB, WEIGHT_REF_TIME_PER_SECOND}, - Weight, - }, -}; -use frame_system::{EnsureRoot, EnsureSigned}; -use pallet_xcm::XcmPassthrough; -use sp_core::{ConstU32, ConstU64, H256}; -use sp_runtime::traits::{Get, IdentityLookup, MaybeEquivalence}; - -use xcm::latest::prelude::*; -use xcm_builder::{ - AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom, - ConvertedConcreteId, EnsureXcmOrigin, FixedRateOfFungible, FixedWeightBounds, - FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter, IsConcrete, NativeAsset, - NoChecking, ParentAsSuperuser, ParentIsPreset, SignedAccountId32AsNative, SignedToAccountId32, - SovereignSignedViaLocation, WithComputedOrigin, -}; -use xcm_executor::{traits::JustTry, Config, XcmExecutor}; - -pub type SovereignAccountOf = - (AccountId32Aliases, ParentIsPreset); - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig)] -impl frame_system::Config for Runtime { - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type Nonce = u64; - type Block = Block; - type Hash = H256; - type Hashing = ::sp_runtime::traits::BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; - type RuntimeEvent = RuntimeEvent; - type BlockWeights = (); - type BlockLength = (); - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type DbWeight = (); - type BaseCallFilter = Everything; - type SystemWeightInfo = (); - type SS58Prefix = (); - type OnSetCode = (); - type MaxConsumers = ConstU32<16>; -} - -parameter_types! { - pub ExistentialDeposit: Balance = 1; - pub const MaxLocks: u32 = 50; - pub const MaxReserves: u32 = 50; -} - -impl pallet_balances::Config for Runtime { - type AccountStore = System; - type Balance = Balance; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<0>; - type MaxLocks = MaxLocks; - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; - type RuntimeEvent = RuntimeEvent; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type WeightInfo = (); - type DoneSlashHandler = (); -} - -parameter_types! { - pub const AssetDeposit: u128 = 1_000_000; - pub const MetadataDepositBase: u128 = 1_000_000; - pub const MetadataDepositPerByte: u128 = 100_000; - pub const AssetAccountDeposit: u128 = 1_000_000; - pub const ApprovalDeposit: u128 = 1_000_000; - pub const AssetsStringLimit: u32 = 50; - pub const RemoveItemsLimit: u32 = 50; -} - -impl pallet_assets::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type Balance = Balance; - type AssetId = AssetIdForAssets; - type Currency = Balances; - type CreateOrigin = AsEnsureOriginWithArg>; - type ForceOrigin = EnsureRoot; - type AssetDeposit = AssetDeposit; - type MetadataDepositBase = MetadataDepositBase; - type MetadataDepositPerByte = MetadataDepositPerByte; - type AssetAccountDeposit = AssetAccountDeposit; - type ApprovalDeposit = ApprovalDeposit; - type StringLimit = AssetsStringLimit; - type Holder = (); - type Freezer = (); - type Extra = (); - type WeightInfo = (); - type RemoveItemsLimit = RemoveItemsLimit; - type AssetIdParameter = AssetIdForAssets; - type CallbackHandle = (); - #[cfg(feature = "runtime-benchmarks")] - type BenchmarkHelper = (); -} - -parameter_types! { - pub const ReservedXcmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0); - pub const ReservedDmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0); -} - -parameter_types! { - pub const KsmLocation: Location = Location::parent(); - pub const TokenLocation: Location = Here.into_location(); - pub const RelayNetwork: NetworkId = ByGenesis([0; 32]); - pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get()), Parachain(MsgQueue::parachain_id().into())].into(); -} - -pub type XcmOriginToCallOrigin = ( - SovereignSignedViaLocation, - ParentAsSuperuser, - SignedAccountId32AsNative, - XcmPassthrough, -); - -parameter_types! { - pub const XcmInstructionWeight: Weight = Weight::from_parts(1_000, 1_000); - pub TokensPerSecondPerMegabyte: (AssetId, u128, u128) = (AssetId(Parent.into()), 1_000_000_000_000, 1024 * 1024); - pub const MaxInstructions: u32 = 100; - pub const MaxAssetsIntoHolding: u32 = 64; - pub ForeignPrefix: Location = (Parent,).into(); - pub CheckingAccount: AccountId = PolkadotXcm::check_account(); - pub TrustedLockPairs: (Location, AssetFilter) = - (Parent.into(), Wild(AllOf { id: AssetId(Parent.into()), fun: WildFungible })); -} - -pub fn estimate_message_fee(number_of_instructions: u64) -> u128 { - let weight = estimate_weight(number_of_instructions); - - estimate_fee_for_weight(weight) -} - -pub fn estimate_weight(number_of_instructions: u64) -> Weight { - XcmInstructionWeight::get().saturating_mul(number_of_instructions) -} - -pub fn estimate_fee_for_weight(weight: Weight) -> u128 { - let (_, units_per_second, units_per_mb) = TokensPerSecondPerMegabyte::get(); - - units_per_second * (weight.ref_time() as u128) / (WEIGHT_REF_TIME_PER_SECOND as u128) + - units_per_mb * (weight.proof_size() as u128) / (WEIGHT_PROOF_SIZE_PER_MB as u128) -} - -pub type LocalBalancesTransactor = - FungibleAdapter, SovereignAccountOf, AccountId, ()>; - -pub struct FromLocationToAsset(PhantomData<(Location, AssetId)>); -impl MaybeEquivalence - for FromLocationToAsset -{ - fn convert(value: &Location) -> Option { - match value.unpack() { - (1, []) => Some(0 as AssetIdForAssets), - (1, [Parachain(para_id)]) => Some(*para_id as AssetIdForAssets), - _ => None, - } - } - - fn convert_back(_id: &AssetIdForAssets) -> Option { - None - } -} - -pub type ForeignAssetsTransactor = FungiblesAdapter< - Assets, - ConvertedConcreteId< - AssetIdForAssets, - Balance, - FromLocationToAsset, - JustTry, - >, - SovereignAccountOf, - AccountId, - NoChecking, - CheckingAccount, ->; - -/// Means for transacting assets on this chain -pub type AssetTransactors = (LocalBalancesTransactor, ForeignAssetsTransactor); - -pub struct ParentRelay; -impl Contains for ParentRelay { - fn contains(location: &Location) -> bool { - location.contains_parents_only(1) - } -} -pub struct ThisParachain; -impl Contains for ThisParachain { - fn contains(location: &Location) -> bool { - matches!(location.unpack(), (0, [Junction::AccountId32 { .. }])) - } -} - -pub type XcmRouter = crate::ParachainXcmRouter; - -pub type Barrier = ( - xcm_builder::AllowUnpaidExecutionFrom, - WithComputedOrigin< - (AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom), - UniversalLocation, - ConstU32<1>, - >, -); - -parameter_types! { - pub NftCollectionOne: AssetFilter - = Wild(AllOf { fun: WildNonFungible, id: AssetId((Parent, GeneralIndex(1)).into()) }); - pub NftCollectionOneForRelay: (AssetFilter, Location) - = (NftCollectionOne::get(), Parent.into()); - pub RelayNativeAsset: AssetFilter = Wild(AllOf { fun: WildFungible, id: AssetId((Parent, Here).into()) }); - pub RelayNativeAssetForRelay: (AssetFilter, Location) = (RelayNativeAsset::get(), Parent.into()); -} -pub type TrustedTeleporters = - (xcm_builder::Case, xcm_builder::Case); -pub type TrustedReserves = EverythingBut>; - -pub struct XcmConfig; -impl Config for XcmConfig { - type RuntimeCall = RuntimeCall; - type XcmSender = XcmRouter; - type XcmEventEmitter = PolkadotXcm; - type AssetTransactor = AssetTransactors; - type OriginConverter = XcmOriginToCallOrigin; - type IsReserve = (NativeAsset, TrustedReserves); - type IsTeleporter = TrustedTeleporters; - type UniversalLocation = UniversalLocation; - type Barrier = Barrier; - type Weigher = FixedWeightBounds; - type Trader = FixedRateOfFungible; - type ResponseHandler = PolkadotXcm; - type AssetTrap = PolkadotXcm; - type AssetLocker = PolkadotXcm; - type AssetExchanger = (); - type AssetClaims = PolkadotXcm; - type SubscriptionService = PolkadotXcm; - type PalletInstancesInfo = AllPalletsWithSystem; - type FeeManager = (); - type MaxAssetsIntoHolding = MaxAssetsIntoHolding; - type MessageExporter = (); - type UniversalAliases = Nothing; - type CallDispatcher = RuntimeCall; - type SafeCallFilter = Everything; - type Aliasers = Nothing; - type TransactionalProcessor = FrameTransactionalProcessor; - type HrmpNewChannelOpenRequestHandler = (); - type HrmpChannelAcceptedHandler = (); - type HrmpChannelClosingHandler = (); - type XcmRecorder = PolkadotXcm; -} - -impl mock_msg_queue::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type XcmExecutor = XcmExecutor; -} - -pub type LocalOriginToLocation = SignedToAccountId32; - -pub struct TrustedLockerCase(PhantomData); -impl> ContainsPair for TrustedLockerCase { - fn contains(origin: &Location, asset: &Asset) -> bool { - let (o, a) = T::get(); - a.matches(asset) && &o == origin - } -} - -impl pallet_xcm::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type SendXcmOrigin = EnsureXcmOrigin; - type XcmRouter = XcmRouter; - type ExecuteXcmOrigin = EnsureXcmOrigin; - type XcmExecuteFilter = Everything; - type XcmExecutor = XcmExecutor; - type XcmTeleportFilter = Nothing; - type XcmReserveTransferFilter = Everything; - type Weigher = FixedWeightBounds; - type UniversalLocation = UniversalLocation; - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; - type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; - type Currency = Balances; - type CurrencyMatcher = IsConcrete; - type TrustedLockers = TrustedLockerCase; - type SovereignAccountOf = SovereignAccountOf; - type MaxLockers = ConstU32<8>; - type MaxRemoteLockConsumers = ConstU32<0>; - type RemoteLockConsumerIdentifier = (); - type WeightInfo = pallet_xcm::TestWeightInfo; - type AdminOrigin = EnsureRoot; - // Aliasing is disabled: xcm_executor::Config::Aliasers is set to `Nothing`. - type AuthorizedAliasConsideration = Disabled; -} - -type Block = frame_system::mocking::MockBlock; - -impl pallet_timestamp::Config for Runtime { - type Moment = u64; - type OnTimestampSet = (); - type MinimumPeriod = ConstU64<1>; - type WeightInfo = (); -} - -construct_runtime!( - pub enum Runtime - { - System: frame_system, - Balances: pallet_balances, - Timestamp: pallet_timestamp, - MsgQueue: mock_msg_queue, - PolkadotXcm: pallet_xcm, - Contracts: pallet_revive, - Assets: pallet_assets, - } -); diff --git a/substrate/frame/revive/mock-network/src/parachain/contracts_config.rs b/substrate/frame/revive/mock-network/src/parachain/contracts_config.rs deleted file mode 100644 index 49567a6d87a7d..0000000000000 --- a/substrate/frame/revive/mock-network/src/parachain/contracts_config.rs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Substrate. - -// Substrate is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Substrate is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Substrate. If not, see . - -use super::{AccountId, Balances, Runtime, RuntimeCall, RuntimeEvent}; -use crate::parachain::RuntimeHoldReason; -use frame_support::derive_impl; -use frame_system::EnsureSigned; - -#[derive_impl(pallet_revive::config_preludes::TestDefaultConfig)] -impl pallet_revive::Config for Runtime { - type AddressMapper = pallet_revive::AccountId32Mapper; - type Currency = Balances; - type UploadOrigin = EnsureSigned; - type InstantiateOrigin = EnsureSigned; - type Time = super::Timestamp; - type Xcm = pallet_xcm::Pallet; -} diff --git a/substrate/frame/revive/mock-network/src/primitives.rs b/substrate/frame/revive/mock-network/src/primitives.rs deleted file mode 100644 index cb9b2f00f9e73..0000000000000 --- a/substrate/frame/revive/mock-network/src/primitives.rs +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Substrate. - -// Substrate is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Substrate is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Substrate. If not, see . - -pub type Balance = u128; - -pub const UNITS: Balance = 10_000_000_000; -pub const CENTS: Balance = UNITS / 100; // 100_000_000 - -pub type AccountId = sp_runtime::AccountId32; -pub type AssetIdForAssets = u128; diff --git a/substrate/frame/revive/mock-network/src/relay_chain.rs b/substrate/frame/revive/mock-network/src/relay_chain.rs deleted file mode 100644 index 0e60e3df6e19d..0000000000000 --- a/substrate/frame/revive/mock-network/src/relay_chain.rs +++ /dev/null @@ -1,243 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Substrate. - -// Substrate is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Substrate is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Substrate. If not, see . - -//! Relay chain runtime mock. - -use frame_support::{ - construct_runtime, derive_impl, parameter_types, - traits::{Contains, Disabled, Everything, Nothing}, - weights::Weight, -}; - -use frame_system::EnsureRoot; -use sp_core::{ConstU32, H256}; -use sp_runtime::traits::IdentityLookup; - -use polkadot_parachain_primitives::primitives::Id as ParaId; -use polkadot_runtime_parachains::{configuration, origin, shared}; -use xcm::latest::prelude::*; -use xcm_builder::{ - AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowSubscriptionsFrom, - AllowTopLevelPaidExecutionFrom, ChildParachainAsNative, ChildParachainConvertsVia, - ChildSystemParachainAsSuperuser, DescribeAllTerminal, DescribeFamily, FixedRateOfFungible, - FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, HashedDescription, IsConcrete, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, WithComputedOrigin, -}; -use xcm_executor::{Config, XcmExecutor}; - -use super::{ - mocks::relay_message_queue::*, - primitives::{AccountId, Balance}, -}; - -#[derive_impl(frame_system::config_preludes::TestDefaultConfig)] -impl frame_system::Config for Runtime { - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - type Block = Block; - type Nonce = u64; - type Hash = H256; - type Hashing = ::sp_runtime::traits::BlakeTwo256; - type AccountId = AccountId; - type Lookup = IdentityLookup; - type RuntimeEvent = RuntimeEvent; - type BlockWeights = (); - type BlockLength = (); - type Version = (); - type PalletInfo = PalletInfo; - type AccountData = pallet_balances::AccountData; - type OnNewAccount = (); - type OnKilledAccount = (); - type DbWeight = (); - type BaseCallFilter = Everything; - type SystemWeightInfo = (); - type SS58Prefix = (); - type OnSetCode = (); - type MaxConsumers = ConstU32<16>; -} - -parameter_types! { - pub ExistentialDeposit: Balance = 1; - pub const MaxLocks: u32 = 50; - pub const MaxReserves: u32 = 50; -} - -impl pallet_balances::Config for Runtime { - type MaxLocks = MaxLocks; - type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; - type AccountStore = System; - type WeightInfo = (); - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<0>; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type DoneSlashHandler = (); -} - -impl shared::Config for Runtime { - type DisabledValidators = (); -} - -impl configuration::Config for Runtime { - type WeightInfo = configuration::TestWeightInfo; -} - -parameter_types! { - pub RelayNetwork: NetworkId = ByGenesis([0; 32]); - pub const TokenLocation: Location = Here.into_location(); - pub UniversalLocation: InteriorLocation = RelayNetwork::get().into(); - pub UnitWeightCost: u64 = 1_000; -} - -pub type SovereignAccountOf = ( - HashedDescription>, - AccountId32Aliases, - ChildParachainConvertsVia, -); - -pub type LocalBalancesTransactor = - FungibleAdapter, SovereignAccountOf, AccountId, ()>; - -pub type AssetTransactors = LocalBalancesTransactor; - -type LocalOriginConverter = ( - SovereignSignedViaLocation, - ChildParachainAsNative, - SignedAccountId32AsNative, - ChildSystemParachainAsSuperuser, -); - -parameter_types! { - pub const XcmInstructionWeight: Weight = Weight::from_parts(1_000, 1_000); - pub TokensPerSecondPerMegabyte: (AssetId, u128, u128) = - (AssetId(TokenLocation::get()), 1_000_000_000_000, 1024 * 1024); - pub const MaxInstructions: u32 = 100; - pub const MaxAssetsIntoHolding: u32 = 64; -} - -pub struct ChildrenParachains; -impl Contains for ChildrenParachains { - fn contains(location: &Location) -> bool { - matches!(location.unpack(), (0, [Parachain(_)])) - } -} - -pub type XcmRouter = crate::RelayChainXcmRouter; -pub type Barrier = WithComputedOrigin< - ( - AllowExplicitUnpaidExecutionFrom, - AllowTopLevelPaidExecutionFrom, - AllowSubscriptionsFrom, - ), - UniversalLocation, - ConstU32<1>, ->; - -pub struct XcmConfig; -impl Config for XcmConfig { - type RuntimeCall = RuntimeCall; - type XcmSender = XcmRouter; - type XcmEventEmitter = XcmPallet; - type AssetTransactor = AssetTransactors; - type OriginConverter = LocalOriginConverter; - type IsReserve = (); - type IsTeleporter = (); - type UniversalLocation = UniversalLocation; - type Barrier = Barrier; - type Weigher = FixedWeightBounds; - type Trader = FixedRateOfFungible; - type ResponseHandler = XcmPallet; - type AssetTrap = XcmPallet; - type AssetLocker = XcmPallet; - type AssetExchanger = (); - type AssetClaims = XcmPallet; - type SubscriptionService = XcmPallet; - type PalletInstancesInfo = AllPalletsWithSystem; - type FeeManager = (); - type MaxAssetsIntoHolding = MaxAssetsIntoHolding; - type MessageExporter = (); - type UniversalAliases = Nothing; - type CallDispatcher = RuntimeCall; - type SafeCallFilter = Everything; - type Aliasers = Nothing; - type TransactionalProcessor = FrameTransactionalProcessor; - type HrmpNewChannelOpenRequestHandler = (); - type HrmpChannelAcceptedHandler = (); - type HrmpChannelClosingHandler = (); - type XcmRecorder = XcmPallet; -} - -pub type LocalOriginToLocation = SignedToAccountId32; - -impl pallet_xcm::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type SendXcmOrigin = xcm_builder::EnsureXcmOrigin; - type XcmRouter = XcmRouter; - type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin; - type XcmExecuteFilter = Everything; - type XcmExecutor = XcmExecutor; - type XcmTeleportFilter = Everything; - type XcmReserveTransferFilter = Everything; - type Weigher = FixedWeightBounds; - type UniversalLocation = UniversalLocation; - type RuntimeOrigin = RuntimeOrigin; - type RuntimeCall = RuntimeCall; - const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100; - type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion; - type Currency = Balances; - type CurrencyMatcher = IsConcrete; - type TrustedLockers = (); - type SovereignAccountOf = SovereignAccountOf; - type MaxLockers = ConstU32<8>; - type MaxRemoteLockConsumers = ConstU32<0>; - type RemoteLockConsumerIdentifier = (); - type WeightInfo = pallet_xcm::TestWeightInfo; - type AdminOrigin = EnsureRoot; - // Aliasing is disabled: xcm_executor::Config::Aliasers is set to `Nothing`. - type AuthorizedAliasConsideration = Disabled; -} - -impl origin::Config for Runtime {} - -type Block = frame_system::mocking::MockBlock; - -impl pallet_message_queue::Config for Runtime { - type RuntimeEvent = RuntimeEvent; - type Size = u32; - type HeapSize = MessageQueueHeapSize; - type MaxStale = MessageQueueMaxStale; - type ServiceWeight = MessageQueueServiceWeight; - type IdleMaxServiceWeight = (); - type MessageProcessor = MessageProcessor; - type QueueChangeHandler = (); - type WeightInfo = (); - type QueuePausedQuery = (); -} - -construct_runtime!( - pub enum Runtime { - System: frame_system, - Balances: pallet_balances, - ParasOrigin: origin, - XcmPallet: pallet_xcm, - MessageQueue: pallet_message_queue, - } -); diff --git a/substrate/frame/revive/mock-network/src/tests.rs b/substrate/frame/revive/mock-network/src/tests.rs deleted file mode 100644 index 34f797c2b530f..0000000000000 --- a/substrate/frame/revive/mock-network/src/tests.rs +++ /dev/null @@ -1,204 +0,0 @@ -// This file is part of Substrate. - -// Copyright (C) Parity Technologies (UK) Ltd. -// SPDX-License-Identifier: Apache-2.0 - -// Licensed under the Apache License, Version 2.0 (the "License"); -// you may not use this file except in compliance with the License. -// You may obtain a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -// Unless required by applicable law or agreed to in writing, software -// distributed under the License is distributed on an "AS IS" BASIS, -// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// See the License for the specific language governing permissions and -// limitations under the License. - -use crate::{ - parachain, parachain_account_sovereign_account_id, primitives::CENTS, relay_chain, MockNet, - ParaA, ParachainBalances, Relay, ALICE, BOB, INITIAL_BALANCE, -}; -use codec::{Decode, Encode}; -use frame_support::traits::{fungibles::Mutate, Currency}; -use frame_system::RawOrigin; -use pallet_revive::{ - test_utils::{self, builder::*}, - Code, DepositLimit, -}; -use pallet_revive_fixtures::compile_module; -use pallet_revive_uapi::ReturnErrorCode; -use sp_core::H160; -use xcm::{v4::prelude::*, VersionedLocation, VersionedXcm}; -use xcm_simulator::TestExt; - -macro_rules! assert_return_code { - ( $x:expr , $y:expr $(,)? ) => {{ - assert_eq!(u32::from_le_bytes($x.data[..].try_into().unwrap()), $y as u32); - }}; -} - -fn bare_call(dest: H160) -> BareCallBuilder { - BareCallBuilder::::bare_call(RawOrigin::Signed(ALICE).into(), dest) -} - -/// Instantiate the tests contract, and fund it with some balance and assets. -fn instantiate_test_contract(name: &str) -> Contract { - let (wasm, _) = compile_module(name).unwrap(); - - // Instantiate contract. - let contract = ParaA::execute_with(|| { - BareInstantiateBuilder::::bare_instantiate( - RawOrigin::Signed(ALICE).into(), - Code::Upload(wasm), - ) - .storage_deposit_limit(DepositLimit::Balance(1_000_000_000_000)) - .build_and_unwrap_contract() - }); - - // Funds contract account with some balance and assets. - ParaA::execute_with(|| { - parachain::Balances::make_free_balance_be(&contract.account_id, INITIAL_BALANCE); - parachain::Assets::mint_into(0u32.into(), &contract.account_id, INITIAL_BALANCE).unwrap(); - }); - Relay::execute_with(|| { - let sovereign_account = - parachain_account_sovereign_account_id(1u32, contract.account_id.clone()); - relay_chain::Balances::make_free_balance_be(&sovereign_account, INITIAL_BALANCE); - }); - - contract -} - -#[test] -fn test_xcm_execute() { - MockNet::reset(); - - let Contract { addr, account_id } = instantiate_test_contract("xcm_execute"); - - // Execute XCM instructions through the contract. - ParaA::execute_with(|| { - let amount: u128 = 10 * CENTS; - let assets: Asset = (Here, amount).into(); - let beneficiary = AccountId32 { network: None, id: BOB.clone().into() }; - - // The XCM used to transfer funds to Bob. - let message: Xcm<()> = Xcm::builder_unsafe() - .withdraw_asset(assets.clone()) - .deposit_asset(assets, beneficiary) - .build(); - - let result = bare_call(addr).data(VersionedXcm::V4(message).encode()).build(); - - assert_eq!(result.gas_consumed, result.gas_required); - assert_return_code!(&result.result.unwrap(), ReturnErrorCode::Success); - - // Check if the funds are subtracted from the account of Alice and added to the account of - // Bob. - let initial = INITIAL_BALANCE; - assert_eq!(ParachainBalances::free_balance(BOB), initial + amount); - assert_eq!(ParachainBalances::free_balance(&account_id), initial - amount); - }); -} - -#[test] -fn test_xcm_execute_incomplete() { - MockNet::reset(); - - let Contract { addr, account_id } = instantiate_test_contract("xcm_execute"); - let amount = 10 * CENTS; - - // Execute XCM instructions through the contract. - ParaA::execute_with(|| { - let assets: Asset = (Here, amount).into(); - let beneficiary = AccountId32 { network: None, id: BOB.clone().into() }; - - // The XCM used to transfer funds to Bob. - let message: Xcm<()> = Xcm::builder_unsafe() - .withdraw_asset(assets.clone()) - // This will fail as the contract does not have enough balance to complete both - // withdrawals. - .withdraw_asset((Here, INITIAL_BALANCE)) - .buy_execution(assets.clone(), Unlimited) - .deposit_asset(assets, beneficiary) - .build(); - - let result = bare_call(addr).data(VersionedXcm::V4(message).encode()).build(); - - assert_eq!(result.gas_consumed, result.gas_required); - assert_return_code!(&result.result.unwrap(), ReturnErrorCode::XcmExecutionFailed); - - assert_eq!(ParachainBalances::free_balance(BOB), INITIAL_BALANCE); - assert_eq!(ParachainBalances::free_balance(&account_id), INITIAL_BALANCE - amount); - }); -} - -#[test] -fn test_xcm_execute_reentrant_call() { - MockNet::reset(); - - let Contract { addr, .. } = instantiate_test_contract("xcm_execute"); - - ParaA::execute_with(|| { - let transact_call = parachain::RuntimeCall::Contracts(pallet_revive::Call::call { - dest: addr, - gas_limit: 1_000_000.into(), - storage_deposit_limit: test_utils::deposit_limit::(), - data: vec![], - value: 0u128, - }); - - // The XCM used to transfer funds to Bob. - let message: Xcm = Xcm::builder_unsafe() - .transact(OriginKind::Native, 1_000_000_000, transact_call.encode()) - .expect_transact_status(MaybeErrorCode::Success) - .build(); - - let result = bare_call(addr) - .data(VersionedXcm::V4(message).encode()) - .build_and_unwrap_result(); - - assert_return_code!(&result, ReturnErrorCode::XcmExecutionFailed); - - // Funds should not change hands as the XCM transact failed. - assert_eq!(ParachainBalances::free_balance(BOB), INITIAL_BALANCE); - }); -} - -#[test] -fn test_xcm_send() { - MockNet::reset(); - let Contract { addr, account_id } = instantiate_test_contract("xcm_send"); - let amount = 1_000 * CENTS; - let fee = parachain::estimate_message_fee(4); // Accounts for the `DescendOrigin` instruction added by `send_xcm` - - // Send XCM instructions through the contract, to transfer some funds from the contract - // derivative account to Alice on the relay chain. - ParaA::execute_with(|| { - let dest = VersionedLocation::V4(Parent.into()); - let assets: Asset = (Here, amount).into(); - let beneficiary = AccountId32 { network: None, id: ALICE.clone().into() }; - - let message: Xcm<()> = Xcm::builder() - .withdraw_asset(assets.clone()) - .buy_execution((Here, fee), Unlimited) - .deposit_asset(assets, beneficiary) - .build(); - - let result = bare_call(addr) - .data((dest, VersionedXcm::V4(message)).encode()) - .build_and_unwrap_result(); - - let mut data = &result.data[..]; - XcmHash::decode(&mut data).expect("Failed to decode xcm_send message_id"); - }); - - Relay::execute_with(|| { - let derived_contract_addr = ¶chain_account_sovereign_account_id(1, account_id); - assert_eq!( - INITIAL_BALANCE - amount, - relay_chain::Balances::free_balance(derived_contract_addr) - ); - assert_eq!(INITIAL_BALANCE + amount - fee, relay_chain::Balances::free_balance(ALICE)); - }); -} diff --git a/substrate/frame/revive/src/exec.rs b/substrate/frame/revive/src/exec.rs index 7797b7b2e475b..f980eb148d9ac 100644 --- a/substrate/frame/revive/src/exec.rs +++ b/substrate/frame/revive/src/exec.rs @@ -32,12 +32,12 @@ use alloc::vec::Vec; use core::{fmt::Debug, marker::PhantomData, mem}; use frame_support::{ crypto::ecdsa::ECDSAExt, - dispatch::{DispatchResult, DispatchResultWithPostInfo}, + dispatch::DispatchResult, storage::{with_transaction, TransactionOutcome}, traits::{ fungible::{Inspect, Mutate}, tokens::{Fortitude, Preservation}, - Contains, FindAuthor, OriginTrait, Time, + FindAuthor, Time, }, weights::Weight, Blake2_128Concat, BoundedVec, StorageHasher, @@ -53,7 +53,7 @@ use sp_core::{ }; use sp_io::{crypto::secp256k1_ecdsa_recover_compressed, hashing::blake2_256}; use sp_runtime::{ - traits::{BadOrigin, Bounded, Convert, Dispatchable, Saturating, Zero}, + traits::{BadOrigin, Bounded, Convert, Saturating, Zero}, DispatchError, SaturatedConversion, }; @@ -229,9 +229,6 @@ pub trait Ext: PrecompileWithInfoExt { /// /// Note: Requires &mut self to access the contract info. fn set_immutable_data(&mut self, data: ImmutableData) -> Result<(), DispatchError>; - - /// Call some dispatchable and return the result. - fn call_runtime(&self, call: ::RuntimeCall) -> DispatchResultWithPostInfo; } /// Environment functions which are available to pre-compiles with `HAS_CONTRACT_INFO = true`. @@ -1588,12 +1585,6 @@ where Ok(()) } - fn call_runtime(&self, call: ::RuntimeCall) -> DispatchResultWithPostInfo { - let mut origin: T::RuntimeOrigin = RawOrigin::Signed(self.account_id().clone()).into(); - origin.add_filter(T::CallFilter::contains); - call.dispatch(origin) - } - fn immutable_data_len(&mut self) -> u32 { self.top_frame_mut().contract_info().immutable_data_len() } diff --git a/substrate/frame/revive/src/exec/tests.rs b/substrate/frame/revive/src/exec/tests.rs index ef2b165fd337b..e352fa444eb7c 100644 --- a/substrate/frame/revive/src/exec/tests.rs +++ b/substrate/frame/revive/src/exec/tests.rs @@ -28,17 +28,17 @@ use crate::{ test_utils::*, tests::{ test_utils::{get_balance, place_contract, set_balance}, - ExtBuilder, RuntimeCall, RuntimeEvent as MetaEvent, Test, TestFilter, + ExtBuilder, RuntimeEvent as MetaEvent, Test, }, AddressMapper, Error, }; use assert_matches::assert_matches; use frame_support::{assert_err, assert_ok, parameter_types}; -use frame_system::{AccountInfo, EventRecord, Phase}; +use frame_system::AccountInfo; use pallet_revive_uapi::ReturnFlags; use pretty_assertions::assert_eq; use sp_io::hashing::keccak_256; -use sp_runtime::{traits::Hash, DispatchError}; +use sp_runtime::DispatchError; use std::{cell::RefCell, collections::hash_map::HashMap, rc::Rc}; type System = frame_system::Pallet; @@ -1584,138 +1584,6 @@ fn call_deny_reentry() { }); } -#[test] -fn call_runtime_works() { - let code_hash = MockLoader::insert(Call, |ctx, _| { - let call = RuntimeCall::System(frame_system::Call::remark_with_event { - remark: b"Hello World".to_vec(), - }); - ctx.ext.call_runtime(call).unwrap(); - exec_success() - }); - - ExtBuilder::default().build().execute_with(|| { - let min_balance = ::Currency::minimum_balance(); - - let mut gas_meter = GasMeter::::new(GAS_LIMIT); - set_balance(&ALICE, min_balance * 10); - place_contract(&BOB, code_hash); - let origin = Origin::from_account_id(ALICE); - let mut storage_meter = storage::meter::Meter::new(0); - System::reset_events(); - MockStack::run_call( - origin, - BOB_ADDR, - &mut gas_meter, - &mut storage_meter, - U256::zero(), - vec![], - false, - ) - .unwrap(); - - let remark_hash = ::Hashing::hash(b"Hello World"); - assert_eq!( - System::events(), - vec![EventRecord { - phase: Phase::Initialization, - event: MetaEvent::System(frame_system::Event::Remarked { - sender: BOB_FALLBACK, - hash: remark_hash - }), - topics: vec![], - },] - ); - }); -} - -#[test] -fn call_runtime_filter() { - let code_hash = MockLoader::insert(Call, |ctx, _| { - use frame_system::Call as SysCall; - use pallet_balances::Call as BalanceCall; - use pallet_utility::Call as UtilCall; - - // remark should still be allowed - let allowed_call = - RuntimeCall::System(SysCall::remark_with_event { remark: b"Hello".to_vec() }); - - // transfers are disallowed by the `TestFiler` (see below) - let forbidden_call = - RuntimeCall::Balances(BalanceCall::transfer_allow_death { dest: CHARLIE, value: 22 }); - - // simple cases: direct call - assert_err!( - ctx.ext.call_runtime(forbidden_call.clone()), - frame_system::Error::::CallFiltered - ); - - // as part of a patch: return is OK (but it interrupted the batch) - assert_ok!(ctx.ext.call_runtime(RuntimeCall::Utility(UtilCall::batch { - calls: vec![allowed_call.clone(), forbidden_call, allowed_call] - })),); - - // the transfer wasn't performed - assert_eq!(get_balance(&CHARLIE), 0); - - exec_success() - }); - - TestFilter::set_filter(|call| match call { - RuntimeCall::Balances(pallet_balances::Call::transfer_allow_death { .. }) => false, - _ => true, - }); - - ExtBuilder::default().build().execute_with(|| { - let min_balance = ::Currency::minimum_balance(); - - let mut gas_meter = GasMeter::::new(GAS_LIMIT); - set_balance(&ALICE, min_balance * 10); - place_contract(&BOB, code_hash); - let origin = Origin::from_account_id(ALICE); - let mut storage_meter = storage::meter::Meter::new(0); - System::reset_events(); - MockStack::run_call( - origin, - BOB_ADDR, - &mut gas_meter, - &mut storage_meter, - U256::zero(), - vec![], - false, - ) - .unwrap(); - - let remark_hash = ::Hashing::hash(b"Hello"); - assert_eq!( - System::events(), - vec![ - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::System(frame_system::Event::Remarked { - sender: BOB_FALLBACK, - hash: remark_hash - }), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::Utility(pallet_utility::Event::ItemCompleted), - topics: vec![], - }, - EventRecord { - phase: Phase::Initialization, - event: MetaEvent::Utility(pallet_utility::Event::BatchInterrupted { - index: 1, - error: frame_system::Error::::CallFiltered.into() - },), - topics: vec![], - }, - ] - ); - }); -} - #[test] fn nonce() { let fail_code = MockLoader::insert(Constructor, |_, _| exec_trapped()); diff --git a/substrate/frame/revive/src/lib.rs b/substrate/frame/revive/src/lib.rs index c3a3b1ad81741..76895a3296b1e 100644 --- a/substrate/frame/revive/src/lib.rs +++ b/substrate/frame/revive/src/lib.rs @@ -65,7 +65,7 @@ use frame_support::{ traits::{ fungible::{Inspect, Mutate, MutateHold}, tokens::{Fortitude::Polite, Preservation::Preserve}, - ConstU32, ConstU64, Contains, EnsureOrigin, Get, IsType, OriginTrait, Time, + ConstU32, ConstU64, EnsureOrigin, Get, IsType, OriginTrait, Time, }, weights::WeightMeter, BoundedVec, RuntimeDebugNoBound, @@ -162,31 +162,6 @@ pub mod pallet { #[pallet::no_default_bounds] type RuntimeHoldReason: From; - /// Filter that is applied to calls dispatched by contracts. - /// - /// Use this filter to control which dispatchables are callable by contracts. - /// This is applied in **addition** to [`frame_system::Config::BaseCallFilter`]. - /// It is recommended to treat this as a whitelist. - /// - /// # Stability - /// - /// The runtime **must** make sure that all dispatchables that are callable by - /// contracts remain stable. In addition [`Self::RuntimeCall`] itself must remain stable. - /// This means that no existing variants are allowed to switch their positions. - /// - /// # Note - /// - /// Note that dispatchables that are called via contracts do not spawn their - /// own wasm instance for each call (as opposed to when called via a transaction). - /// Therefore please make sure to be restrictive about which dispatchables are allowed - /// in order to not introduce a new DoS vector like memory allocation patterns that can - /// be exploited to drive the runtime into a panic. - /// - /// This filter does not apply to XCM transact calls. To impose restrictions on XCM transact - /// calls, you must configure them separately within the XCM pallet itself. - #[pallet::no_default_bounds] - type CallFilter: Contains<::RuntimeCall>; - /// Used to answer contracts' queries regarding the current weight price. This is **not** /// used to calculate the actual fee and is only for informational purposes. #[pallet::no_default_bounds] @@ -266,15 +241,6 @@ pub mod pallet { #[pallet::no_default_bounds] type InstantiateOrigin: EnsureOrigin; - /// A type that exposes XCM APIs, allowing contracts to interact with other parachains, and - /// execute XCM programs. - #[pallet::no_default_bounds] - type Xcm: xcm_builder::Controller< - OriginFor, - ::RuntimeCall, - BlockNumberFor, - >; - /// The amount of memory in bytes that parachain nodes a lot to the runtime. /// /// This is used in [`Pallet::integrity_test`] to make sure that the runtime has enough @@ -360,7 +326,6 @@ pub mod pallet { #[inject_runtime_type] type RuntimeCall = (); - type CallFilter = (); type Precompiles = (); type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; type DepositPerByte = DepositPerByte; @@ -371,7 +336,6 @@ pub mod pallet { type InstantiateOrigin = EnsureSigned; type WeightInfo = (); type WeightPrice = Self; - type Xcm = (); type RuntimeMemory = ConstU32<{ 128 * 1024 * 1024 }>; type PVFMemory = ConstU32<{ 512 * 1024 * 1024 }>; type ChainId = ConstU64<42>; @@ -432,8 +396,6 @@ pub mod pallet { InputForwarded = 0x0E, /// The amount of topics passed to `seal_deposit_events` exceeds the limit. TooManyTopics = 0x0F, - /// Failed to decode the XCM program. - XCMDecodeFailed = 0x11, /// A contract with the same AccountId already exists. DuplicateContract = 0x12, /// A contract self destructed in its constructor. diff --git a/substrate/frame/revive/src/tests.rs b/substrate/frame/revive/src/tests.rs index b9251e1168b32..acb6ebc8fc1da 100644 --- a/substrate/frame/revive/src/tests.rs +++ b/substrate/frame/revive/src/tests.rs @@ -37,17 +37,16 @@ use crate::{ use crate::test_utils::builder::Contract; use assert_matches::assert_matches; -use codec::{Decode, Encode}; +use codec::Encode; use frame_support::{ - assert_err, assert_err_ignore_postinfo, assert_err_with_weight, assert_noop, assert_ok, - derive_impl, + assert_err, assert_err_ignore_postinfo, assert_noop, assert_ok, derive_impl, pallet_prelude::EnsureOrigin, parameter_types, storage::child, traits::{ fungible::{BalancedHold, Inspect, Mutate, MutateHold}, tokens::Preservation, - ConstU32, ConstU64, Contains, FindAuthor, OnIdle, OnInitialize, StorageVersion, + ConstU32, ConstU64, FindAuthor, OnIdle, OnInitialize, StorageVersion, }, weights::{constants::WEIGHT_REF_TIME_PER_SECOND, FixedFee, IdentityFee, Weight, WeightMeter}, }; @@ -293,36 +292,6 @@ impl Convert> for Test { } } -/// A filter whose filter function can be swapped at runtime. -pub struct TestFilter; - -#[derive(Clone)] -pub struct Filters { - filter: fn(&RuntimeCall) -> bool, -} - -impl Default for Filters { - fn default() -> Self { - Filters { filter: (|_| true) } - } -} - -parameter_types! { - static CallFilter: Filters = Default::default(); -} - -impl TestFilter { - pub fn set_filter(filter: fn(&RuntimeCall) -> bool) { - CallFilter::mutate(|fltr| fltr.filter = filter); - } -} - -impl Contains for TestFilter { - fn contains(call: &RuntimeCall) -> bool { - (CallFilter::get().filter)(call) - } -} - parameter_types! { pub static UploadAccount: Option<::AccountId> = None; pub static InstantiateAccount: Option<::AccountId> = None; @@ -369,7 +338,6 @@ impl Config for Test { type Time = Timestamp; type AddressMapper = AccountId32Mapper; type Currency = Balances; - type CallFilter = TestFilter; type DepositPerByte = DepositPerByte; type DepositPerItem = DepositPerItem; type UnsafeUnstableInterface = UnstableInterface; @@ -1904,7 +1872,6 @@ fn refcounter() { #[test] fn gas_estimation_for_subcalls() { let (caller_code, _caller_hash) = compile_module("call_with_limit").unwrap(); - let (call_runtime_code, _caller_hash) = compile_module("call_runtime").unwrap(); let (dummy_code, _callee_hash) = compile_module("dummy").unwrap(); ExtBuilder::default().existential_deposit(50).build().execute_with(|| { let min_balance = Contracts::min_balance(); @@ -1919,11 +1886,6 @@ fn gas_estimation_for_subcalls() { .value(min_balance * 100) .build_and_unwrap_contract(); - let Contract { addr: addr_call_runtime, .. } = - builder::bare_instantiate(Code::Upload(call_runtime_code)) - .value(min_balance * 100) - .build_and_unwrap_contract(); - // Run the test for all of those weight limits for the subcall let weights = [ Weight::MAX, @@ -1934,124 +1896,63 @@ fn gas_estimation_for_subcalls() { Weight::from_parts(GAS_LIMIT.ref_time(), u64::MAX), ]; - // This call is passed to the sub call in order to create a large `required_weight` - let runtime_call = RuntimeCall::Dummy(pallet_dummy::Call::overestimate_pre_charge { - pre_charge: Weight::from_parts(10_000_000_000, 512 * 1024), - actual_weight: Weight::from_parts(1, 1), - }) - .encode(); - - // Encodes which contract should be sub called with which input - let sub_calls: [(&[u8], Vec<_>, bool); 2] = [ - (addr_dummy.as_ref(), vec![], false), - (addr_call_runtime.as_ref(), runtime_call, true), - ]; + let (sub_addr, sub_input) = (addr_dummy.as_ref(), vec![]); for weight in weights { - for (sub_addr, sub_input, out_of_gas_in_subcall) in &sub_calls { - let input: Vec = sub_addr - .iter() - .cloned() - .chain(weight.ref_time().to_le_bytes()) - .chain(weight.proof_size().to_le_bytes()) - .chain(sub_input.clone()) - .collect(); - - // Call in order to determine the gas that is required for this call - let result_orig = builder::bare_call(addr_caller).data(input.clone()).build(); - assert_ok!(&result_orig.result); - - // If the out of gas happens in the subcall the caller contract - // will just trap. Otherwise we would need to forward an error - // code to signal that the sub contract ran out of gas. - let error: DispatchError = if *out_of_gas_in_subcall { - assert!(result_orig.gas_required.all_gt(result_orig.gas_consumed)); - >::ContractTrapped.into() - } else { - assert_eq!(result_orig.gas_required, result_orig.gas_consumed); - >::OutOfGas.into() - }; - - // Make the same call using the estimated gas. Should succeed. - let result = builder::bare_call(addr_caller) - .gas_limit(result_orig.gas_required) - .storage_deposit_limit(result_orig.storage_deposit.charge_or_zero().into()) - .data(input.clone()) - .build(); - assert_ok!(&result.result); - - // Check that it fails with too little ref_time - let result = builder::bare_call(addr_caller) - .gas_limit(result_orig.gas_required.sub_ref_time(1)) - .storage_deposit_limit(result_orig.storage_deposit.charge_or_zero().into()) - .data(input.clone()) - .build(); - assert_err!(result.result, error); - - // Check that it fails with too little proof_size - let result = builder::bare_call(addr_caller) - .gas_limit(result_orig.gas_required.sub_proof_size(1)) - .storage_deposit_limit(result_orig.storage_deposit.charge_or_zero().into()) - .data(input.clone()) - .build(); - assert_err!(result.result, error); - } + let input: Vec = sub_addr + .iter() + .cloned() + .chain(weight.ref_time().to_le_bytes()) + .chain(weight.proof_size().to_le_bytes()) + .chain(sub_input.clone()) + .collect(); + + // Call in order to determine the gas that is required for this call + let result_orig = builder::bare_call(addr_caller).data(input.clone()).build(); + assert_ok!(&result_orig.result); + assert_eq!(result_orig.gas_required, result_orig.gas_consumed); + + // Make the same call using the estimated gas. Should succeed. + let result = builder::bare_call(addr_caller) + .gas_limit(result_orig.gas_required) + .storage_deposit_limit(result_orig.storage_deposit.charge_or_zero().into()) + .data(input.clone()) + .build(); + assert_ok!(&result.result); + + // Check that it fails with too little ref_time + let result = builder::bare_call(addr_caller) + .gas_limit(result_orig.gas_required.sub_ref_time(1)) + .storage_deposit_limit(result_orig.storage_deposit.charge_or_zero().into()) + .data(input.clone()) + .build(); + assert_err!(result.result, >::OutOfGas); + + // Check that it fails with too little proof_size + let result = builder::bare_call(addr_caller) + .gas_limit(result_orig.gas_required.sub_proof_size(1)) + .storage_deposit_limit(result_orig.storage_deposit.charge_or_zero().into()) + .data(input.clone()) + .build(); + assert_err!(result.result, >::OutOfGas); } }); } #[test] -fn gas_estimation_call_runtime() { - let (caller_code, _caller_hash) = compile_module("call_runtime").unwrap(); - ExtBuilder::default().existential_deposit(50).build().execute_with(|| { - let min_balance = Contracts::min_balance(); - let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); - let _ = ::Currency::set_balance(&CHARLIE, 1000 * min_balance); - - let Contract { addr: addr_caller, .. } = - builder::bare_instantiate(Code::Upload(caller_code)) - .value(min_balance * 100) - .salt(Some([0; 32])) - .build_and_unwrap_contract(); +fn call_runtime_reentrancy_guarded() { + use crate::precompiles::Precompile; + use alloy_core::sol_types::SolInterface; + use precompiles::{INoInfo, NoInfo}; - // Call something trivial with a huge gas limit so that we can observe the effects - // of pre-charging. This should create a difference between consumed and required. - let call = RuntimeCall::Dummy(pallet_dummy::Call::overestimate_pre_charge { - pre_charge: Weight::from_parts(10_000_000, 1_000), - actual_weight: Weight::from_parts(100, 100), - }); - let result = builder::bare_call(addr_caller).data(call.encode()).build(); - // contract encodes the result of the dispatch runtime - let outcome = u32::decode(&mut result.result.unwrap().data.as_ref()).unwrap(); - assert_eq!(outcome, 0); - assert!(result.gas_required.all_gt(result.gas_consumed)); - - // Make the same call using the required gas. Should succeed. - assert_ok!( - builder::bare_call(addr_caller) - .gas_limit(result.gas_required) - .data(call.encode()) - .build() - .result - ); - }); -} + let precompile_addr = H160(NoInfo::::MATCHER.base_address()); -#[test] -fn call_runtime_reentrancy_guarded() { - let (caller_code, _caller_hash) = compile_module("call_runtime").unwrap(); let (callee_code, _callee_hash) = compile_module("dummy").unwrap(); ExtBuilder::default().existential_deposit(50).build().execute_with(|| { let min_balance = Contracts::min_balance(); let _ = ::Currency::set_balance(&ALICE, 1000 * min_balance); let _ = ::Currency::set_balance(&CHARLIE, 1000 * min_balance); - let Contract { addr: addr_caller, .. } = - builder::bare_instantiate(Code::Upload(caller_code)) - .value(min_balance * 100) - .salt(Some([0; 32])) - .build_and_unwrap_contract(); - let Contract { addr: addr_callee, .. } = builder::bare_instantiate(Code::Upload(callee_code)) .value(min_balance * 100) @@ -2065,13 +1966,19 @@ fn call_runtime_reentrancy_guarded() { gas_limit: GAS_LIMIT / 3, storage_deposit_limit: deposit_limit::(), data: vec![], - }); + }) + .encode(); // Call runtime to re-enter back to contracts engine by // calling dummy contract - let result = builder::bare_call(addr_caller).data(call.encode()).build_and_unwrap_result(); + let result = builder::bare_call(precompile_addr) + .data( + INoInfo::INoInfoCalls::callRuntime(INoInfo::callRuntimeCall { call: call.into() }) + .abi_encode(), + ) + .build(); // Call to runtime should fail because of the re-entrancy guard - assert_return_code!(result, RuntimeReturnCode::CallRuntimeFailed); + assert_err!(result.result, >::ReenteredPallet); }); } @@ -2120,67 +2027,6 @@ fn sr25519_verify() { }); } -#[test] -fn failed_deposit_charge_should_roll_back_call() { - let (wasm_caller, _) = compile_module("call_runtime_and_call").unwrap(); - let (wasm_callee, _) = compile_module("store_call").unwrap(); - const ED: u64 = 200; - - let execute = || { - ExtBuilder::default().existential_deposit(ED).build().execute_with(|| { - let _ = ::Currency::set_balance(&ALICE, 1_000_000); - - // Instantiate both contracts. - let caller = builder::bare_instantiate(Code::Upload(wasm_caller.clone())) - .build_and_unwrap_contract(); - let Contract { addr: addr_callee, .. } = - builder::bare_instantiate(Code::Upload(wasm_callee.clone())) - .build_and_unwrap_contract(); - - // Give caller proxy access to Alice. - assert_ok!(Proxy::add_proxy( - RuntimeOrigin::signed(ALICE), - caller.account_id.clone(), - (), - 0 - )); - - // Create a Proxy call that will attempt to transfer away Alice's balance. - let transfer_call = - Box::new(RuntimeCall::Balances(pallet_balances::Call::transfer_allow_death { - dest: CHARLIE, - value: pallet_balances::Pallet::::free_balance(&ALICE) - (2 * ED + 48), - })); - - // Wrap the transfer call in a proxy call. - let transfer_proxy_call = RuntimeCall::Proxy(pallet_proxy::Call::proxy { - real: ALICE, - force_proxy_type: Some(()), - call: transfer_call, - }); - - let data = ( - 1u32, // storage length - addr_callee, - transfer_proxy_call, - ); - - builder::call(caller.addr).data(data.encode()).build() - }) - }; - - // With a low enough deposit per byte, the call should succeed. - let result = execute().unwrap(); - - // Bump the deposit per byte to a high value to trigger an error - DEPOSIT_PER_BYTE.with(|c| *c.borrow_mut() = 200); - assert_err_with_weight!( - execute(), - >::StorageDepositNotEnoughFunds, - result.actual_weight - ); -} - #[test] fn upload_code_works() { let (wasm, code_hash) = compile_module("dummy").unwrap(); diff --git a/substrate/frame/revive/src/tests/precompiles.rs b/substrate/frame/revive/src/tests/precompiles.rs index 372e1c697b492..288c98ef76499 100644 --- a/substrate/frame/revive/src/tests/precompiles.rs +++ b/substrate/frame/revive/src/tests/precompiles.rs @@ -18,15 +18,19 @@ //! Precompiles added to the test runtime. use crate::{ + exec::{ErrorOrigin, ExecError}, precompiles::{AddressMatcher, Error, Ext, ExtWithInfo, Precompile, Token}, - Config, DispatchError, Weight, + Config, DispatchError, Origin, Weight, }; use alloc::vec::Vec; use alloy_core::{ sol, sol_types::{PanicKind, SolValue}, }; +use codec::Decode; use core::{marker::PhantomData, num::NonZero}; +use frame_system::RawOrigin; +use sp_runtime::traits::Dispatchable; sol! { interface IWithInfo { @@ -39,6 +43,7 @@ sol! { function panics() external; function errors() external; function consumeMaxGas() external; + function callRuntime(bytes memory call) external; } } @@ -86,6 +91,20 @@ impl Precompile for NoInfo { env.gas_meter_mut().charge(MaxGasToken)?; Ok(Vec::new()) }, + INoInfoCalls::callRuntime(INoInfo::callRuntimeCall { call }) => { + let origin = env.caller(); + let frame_origin = match origin { + Origin::Root => RawOrigin::Root.into(), + Origin::Signed(account_id) => RawOrigin::Signed(account_id.clone()).into(), + }; + + let call = ::RuntimeCall::decode(&mut &call[..]).unwrap(); + match call.dispatch(frame_origin) { + Ok(_) => Ok(Vec::new()), + Err(e) => + Err(Error::Error(ExecError { error: e.error, origin: ErrorOrigin::Caller })), + } + }, } } } diff --git a/substrate/frame/revive/src/wasm/runtime.rs b/substrate/frame/revive/src/wasm/runtime.rs index 9b858acd52549..e7d3695b7eae7 100644 --- a/substrate/frame/revive/src/wasm/runtime.rs +++ b/substrate/frame/revive/src/wasm/runtime.rs @@ -28,24 +28,16 @@ use crate::{ weights::WeightInfo, Config, Error, LOG_TARGET, SENTINEL, }; -use alloc::{boxed::Box, vec, vec::Vec}; -use codec::{Decode, DecodeLimit, Encode}; +use alloc::{vec, vec::Vec}; +use codec::Encode; use core::{fmt, marker::PhantomData, mem}; -use frame_support::{ - dispatch::DispatchInfo, ensure, pallet_prelude::DispatchResultWithPostInfo, parameter_types, - traits::Get, weights::Weight, -}; +use frame_support::{ensure, traits::Get, weights::Weight}; use pallet_revive_proc_macro::define_env; use pallet_revive_uapi::{CallFlags, ReturnErrorCode, ReturnFlags, StorageFlags}; use sp_core::{H160, H256, U256}; use sp_io::hashing::{blake2_128, blake2_256, keccak_256}; use sp_runtime::{DispatchError, RuntimeDebug}; -type CallOf = ::RuntimeCall; - -/// The maximum nesting depth a contract can use when encoding types. -const MAX_DECODE_NESTING: u32 = 256; - /// Abstraction over the memory access within syscalls. /// /// The reason for this abstraction is that we run syscalls on the host machine when @@ -117,23 +109,6 @@ pub trait Memory { self.read_into_buf(ptr, code_hash.as_bytes_mut())?; Ok(code_hash) } - - /// Read designated chunk from the sandbox memory and attempt to decode into the specified type. - /// - /// Returns `Err` if one of the following conditions occurs: - /// - /// - requested buffer is not within the bounds of the sandbox memory. - /// - the buffer contents cannot be decoded as the required type. - /// - /// # Note - /// - /// Make sure to charge a proportional amount of weight if `len` is not fixed. - fn read_as_unbounded(&self, ptr: u32, len: u32) -> Result { - let buf = self.read(ptr, len)?; - let decoded = D::decode_all_with_depth_limit(MAX_DECODE_NESTING, &mut buf.as_ref()) - .map_err(|_| DispatchError::from(Error::::DecodingFailed))?; - Ok(decoded) - } } /// Allows syscalls access to the PolkaVM instance they are executing in. @@ -218,13 +193,6 @@ impl PolkaVmInstance for polkavm::RawInstance { } } -parameter_types! { - /// Getter types used by [`crate::SyscallDoc:call_runtime`] - const CallRuntimeFailed: ReturnErrorCode = ReturnErrorCode::CallRuntimeFailed; - /// Getter types used by [`crate::SyscallDoc::xcm_execute`] - const XcmExecutionFailed: ReturnErrorCode = ReturnErrorCode::XcmExecutionFailed; -} - impl From<&ExecReturnValue> for ReturnErrorCode { fn from(from: &ExecReturnValue) -> Self { if from.flags.contains(ReturnFlags::REVERT) { @@ -394,12 +362,8 @@ pub enum RuntimeCosts { EcdsaRecovery, /// Weight of calling `seal_sr25519_verify` for the given input size. Sr25519Verify(u32), - /// Weight charged for calling into the runtime. - CallRuntime(Weight), /// Weight charged by a precompile. Precompile(Weight), - /// Weight charged for calling xcm_execute. - CallXcmExecute(Weight), /// Weight of calling `seal_set_code_hash` SetCodeHash, /// Weight of calling `ecdsa_to_eth_address` @@ -468,10 +432,7 @@ macro_rules! cost_args { impl Token for RuntimeCosts { fn influence_lowest_gas_limit(&self) -> bool { - match self { - &Self::CallXcmExecute(_) => false, - _ => true, - } + true } fn weight(&self) -> Weight { @@ -547,7 +508,7 @@ impl Token for RuntimeCosts { HashBlake128(len) => T::WeightInfo::seal_hash_blake2_128(len), EcdsaRecovery => T::WeightInfo::ecdsa_recover(), Sr25519Verify(len) => T::WeightInfo::seal_sr25519_verify(len), - Precompile(weight) | CallRuntime(weight) | CallXcmExecute(weight) => weight, + Precompile(weight) => weight, SetCodeHash => T::WeightInfo::seal_set_code_hash(), EcdsaToEthAddress => T::WeightInfo::seal_ecdsa_to_eth_address(), GetImmutableData(len) => T::WeightInfo::seal_get_immutable_data(len), @@ -724,27 +685,6 @@ impl<'a, E: Ext, M: ?Sized + Memory> Runtime<'a, E, M> { self.ext.gas_meter_mut().adjust_gas(charged, actual_costs); } - /// Charge, Run and adjust gas, for executing the given dispatchable. - fn call_dispatchable>( - &mut self, - dispatch_info: DispatchInfo, - runtime_cost: impl Fn(Weight) -> RuntimeCosts, - run: impl FnOnce(&mut Self) -> DispatchResultWithPostInfo, - ) -> Result { - use frame_support::dispatch::extract_actual_weight; - let charged = self.charge_gas(runtime_cost(dispatch_info.call_weight))?; - let result = run(self); - let actual_weight = extract_actual_weight(&result, &dispatch_info); - self.adjust_gas(charged, runtime_cost(actual_weight)); - match result { - Ok(_) => Ok(ReturnErrorCode::Success), - Err(e) => { - log::debug!(target: LOG_TARGET, "call failed with: {e:?}"); - Ok(ErrorReturnCode::get()) - }, - } - } - /// Write the given buffer and its length to the designated locations in sandbox memory and /// charge gas according to the token returned by `create_token`. /// @@ -1948,25 +1888,6 @@ pub mod env { Ok(self.ext.gas_meter().gas_left().ref_time()) } - /// Call some dispatchable of the runtime. - /// See [`frame_support::traits::call_runtime`]. - #[mutating] - fn call_runtime( - &mut self, - memory: &mut M, - call_ptr: u32, - call_len: u32, - ) -> Result { - use frame_support::dispatch::GetDispatchInfo; - self.charge_gas(RuntimeCosts::CopyFromContract(call_len))?; - let call: ::RuntimeCall = memory.read_as_unbounded(call_ptr, call_len)?; - self.call_dispatchable::( - call.get_dispatch_info(), - RuntimeCosts::CallRuntime, - |runtime| runtime.ext.call_runtime(call), - ) - } - /// Checks whether the caller of the current contract is the origin of the whole call stack. /// See [`pallet_revive_uapi::HostFn::caller_is_origin`]. fn caller_is_origin(&mut self, _memory: &mut M) -> Result { @@ -2177,80 +2098,6 @@ pub mod env { )?) } - /// Execute an XCM program locally, using the contract's address as the origin. - /// See [`pallet_revive_uapi::HostFn::execute_xcm`]. - #[mutating] - fn xcm_execute( - &mut self, - memory: &mut M, - msg_ptr: u32, - msg_len: u32, - ) -> Result { - use frame_support::dispatch::DispatchInfo; - use xcm::VersionedXcm; - use xcm_builder::{ExecuteController, ExecuteControllerWeightInfo}; - - self.charge_gas(RuntimeCosts::CopyFromContract(msg_len))?; - let message: VersionedXcm> = memory.read_as_unbounded(msg_ptr, msg_len)?; - - let execute_weight = - <::Xcm as ExecuteController<_, _>>::WeightInfo::execute(); - let weight = self.ext.gas_meter().gas_left().max(execute_weight); - let dispatch_info = DispatchInfo { call_weight: weight, ..Default::default() }; - - self.call_dispatchable::( - dispatch_info, - RuntimeCosts::CallXcmExecute, - |runtime| { - let origin = crate::RawOrigin::Signed(runtime.ext.account_id().clone()).into(); - let weight_used = <::Xcm>::execute( - origin, - Box::new(message), - weight.saturating_sub(execute_weight), - )?; - - Ok(Some(weight_used.saturating_add(execute_weight)).into()) - }, - ) - } - - /// Send an XCM program from the contract to the specified destination. - /// See [`pallet_revive_uapi::HostFn::send_xcm`]. - #[mutating] - fn xcm_send( - &mut self, - memory: &mut M, - dest_ptr: u32, - dest_len: u32, - msg_ptr: u32, - msg_len: u32, - output_ptr: u32, - ) -> Result { - use xcm::{VersionedLocation, VersionedXcm}; - use xcm_builder::{SendController, SendControllerWeightInfo}; - - self.charge_gas(RuntimeCosts::CopyFromContract(dest_len))?; - let dest: VersionedLocation = memory.read_as_unbounded(dest_ptr, dest_len)?; - - self.charge_gas(RuntimeCosts::CopyFromContract(msg_len))?; - let message: VersionedXcm<()> = memory.read_as_unbounded(msg_ptr, msg_len)?; - - let weight = <::Xcm as SendController<_>>::WeightInfo::send(); - self.charge_gas(RuntimeCosts::CallRuntime(weight))?; - let origin = crate::RawOrigin::Signed(self.ext.account_id().clone()).into(); - - match <::Xcm>::send(origin, dest.into(), message.into()) { - Ok(message_id) => { - memory.write(output_ptr, &message_id.encode())?; - Ok(ReturnErrorCode::Success) - }, - Err(e) => { - log::debug!(target: LOG_TARGET, "seal0::xcm_send failed with: {e:?}"); - Ok(ReturnErrorCode::XcmSendFailed) - }, - } - } - /// Retrieves the account id for a specified contract address. /// /// See [`pallet_revive_uapi::HostFn::to_account_id`]. diff --git a/substrate/frame/revive/uapi/src/host.rs b/substrate/frame/revive/uapi/src/host.rs index 6abc0c9c2a411..ac4e2cab791b2 100644 --- a/substrate/frame/revive/uapi/src/host.rs +++ b/substrate/frame/revive/uapi/src/host.rs @@ -480,33 +480,6 @@ pub trait HostFn: private::Sealed { #[unstable_hostfn] fn call_chain_extension(func_id: u32, input: &[u8], output: Option<&mut &mut [u8]>) -> u32; - /// Call some dispatchable of the runtime. - /// - /// # Parameters - /// - /// - `call`: The call data. - /// - /// # Return - /// - /// Returns `Error::Success` when the dispatchable was successfully executed and - /// returned `Ok`. When the dispatchable was executed but returned an error - /// `Error::CallRuntimeFailed` is returned. The full error is not - /// provided because it is not guaranteed to be stable. - /// - /// # Comparison with `ChainExtension` - /// - /// Just as a chain extension this API allows the runtime to extend the functionality - /// of contracts. While making use of this function is generally easier it cannot be - /// used in all cases. Consider writing a chain extension if you need to do perform - /// one of the following tasks: - /// - /// - Return data. - /// - Provide functionality **exclusively** to contracts. - /// - Provide custom weights. - /// - Avoid the need to keep the `Call` data structure stable. - #[unstable_hostfn] - fn call_runtime(call: &[u8]) -> Result; - /// Checks whether the caller of the current contract is the origin of the whole call stack. /// /// Prefer this over [`is_contract()`][`Self::is_contract`] when checking whether your contract @@ -708,41 +681,6 @@ pub trait HostFn: private::Sealed { /// - `output`: A reference to the output data buffer to write the weight left. #[unstable_hostfn] fn weight_left(output: &mut &mut [u8]); - - /// Execute an XCM program locally, using the contract's address as the origin. - /// This is equivalent to dispatching `pallet_xcm::execute` through call_runtime, except that - /// the function is called directly instead of being dispatched. - /// - /// # Parameters - /// - /// - `msg`: The message, should be decodable as a [VersionedXcm](https://paritytech.github.io/polkadot-sdk/master/staging_xcm/enum.VersionedXcm.html), - /// traps otherwise. - /// - `output`: A reference to the output data buffer to write the [Outcome](https://paritytech.github.io/polkadot-sdk/master/staging_xcm/v3/enum.Outcome.html) - /// - /// # Return - /// - /// Returns `Error::Success` when the XCM execution attempt is successful. When the XCM - /// execution fails, `ReturnCode::XcmExecutionFailed` is returned - #[unstable_hostfn] - fn xcm_execute(msg: &[u8]) -> Result; - - /// Send an XCM program from the contract to the specified destination. - /// This is equivalent to dispatching `pallet_xcm::send` through `call_runtime`, except that - /// the function is called directly instead of being dispatched. - /// - /// # Parameters - /// - /// - `dest`: The XCM destination, should be decodable as [VersionedLocation](https://paritytech.github.io/polkadot-sdk/master/staging_xcm/enum.VersionedLocation.html), - /// traps otherwise. - /// - `msg`: The message, should be decodable as a [VersionedXcm](https://paritytech.github.io/polkadot-sdk/master/staging_xcm/enum.VersionedXcm.html), - /// traps otherwise. - /// - /// # Return - /// - /// Returns `ReturnCode::Success` when the message was successfully sent. When the XCM - /// execution fails, `ReturnErrorCode::XcmSendFailed` is returned. - #[unstable_hostfn] - fn xcm_send(dest: &[u8], msg: &[u8], output: &mut [u8; 32]) -> Result; } mod private { diff --git a/substrate/frame/revive/uapi/src/host/riscv64.rs b/substrate/frame/revive/uapi/src/host/riscv64.rs index 40a6f61c0bf00..45da03e604720 100644 --- a/substrate/frame/revive/uapi/src/host/riscv64.rs +++ b/substrate/frame/revive/uapi/src/host/riscv64.rs @@ -137,7 +137,6 @@ mod sys { out_ptr: *mut u8, out_len_ptr: *mut u32, ) -> ReturnCode; - pub fn call_runtime(call_ptr: *const u8, call_len: u32) -> ReturnCode; pub fn sr25519_verify( signature_ptr: *const u8, pub_key_ptr: *const u8, @@ -147,14 +146,6 @@ mod sys { pub fn set_code_hash(code_hash_ptr: *const u8); pub fn ecdsa_to_eth_address(key_ptr: *const u8, out_ptr: *mut u8) -> ReturnCode; pub fn instantiation_nonce() -> u64; - pub fn xcm_execute(msg_ptr: *const u8, msg_len: u32) -> ReturnCode; - pub fn xcm_send( - dest_ptr: *const u8, - dest_len: *const u8, - msg_ptr: *const u8, - msg_len: u32, - out_ptr: *mut u8, - ) -> ReturnCode; pub fn return_data_size() -> u64; pub fn return_data_copy(out_ptr: *mut u8, out_len_ptr: *mut u32, offset: u32); } @@ -494,12 +485,6 @@ impl HostFn for HostFnImpl { unsafe { sys::call_data_copy(output.as_mut_ptr(), len, offset) }; } - #[unstable_hostfn] - fn call_runtime(call: &[u8]) -> Result { - let ret_code = unsafe { sys::call_runtime(call.as_ptr(), call.len() as u32) }; - ret_code.into() - } - #[unstable_hostfn] fn caller_is_origin() -> bool { let ret_val = unsafe { sys::caller_is_origin() }; @@ -605,24 +590,4 @@ impl HostFn for HostFnImpl { unsafe { sys::weight_left(output.as_mut_ptr(), &mut output_len) } extract_from_slice(output, output_len as usize) } - - #[unstable_hostfn] - fn xcm_execute(msg: &[u8]) -> Result { - let ret_code = unsafe { sys::xcm_execute(msg.as_ptr(), msg.len() as _) }; - ret_code.into() - } - - #[unstable_hostfn] - fn xcm_send(dest: &[u8], msg: &[u8], output: &mut [u8; 32]) -> Result { - let ret_code = unsafe { - sys::xcm_send( - dest.as_ptr(), - dest.len() as _, - msg.as_ptr(), - msg.len() as _, - output.as_mut_ptr(), - ) - }; - ret_code.into() - } } diff --git a/substrate/frame/revive/uapi/src/lib.rs b/substrate/frame/revive/uapi/src/lib.rs index f52e72ebc9399..66cf4ffcd6ded 100644 --- a/substrate/frame/revive/uapi/src/lib.rs +++ b/substrate/frame/revive/uapi/src/lib.rs @@ -105,16 +105,10 @@ define_error_codes! { TransferFailed = 4, /// The subcall ran out of weight or storage deposit. OutOfResources = 5, - /// The call dispatched by `call_runtime` was executed but returned an error. - CallRuntimeFailed = 6, /// ECDSA public key recovery failed. Most probably wrong recovery id or signature. EcdsaRecoveryFailed = 7, /// sr25519 signature verification failed. Sr25519VerifyFailed = 8, - /// The `xcm_execute` call failed. - XcmExecutionFailed = 9, - /// The `xcm_send` call failed. - XcmSendFailed = 10, /// Contract instantiation failed because the address already exists. /// Occurs when instantiating the same contract with the same salt more than once. DuplicateContractAddress = 11, diff --git a/umbrella/Cargo.toml b/umbrella/Cargo.toml index 736d40c411c1a..3380a01205ff1 100644 --- a/umbrella/Cargo.toml +++ b/umbrella/Cargo.toml @@ -124,7 +124,6 @@ std = [ "pallet-recovery?/std", "pallet-referenda?/std", "pallet-remark?/std", - "pallet-revive-mock-network?/std", "pallet-revive?/std", "pallet-root-offences?/std", "pallet-root-testing?/std", @@ -306,7 +305,6 @@ runtime-benchmarks = [ "pallet-recovery?/runtime-benchmarks", "pallet-referenda?/runtime-benchmarks", "pallet-remark?/runtime-benchmarks", - "pallet-revive-mock-network?/runtime-benchmarks", "pallet-revive?/runtime-benchmarks", "pallet-root-offences?/runtime-benchmarks", "pallet-safe-mode?/runtime-benchmarks", @@ -439,7 +437,6 @@ try-runtime = [ "pallet-recovery?/try-runtime", "pallet-referenda?/try-runtime", "pallet-remark?/try-runtime", - "pallet-revive-mock-network?/try-runtime", "pallet-revive?/try-runtime", "pallet-root-offences?/try-runtime", "pallet-root-testing?/try-runtime", @@ -854,7 +851,6 @@ node = [ "mmr-rpc", "pallet-contracts-mock-network", "pallet-revive-eth-rpc", - "pallet-revive-mock-network", "pallet-transaction-payment-rpc", "parachains-runtimes-test-utils", "polkadot-approval-distribution", @@ -2262,11 +2258,6 @@ default-features = false optional = true path = "../substrate/frame/revive/rpc" -[dependencies.pallet-revive-mock-network] -default-features = false -optional = true -path = "../substrate/frame/revive/mock-network" - [dependencies.pallet-transaction-payment-rpc] default-features = false optional = true diff --git a/umbrella/src/lib.rs b/umbrella/src/lib.rs index fde520b937c00..955a17d6b6546 100644 --- a/umbrella/src/lib.rs +++ b/umbrella/src/lib.rs @@ -612,10 +612,6 @@ pub use pallet_revive; #[cfg(feature = "pallet-revive-eth-rpc")] pub use pallet_revive_eth_rpc; -/// A mock network for testing pallet-revive. -#[cfg(feature = "pallet-revive-mock-network")] -pub use pallet_revive_mock_network; - /// Procedural macros used in pallet_revive. #[cfg(feature = "pallet-revive-proc-macro")] pub use pallet_revive_proc_macro;